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    /// The underlying scalar the payload-carrying arm carries — the
1391    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1392    /// subject ([`Self::PubSub`] `:subject`), or slot template
1393    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1394    /// `&'a str` storage — or `None` on the payload-less
1395    /// [`Self::Capability`] arm.
1396    ///
1397    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1398    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1399    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1400    /// the paired sub-selector axis. Both per-half accessors read from
1401    /// one authoritative match, so a future [`WitTarget`] variant
1402    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1403    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1404    /// on [`Self::payload_pair`] and both per-half projections + every
1405    /// downstream consumer picks the new arm up by construction — no
1406    /// coordinated N-way rewrite across the paired accessor dispatches,
1407    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1408    /// and every future WIT-registry-shaped consumer.
1409    ///
1410    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1411    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1412    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1413    /// both per-half projections as thin readers, every downstream
1414    /// consumer through the same match" discipline extended onto the
1415    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1416    /// gap between the two paired-dispatch surfaces: the peer
1417    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1418    /// the first-component projection until this lift; the second-
1419    /// component sibling now sits alongside so both halves reach every
1420    /// future consumer through the same substrate-primitive dispatch.
1421    ///
1422    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1423    #[must_use]
1424    pub const fn payload(&self) -> Option<&'a str> {
1425        match self.payload_pair() {
1426            Some((_, p)) => Some(p),
1427            None => None,
1428        }
1429    }
1430
1431    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1432    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1433    /// returns the [`Self::Http`]-arm's author-declared request path
1434    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1435    /// projected target is [`Self::Http { endpoint }`], `None` on the
1436    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1437    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1438    /// definition).
1439    ///
1440    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1441    /// `path:` rule payload every substrate-side L7-introspecting
1442    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1443    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1444    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1445    /// on the L7 introspection branch; every peer WIT shape stays
1446    /// L4-only because Cilium can't introspect NATS / key-value / plain
1447    /// capability edges), and every future L7-introspecting consumer
1448    /// of the projected target's HTTP endpoint (the future M4
1449    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1450    /// materializer's per-edge L7 admission-webhook overlay, the
1451    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1452    /// path bucket-key resolver, the future per-`:contratos`-edge
1453    /// mTLS-required overlay's HTTP-shape scope filter, the future
1454    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1455    /// through the same typed dispatch.
1456    ///
1457    /// Prior to this lift the sole production consumer of the projected-
1458    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1459    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1460    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1461    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1462    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1463    /// match that expressed no compile-time link back to the substrate
1464    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1465    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1466    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1467    /// with no post-projection peer on the typed-view surface. A future
1468    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1469    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1470    /// gRPC-shaped worlds per this enum's own docstring at
1471    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1472    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1473    /// would have had to be threaded through the caixa-mesh L7 emit
1474    /// branch's raw `if let` in lockstep — either coalescing the two
1475    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1476    /// emit path per-arm — with no substrate-primitive dispatch making
1477    /// the "which arms count as L7-HTTP-shaped for path-emission
1478    /// purposes" question the substrate's answer to give. Lifting the
1479    /// resolution to a typed method on the substrate primitive means
1480    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1481    /// projected-target HTTP endpoint reaches for exactly one typed
1482    /// dispatch — the resolver's accept-set migrates as a unit on any
1483    /// future arm-family widening, and the caixa-mesh L7 emit branch
1484    /// reads through the same substrate primitive.
1485    ///
1486    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1487    /// (7020470) `Option<&str>` scalar accessor on the raw
1488    /// `:contratos :endpoint` field-access axis — same "one typed
1489    /// dispatch on the substrate primitive, thin projections at each
1490    /// consumer" discipline extended onto the peer post-projection typed-
1491    /// view surface (the [`WitContract::endpoint`] pre-projection
1492    /// accessor returns `Some` for any author-declared `:endpoint`
1493    /// value regardless of the paired `:wit` world's HTTP-shape
1494    /// classification — the raw slot before validation crosses it —
1495    /// while this post-projection [`Self::http_endpoint`] accessor
1496    /// returns `Some` iff the target has been projected onto the
1497    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1498    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1499    /// coherence; the two accessors close the pre-projection /
1500    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1501    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1502    /// the three payload-carrying arms) — extends the per-arm
1503    /// projection family onto the [`Self::Http`] specialization axis
1504    /// that the pan-arm accessor's shape blends into a single arm-
1505    /// agnostic view; leaves the [`Self::pubsub_subject`] /
1506    /// [`Self::store_slot`] peer per-arm projections as the two future
1507    /// per-arm axes future compounding runs fold on once a per-arm
1508    /// pub-sub / store-shape consumer lands.
1509    #[must_use]
1510    pub const fn http_endpoint(&self) -> Option<&'a str> {
1511        match *self {
1512            WitTarget::Http { endpoint } => Some(endpoint),
1513            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1514        }
1515    }
1516
1517    /// Render this typed target as a stable human-readable label
1518    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1519    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1520    /// the WIT world is a pure capability edge).
1521    ///
1522    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1523    /// gate so the diagnostic names *which* identical edge was
1524    /// declared twice (not just which `(de, para, wit)` triple).
1525    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1526    /// on the payload-carrying arms (`Some((field, payload)) →
1527    /// format!(":{field} {payload:?}")`) and through the lifted
1528    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1529    /// [`Self::Capability`] arm — so a future variant addition (the
1530    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1531    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1532    /// `Queue`-shaped peer) becomes a single new match-arm on
1533    /// [`Self::payload_pair`] rather than a rewrite of this template
1534    /// (and every downstream consumer that reaches for the label
1535    /// shape: the per-edge policy resolver in M4, the `feira app
1536    /// graph` view, the operator's mesh-graph audit). Until this
1537    /// lift landed the three payload arms carried three near-identical
1538    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1539    /// [`Self::Capability`] arm carried the payload-less byte-string
1540    /// twice (once inline here, once in the pin test) — closing the
1541    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1542    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1543    /// / 4a1e490) peer-const lifts already established for the
1544    /// payload-carrying arms.
1545    #[must_use]
1546    pub fn label(&self) -> String {
1547        match self.payload_pair() {
1548            Some((field, payload)) => format!(":{field} {payload:?}"),
1549            None => Self::CAPABILITY_LABEL.to_string(),
1550        }
1551    }
1552
1553    /// Render this typed target as the `feira app graph` per-`:contratos`
1554    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
1555    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
1556    /// payload-less arm).
1557    ///
1558    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1559    /// on the payload-carrying arms (`Some((field, payload)) →
1560    /// format!("{field}={payload}")`) and through the lifted
1561    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
1562    /// [`Self::Capability`] arm — so a future variant addition
1563    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
1564    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1565    /// `Queue`-shaped peer) becomes one match-arm edit at
1566    /// [`Self::payload_pair`], propagating through this graph-verb
1567    /// projection at zero call-site cost, sibling to the peer
1568    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
1569    /// same 4-arm dispatch.
1570    ///
1571    /// Until this lift landed the [`caixa-feira`]
1572    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
1573    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
1574    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
1575    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
1576    /// `format!("{}={endpoint}", ...)` template and hard-coding
1577    /// `"(capability-only)"` as a fifth payload-less scalar with no link
1578    /// back to the paired [`WitTarget::Capability`] variant declaration.
1579    /// A future variant addition would have had to be threaded through
1580    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
1581    /// verb's inline match in lockstep or the two projections would
1582    /// silently disagree on the arm-set the graph verb prints — the
1583    /// duplicate-`:contratos` diagnostic reading one shape while the
1584    /// graph verb's payload column silently dropped the new arm to
1585    /// `(capability-only)`. Lifting the graph-verb projection onto the
1586    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
1587    /// the axis: both projections migrate as a unit.
1588    ///
1589    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
1590    /// quoting) shape is graph-verb-canonical — distinct from the
1591    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
1592    /// duplicate-`:contratos` diagnostic seeds (see
1593    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
1594    /// on the payload-less axis for the paired distinction).
1595    #[must_use]
1596    pub fn graph_label(&self) -> String {
1597        match self.payload_pair() {
1598            Some((field, payload)) => format!("{field}={payload}"),
1599            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
1600        }
1601    }
1602}
1603
1604/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1605/// pretty-printed byte-string every consumer that formats a typed
1606/// payload target as user-facing text lands on (the
1607/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1608/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1609/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1610/// graph` per-`:contratos`-edge payload column that reaches the graph
1611/// verb through `format!("{target}")`, the future M4 per-edge policy
1612/// resolver's per-edge audit-log line, the operator's mesh-graph
1613/// per-edge inspection view) reaches for the same lifted
1614/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1615/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1616/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1617/// routes through — extending the three-path-convergence
1618/// (`Debug` for structural inspection, `Display` for user-facing text,
1619/// per-arm typed accessor for the canonical byte-string) discipline the
1620/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1621/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1622/// onto the fourth (and only remaining) typed-shape-discriminator axis
1623/// on the caixa surface.
1624///
1625/// Pre-lift the two paths were structurally independent — every consumer
1626/// reaching for a payload byte-string past the [`WitTarget::label`]
1627/// helper had to pick between three paths ([`WitTarget::label`],
1628/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1629/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1630/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1631/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1632/// that reached for `format!("{target}")` — the canonical shape every
1633/// user-facing pretty-print site on the sibling typed-enum axes already
1634/// uses — would silently land on the `Debug` derive's structural output
1635/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1636/// than the `label()` helper's stable byte-string (`:endpoint
1637/// "/charge"` — the author-facing `:contratos` keyword form) the
1638/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1639/// already threads through. The two spellings would diverge silently in
1640/// every downstream diagnostic / graph / audit line reached through
1641/// `format!` rather than through the `label()` helper. Routing
1642/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1643/// path: every `format!("{v}")` call reaches the same
1644/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1645/// and the duplicate-`:contratos` gate already route through, so a
1646/// future variant addition (the M4-and-later per-edge WIT registry may
1647/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1648/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1649/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1650/// match — rather than fanning out through hand-rolled per-arm
1651/// [`std::fmt::Display`] arms.
1652///
1653/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1654/// is the typed view returned by [`WitContract::target`], not a
1655/// closed-set discriminator enum with a gen-platform Discriminant
1656/// registration, so the `Debug` derive's structural output (which every
1657/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1658/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1659/// shape for structural inspection; `Display` (via `label`) reveals the
1660/// stable author-facing payload projection.
1661///
1662/// Pin tests
1663/// [`tests::wit_target_display_routes_through_label_helper`] and
1664/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1665/// assert the two paths agree byte-for-byte on every variant, so a
1666/// future variant addition or `label()` reimplementation that hand-rolls
1667/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1668/// build error visible at caixa-core test time, not a silent
1669/// per-consumer dispatch miss at diagnostic / audit / graph time.
1670impl std::fmt::Display for WitTarget<'_> {
1671    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1672        f.write_str(&self.label())
1673    }
1674}
1675
1676// ── one Aplicacao member ─────────────────────────────────────────────
1677
1678/// A Servico participating in the Aplicacao. Same shape as
1679/// `crate::supervisor::ChildSpec` but without a restart policy —
1680/// supervision is per-Servico (each member has its own
1681/// `:supervisor`), the Aplicacao orchestrates *placement*.
1682#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1683#[serde(rename_all = "camelCase")]
1684pub struct Membro {
1685    /// Member caixa's `:nome`. Resolves through the same dep
1686    /// resolution path as `crate::dep::Dep`.
1687    pub caixa: String,
1688
1689    /// Semver constraint.
1690    pub versao: String,
1691}
1692
1693impl Membro {
1694    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1695    /// accessor every consumer that reads the member's Servico identity
1696    /// keys off — returns the author-declared `:membros :caixa`
1697    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1698    /// own [`String`] storage.
1699    ///
1700    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1701    /// participating in the Aplicacao — validated by
1702    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1703    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1704    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1705    /// [`validate_no_self_membership`]) — and every downstream consumer
1706    /// that fans on the member's identity keys off this scalar (the
1707    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1708    /// lookup, the per-`:membros` duplicate gate's dedup key, the
1709    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1710    /// identity, the self-membership gate, the
1711    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1712    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1713    /// CR materializer's per-member resolver).
1714    ///
1715    /// Prior to this lift the `.caixa` byte-string was read inline at
1716    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1717    /// set collector at
1718    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1719    /// [`validate_membros`] validation-side member-caixa gate at
1720    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1721    /// per-member duplicate-gate dedup key at
1722    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1723    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1724    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1725    /// [`validate_no_self_membership`] self-loop gate at
1726    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1727    /// expressed no compile-time link back to the typed slot. Every
1728    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1729    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1730    /// `name:` axis, so a future extension of the `:membros :caixa`
1731    /// axis to a richer author surface — a per-cluster alias table the
1732    /// operator pins through a future `:placement`-scoped slot, a
1733    /// namespace-qualified rewrite the M4 CR materializer applies
1734    /// per-CR, a per-member overlay from the future `:membros
1735    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1736    /// acknowledges — would have had to be threaded through every
1737    /// open-coded copy in lockstep or one consumer would silently
1738    /// disagree with the peers on which caixa a given member resolves
1739    /// to. A member-set lookup that treated the name as `"cart"` while
1740    /// the peer adjacency map treated it as `"tenant-a/cart"` would
1741    /// silently split the `:contratos` membership-lookup diagnostic from
1742    /// the cycle-detector's node identity — a two-consumer split at the
1743    /// validator far from the source `caixa.lisp` with no field naming
1744    /// the identity-drift root cause. Lifting the resolution rule to a
1745    /// typed method on the substrate primitive means every downstream
1746    /// consumer of the Aplicacao's per-`:membros` identity surface
1747    /// reaches for exactly one typed dispatch — the resolver's
1748    /// accept-set migrates as a unit on any future axis addition.
1749    ///
1750    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1751    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1752    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1753    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1754    /// destination-Servico scalar accessors — same "one typed dispatch
1755    /// on the substrate primitive, thin projections at each consumer"
1756    /// discipline extended onto the per-`:membros` member-caixa `:nome`
1757    /// byte-string axis. Named `nome()` to match the tatara-lisp
1758    /// author-surface term the field's docstring already reaches for
1759    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1760    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1761    /// already carries — the accessor's name maps directly onto the
1762    /// canonical caixa-identity vocabulary rather than shadowing the
1763    /// field's storage-side `caixa` label.
1764    #[must_use]
1765    pub fn nome(&self) -> &str {
1766        self.caixa.as_str()
1767    }
1768
1769    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
1770    /// requirement scalar accessor every consumer that reads the
1771    /// member's version pin keys off — returns the author-declared
1772    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
1773    /// from the typed slot's own [`String`] storage.
1774    ///
1775    /// The `:membros :versao` slot carries the Cargo-shaped semver
1776    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
1777    /// pins which release of the member-caixa the Aplicacao composes
1778    /// against — the same requirement grammar the peer `:deps :versao`
1779    /// / `:children :versao` axes carry, resolved through the shared
1780    /// [`crate::render::require_valid_versao_requirement`] cascade and
1781    /// the shared [`crate::version::parse_requirement`] parser. Every
1782    /// downstream consumer that fans on the member's version pin keys
1783    /// off this scalar (the [`validate_membros`] per-member requirement
1784    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
1785    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
1786    /// m.nome(), m.versao_requirement())` line, every future per-cluster
1787    /// version-lock overlay the operator pins through a future
1788    /// `:placement`-scoped slot, the future
1789    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
1790    /// version resolver, the future `feira app deploy` pipeline's
1791    /// per-member lacre BLAKE3-closure lookup).
1792    ///
1793    /// Prior to this lift the `.versao` byte-string was accessed inline
1794    /// at two `&str`-shaped sites — the [`validate_membros`]
1795    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
1796    /// …)` and the `feira app graph` per-member printer's `println!(
1797    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
1798    /// prior to this lift) — two open-coded field-accesses that expressed
1799    /// no compile-time link back to the typed slot. A future extension of
1800    /// the `:membros :versao` axis to a richer author surface (a
1801    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1802    /// flow, a lacre-projected concrete-version rewrite the operator
1803    /// materializes at CR-admission time, a future `:membros :versao-lock`
1804    /// per-cluster override slot) would have had to be threaded through
1805    /// every open-coded copy in lockstep or one consumer would silently
1806    /// disagree with the peers on which release constraint a given
1807    /// member resolves to. Lifting the resolution rule to a typed method
1808    /// on the substrate primitive means every downstream requirement-
1809    /// facing consumer reaches for exactly one typed dispatch — the
1810    /// resolver's accept-set migrates as a unit on any future axis
1811    /// addition.
1812    ///
1813    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
1814    /// member-caixa `:nome` scalar accessor — the pair
1815    /// `(nome(), versao_requirement())` jointly projects the
1816    /// `(caixa, versao)` field pair every renderer that fans on
1817    /// per-member identity + version pin keys off, closing the last
1818    /// unlifted per-`:membros` scalar axis so every downstream
1819    /// per-`:membros` reader now routes through a typed dispatch on the
1820    /// substrate primitive. Named `versao_requirement()` rather than
1821    /// `versao()` because the field's storage-side `.versao` label is
1822    /// already the author-surface term (`:versao`); the accessor's name
1823    /// carries the semantic role — the semver *requirement* string the
1824    /// shared [`crate::version::parse_requirement`] entry-point consumes
1825    /// — so a raw field access and a typed dispatch read differently at
1826    /// every consumer site.
1827    ///
1828    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1829    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1830    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1831    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1832    /// destination-Servico scalar accessors — same "one typed dispatch
1833    /// on the substrate primitive, thin projections at each consumer"
1834    /// discipline extended onto the per-`:membros` member-`:versao`
1835    /// semver-requirement byte-string axis.
1836    #[must_use]
1837    pub fn versao_requirement(&self) -> &str {
1838        self.versao.as_str()
1839    }
1840}
1841
1842// ── mesh-level policies ──────────────────────────────────────────────
1843
1844/// Mesh policies that apply to every `:contratos` edge unless
1845/// overridden per-edge in M4. V0 is a single global policy block.
1846#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
1847#[serde(rename_all = "camelCase")]
1848pub struct MeshPolicy {
1849    /// Per-call timeout. Authored as a duration string (`"30s"`).
1850    #[serde(
1851        default,
1852        skip_serializing_if = "Option::is_none",
1853        with = "supervisor::duration_codec"
1854    )]
1855    pub timeout: Option<Duration>,
1856
1857    /// Number of retries on transient failure. None = no retries.
1858    #[serde(default, skip_serializing_if = "Option::is_none")]
1859    pub retries: Option<u32>,
1860
1861    /// Circuit breaker config. Trips after N failures within W
1862    /// duration; closes after a cooldown.
1863    #[serde(default, skip_serializing_if = "Option::is_none")]
1864    pub circuit_breaker: Option<CircuitBreaker>,
1865
1866    /// Whether mTLS is required for every contrato. Default: true
1867    /// (sandboxing-by-default; explicit opt-out only).
1868    #[serde(default, skip_serializing_if = "Option::is_none")]
1869    pub mtls_required: Option<bool>,
1870
1871    /// Token-bucket rate limit. Authored as `"100/s"` or
1872    /// `"5000/m"`; stored as `(rate, window)`.
1873    #[serde(
1874        default,
1875        skip_serializing_if = "Option::is_none",
1876        with = "rate_limit_codec"
1877    )]
1878    pub rate_limit: Option<RateLimit>,
1879}
1880
1881impl MeshPolicy {
1882    /// True when no `:politicas` axis carries a value — every field is
1883    /// `None`. The same emptiness contract every other M2/M3 typed
1884    /// surface carries ([`crate::LimitsSpec::is_empty`],
1885    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
1886    /// typed slot onto a cluster artifact key off this predicate to
1887    /// decide "emit the slot" vs "skip the slot entirely", so an
1888    /// authored-but-unset `:politicas (())` round-trips to a rendered
1889    /// artifact that's structurally identical to one that omits the
1890    /// slot. Lifted as a typed predicate (rather than per-renderer
1891    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
1892    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
1893    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
1894    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
1895    /// not a coordinated rewrite of every consumer that's reaching
1896    /// for the emptiness semantic.
1897    #[must_use]
1898    pub const fn is_empty(&self) -> bool {
1899        self.timeout().is_none()
1900            && self.retries().is_none()
1901            && self.circuit_breaker().is_none()
1902            && self.mtls_required().is_none()
1903            && self.rate_limit().is_none()
1904    }
1905
1906    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
1907    /// per-call-deadline scalar accessor every consumer of the
1908    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
1909    /// returns the author-declared `:politicas :timeout` typed
1910    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
1911    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
1912    /// is `Copy`, so the accessor returns by value; no borrow of
1913    /// `&self` past the call). `None` when the slot is absent (the
1914    /// "cluster default applies — typically the gateway class's
1915    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
1916    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
1917    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
1918    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
1919    /// round-trips to a rendered `HTTPRoute` structurally identical to
1920    /// one that omits the slot).
1921    ///
1922    /// The `:politicas :timeout` slot carries the "no infinite blocking"
1923    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
1924    /// the typed slot's `Option<Duration>` accept-set (zero-floor
1925    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
1926    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
1927    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
1928    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
1929    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
1930    /// Every downstream consumer that reads the per-call cap keys off
1931    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1932    /// renderers key off to decide "emit :politicas overlay" vs "skip
1933    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1934    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
1935    /// fans the deadline into every rule via
1936    /// [`crate::render::single_field_overlay`], the future M4 per-
1937    /// Aplicacao Gateway API reconciler materialization pass, the
1938    /// future per-`:contratos`-edge timeout-override overlay the
1939    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
1940    ///
1941    /// Prior to this lift the `.timeout` field was accessed inline at
1942    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
1943    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
1944    /// …)` call — two open-coded field-accesses that expressed no
1945    /// compile-time link back to the typed slot. A future extension of
1946    /// the `:politicas :timeout` axis to a richer author surface — a
1947    /// per-`:contratos`-edge timeout override the operator pins through
1948    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
1949    /// roadmap acknowledges, a per-cluster timeout-default overlay the
1950    /// M4 CR materializer resolves per-CR, a split of the single
1951    /// per-call `Duration` into a richer `{request, backendRequest}`
1952    /// pair once the Gateway API's per-rule `timeouts` block grows the
1953    /// upstream-facing backendRequest arm alongside the client-facing
1954    /// request arm — would have had to be threaded through both open-
1955    /// coded copies in lockstep or the emptiness predicate and the
1956    /// caixa-mesh emit path would silently disagree on which per-call
1957    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
1958    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
1959    /// == false` while the renderer's overlay-emit path silently read
1960    /// a drifted other value, or vice versa: an author's `:timeout
1961    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
1962    /// the emptiness predicate still classified the policy as non-
1963    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
1964    /// | grep -A2 timeouts` audit would land on a route whose author's
1965    /// typed slot value silently vanished at the renderer layer).
1966    /// Lifting the resolution to a typed method on the substrate
1967    /// primitive means every downstream consumer of the Aplicacao's
1968    /// per-`:politicas` deadline surface reaches for exactly one typed
1969    /// dispatch — the resolver's accept-set migrates as a unit on any
1970    /// future axis addition.
1971    ///
1972    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
1973    /// family (sibling of the peer per-`:politicas`
1974    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
1975    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
1976    /// `Option<bool>` accessor — same "one typed dispatch on the
1977    /// substrate primitive, thin projections at each consumer"
1978    /// discipline extended onto the peer per-`:politicas` typed-
1979    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
1980    /// numeric-Copy-T scalar" projection pattern the sibling
1981    /// `Option<u32>` / `Option<bool>` lifts opened, since every
1982    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
1983    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
1984    /// than a scalar). Named `timeout()` to match the storage field's
1985    /// name; the accessor's identity maps onto the canonical MESH-
1986    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
1987    #[must_use]
1988    pub const fn timeout(&self) -> Option<Duration> {
1989        self.timeout
1990    }
1991
1992    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
1993    /// retry-budget scalar accessor every consumer of the Aplicacao's
1994    /// Gateway API v1.x per-rule retry-cap keys off — returns the
1995    /// author-declared `:politicas :retries` typed `u32` verbatim as an
1996    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
1997    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
1998    /// value; no borrow of `&self` past the call). `None` when the slot
1999    /// is absent (the "cluster default applies — typically 'no retries
2000    /// beyond a single dispatch attempt'" arm the caixa-mesh
2001    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2002    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2003    /// this predicate too, so an authored-but-unset `:politicas
2004    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2005    /// identical to one that omits the slot).
2006    ///
2007    /// The `:politicas :retries` slot carries the "transient failure
2008    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2009    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2010    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2011    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2012    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2013    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2014    /// Every downstream consumer that reads the retry cap keys off this
2015    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2016    /// renderers key off to decide "emit :politicas overlay" vs "skip
2017    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2018    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2019    /// the value into every rule via [`crate::render::single_field_overlay`],
2020    /// the future M4 per-Aplicacao Gateway API reconciler
2021    /// materialization pass, the future per-`:contratos`-edge retry-
2022    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2023    /// acknowledges).
2024    ///
2025    /// Prior to this lift the `.retries` field was accessed inline at
2026    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2027    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2028    /// …)` call — two open-coded field-accesses that expressed no
2029    /// compile-time link back to the typed slot. A future extension of
2030    /// the `:politicas :retries` axis to a richer author surface — a
2031    /// per-`:contratos`-edge retry override the operator pins through a
2032    /// future `:contratos :retries` slot, a per-cluster retry-default
2033    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2034    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2035    /// backoff}` sub-block once the Gateway API grows the peer
2036    /// `retry.codes` / `retry.backoff` axes — would have had to be
2037    /// threaded through both open-coded copies in lockstep or the
2038    /// emptiness predicate and the caixa-mesh emit path would silently
2039    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2040    /// (a `:politicas` block whose only axis is a `Some :retries` would
2041    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2042    /// path silently read a drifted other value, or vice versa: an
2043    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2044    /// block while the emptiness predicate still classified the policy
2045    /// as non-empty). Lifting the resolution to a typed method on the
2046    /// substrate primitive means every downstream consumer of the
2047    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2048    /// one typed dispatch — the resolver's accept-set migrates as a
2049    /// unit on any future axis addition.
2050    ///
2051    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2052    /// family (sibling of the peer per-`:politicas`
2053    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2054    /// same "one typed dispatch on the substrate primitive, thin
2055    /// projections at each consumer" discipline extended onto the
2056    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2057    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2058    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2059    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2060    /// fold on). Named `retries()` to match the storage field's name;
2061    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2062    /// §III.2 vocabulary the slot's docstring already carries.
2063    #[must_use]
2064    pub const fn retries(&self) -> Option<u32> {
2065        self.retries
2066    }
2067
2068    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2069    /// enforcement-toggle scalar accessor every consumer of the
2070    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2071    /// — returns the author-declared `:politicas :mtls-required` typed
2072    /// bool verbatim as an `Option<bool>`, copied out of the typed
2073    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2074    /// the accessor returns by value; no borrow of `&self` past the
2075    /// call). `None` when the slot is absent (the "cluster default
2076    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2077    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2078    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2079    /// this predicate too, so an authored-but-unset `:politicas
2080    /// (:mtls-required ())` round-trips to a rendered
2081    /// `CiliumNetworkPolicy` structurally identical to one that omits
2082    /// the slot).
2083    ///
2084    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2085    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2086    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2087    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2088    /// Cilium `authentication.mode` bijection through
2089    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2090    /// handshake enforced), `Some(false) → "disabled"` (handshake
2091    /// skipped — the debug-edge opt-out), `None` → omit the block
2092    /// (cluster default applies). Every downstream consumer that
2093    /// reads the toggle keys off this scalar (the
2094    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2095    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2096    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2097    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2098    /// ingress rule via [`crate::render::single_field_overlay`], the
2099    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2100    /// materialization pass, the future per-`:contratos`-edge mTLS
2101    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2102    ///
2103    /// Prior to this lift the `.mtls_required` field was accessed
2104    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2105    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2106    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2107    /// two open-coded field-accesses that expressed no compile-time
2108    /// link back to the typed slot. A future extension of the
2109    /// `:politicas :mtls-required` axis to a richer author surface —
2110    /// a per-`:contratos`-edge mTLS override the operator pins through
2111    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2112    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2113    /// M4 CR materializer resolves per-CR, a three-valued
2114    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2115    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2116    /// would have had to be threaded through both open-coded copies in
2117    /// lockstep or the emptiness predicate and the caixa-mesh emit
2118    /// path would silently disagree on which toggle a given
2119    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2120    /// axis is a `Some`
2121    /// `:mtls-required` would satisfy `is_empty() == false` while the
2122    /// renderer's overlay-emit path silently read a drifted other
2123    /// value, or vice versa). Lifting the resolution to a typed method
2124    /// on the substrate primitive means every downstream consumer of
2125    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2126    /// for exactly one typed dispatch — the resolver's accept-set
2127    /// migrates as a unit on any future axis addition.
2128    ///
2129    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2130    /// family (peer of the sibling per-`:placement`
2131    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2132    /// same "one typed dispatch on the substrate primitive, thin
2133    /// projections at each consumer" discipline extended onto the
2134    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2135    /// the "optional per-slot Copy-T scalar" projection pattern the
2136    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2137    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2138    /// `mtls_required()` to match the storage field's name; the
2139    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2140    /// §III.2 vocabulary the slot's docstring already carries.
2141    #[must_use]
2142    pub const fn mtls_required(&self) -> Option<bool> {
2143        self.mtls_required
2144    }
2145
2146    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2147    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2148    /// accessor every consumer of the Aplicacao's per-`:politicas`
2149    /// per-`(rate, window)` rate-limit surface keys off — returns the
2150    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2151    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2152    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2153    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2154    /// past the call). `None` when the slot is absent (the "cluster
2155    /// default applies — typically 'no per-Aplicacao rate declaration,
2156    /// gateway-class per-listener default applies'" arm the future
2157    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2158    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2159    /// `rate_limit().is_none()` arm reads this predicate too, so an
2160    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2161    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2162    /// identical to one that omits the slot).
2163    ///
2164    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2165    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2166    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2167    /// (rate lower-bounded by 1 through
2168    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2169    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2170    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2171    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2172    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2173    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2174    /// `:politicas` overlay emits. Every downstream consumer that
2175    /// reads the rate declaration keys off this scalar (the
2176    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2177    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2178    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2179    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2180    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2181    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2182    /// the future per-`:contratos`-edge rate-limit override the
2183    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2184    ///
2185    /// Prior to this lift the `.rate_limit` field was accessed inline
2186    /// at two sites — [`MeshPolicy::is_empty`]'s
2187    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2188    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2189    /// field-accesses that expressed no compile-time link back to the
2190    /// typed slot. A future extension of the `:politicas :rate-limit`
2191    /// axis to a richer author surface — a per-`:contratos`-edge
2192    /// rate-limit override the operator pins through a future
2193    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2194    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2195    /// the M4 CR materializer resolves per-CR, a promotion of the
2196    /// plain `(rate, window)` scalar pair to a richer
2197    /// `{rate, window, burst, key}` sub-block once Envoy's
2198    /// `local_rate_limit` grows the peer `burst_size` /
2199    /// `descriptor_key` axes — would have had to be threaded through
2200    /// both open-coded copies in lockstep or the emptiness predicate
2201    /// and the validate gate would silently disagree on which rate
2202    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2203    /// block whose only axis is a `Some :rate-limit` would satisfy
2204    /// `is_empty() == false` while the validate path silently read a
2205    /// drifted other value, or vice versa: an author's
2206    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2207    /// emptiness predicate still classified the policy as non-empty).
2208    /// Lifting the resolution to a typed method on the substrate
2209    /// primitive means every downstream consumer of the Aplicacao's
2210    /// per-`:politicas` rate-limit surface reaches for exactly one
2211    /// typed dispatch — the resolver's accept-set migrates as a unit
2212    /// on any future axis addition.
2213    ///
2214    /// First `Option<Copy-composite-T>`-return accessor on the M3
2215    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2216    /// scalar-value axis. Peer of the sibling per-`:politicas`
2217    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2218    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2219    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2220    /// "one typed dispatch on the substrate primitive, thin
2221    /// projections at each consumer" discipline extended onto the
2222    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2223    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2224    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2225    /// sub-accessors rather than a top-level accessor because
2226    /// consumers reach for the axes not the aggregate). Named
2227    /// `rate_limit()` to match the storage field's name; the
2228    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2229    /// §III.2 vocabulary the slot's docstring already carries.
2230    #[must_use]
2231    pub const fn rate_limit(&self) -> Option<RateLimit> {
2232        self.rate_limit
2233    }
2234
2235    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2236    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2237    /// declaration scalar accessor every consumer of the Aplicacao's
2238    /// per-`:politicas` breaker declaration keys off — returns the
2239    /// author-declared `:politicas :circuit-breaker` typed
2240    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2241    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2242    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2243    /// by value; no borrow of `&self` past the call). `None` when the
2244    /// slot is absent (the "cluster default applies — typically 'no
2245    /// per-Aplicacao breaker declaration, gateway-class per-listener
2246    /// default applies'" arm the future caixa-mesh
2247    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2248    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2249    /// arm reads this predicate too, so an authored-but-unset
2250    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2251    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2252    /// that omits the slot).
2253    ///
2254    /// The `:politicas :circuit-breaker` slot carries the
2255    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2256    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2257    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2258    /// zero-floor rejected through
2259    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2260    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2261    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2262    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2263    /// canonical-form pinned through
2264    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2265    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2266    /// bijection the future `CiliumClusterwideEnvoyConfig`
2267    /// per-`:politicas` overlay emits. Every downstream consumer that
2268    /// reads the breaker declaration keys off this scalar (the
2269    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2270    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2271    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2272    /// that brackets `cb.max_failures()` against
2273    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2274    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2275    /// [`crate::render::require_positive_canonical_bounded_duration`],
2276    /// the future M4 per-Aplicacao Envoy reconciler materialization
2277    /// pass, the future per-`:contratos`-edge breaker override the
2278    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2279    ///
2280    /// Prior to this lift the `.circuit_breaker` field was accessed
2281    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2282    /// `self.circuit_breaker.is_none()` arm and the
2283    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2284    /// bind — two open-coded field-accesses that expressed no
2285    /// compile-time link back to the typed slot. A future extension of
2286    /// the `:politicas :circuit-breaker` axis to a richer author
2287    /// surface — a per-`:contratos`-edge breaker override the operator
2288    /// pins through a future `:contratos :circuit-breaker` slot the
2289    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2290    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2291    /// a promotion of the plain `(max_failures, window)` scalar pair to
2292    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2293    /// sub-block once Envoy's `outlier_detection` grows the peer
2294    /// ejection-percentage / ejection-time axes — would have had to be
2295    /// threaded through both open-coded copies in lockstep or the
2296    /// emptiness predicate and the validate gate would silently
2297    /// disagree on which breaker declaration a given [`MeshPolicy`]
2298    /// resolves to (a `:politicas` block whose only axis is a
2299    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2300    /// the validate path silently read a drifted other value, or vice
2301    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2302    /// "60s"))` would omit the value-shape gate while the emptiness
2303    /// predicate still classified the policy as non-empty). Lifting
2304    /// the resolution to a typed method on the substrate primitive
2305    /// means every downstream consumer of the Aplicacao's
2306    /// per-`:politicas` breaker surface reaches for exactly one typed
2307    /// dispatch — the resolver's accept-set migrates as a unit on any
2308    /// future axis addition.
2309    ///
2310    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2311    /// mesh-slot family (sibling of the peer per-`:politicas`
2312    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2313    /// on the same composite-Copy shape, and of the sibling per-
2314    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2315    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2316    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2317    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2318    /// same "one typed dispatch on the substrate primitive, thin
2319    /// projections at each consumer" discipline extended onto the last
2320    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2321    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2322    /// match the storage field's name; the accessor's identity maps
2323    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2324    /// docstring already carries. Closes the last unlifted
2325    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2326    /// reader now routes through a typed dispatch on the substrate
2327    /// primitive.
2328    #[must_use]
2329    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2330        self.circuit_breaker
2331    }
2332}
2333
2334#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2335#[serde(rename_all = "camelCase")]
2336pub struct CircuitBreaker {
2337    pub max_failures: u32,
2338    #[serde(with = "supervisor::duration_codec_required")]
2339    pub window: Duration,
2340}
2341
2342impl CircuitBreaker {
2343    /// Substrate-canonical per-`:politicas :circuit-breaker`
2344    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2345    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2346    /// breaker trip-count keys off — returns the author-declared
2347    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2348    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2349    /// so the accessor returns by value; no borrow of `&self` past the
2350    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2351    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2352    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2353    /// present, and its `:max-failures` field carries the trip count as a
2354    /// required-axis scalar).
2355    ///
2356    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2357    /// "consecutive-transient-failure trip threshold" contract
2358    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2359    /// (zero-floor rejected through
2360    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2361    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2362    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2363    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2364    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2365    /// Every downstream consumer that reads the trip threshold keys off
2366    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2367    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2368    /// canonical `require_positive_bounded_u32` helper, the future M4
2369    /// per-Aplicacao Envoy config reconciler materialization pass, the
2370    /// future per-`:contratos`-edge breaker-override overlay the
2371    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2372    ///
2373    /// Prior to this lift the `.max_failures` field was accessed inline
2374    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2375    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2376    /// open-coded field-access that expressed no compile-time link back
2377    /// to the typed sub-struct axis. A future extension of the
2378    /// `:max-failures` axis to a richer author surface — a
2379    /// per-`:contratos`-edge breaker override the operator pins through a
2380    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2381    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2382    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2383    /// plain `u32` trip count to a richer
2384    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2385    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2386    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2387    /// count arms — would have had to be threaded through every open-
2388    /// coded copy in lockstep or the validate gate and the future M4
2389    /// emit path would silently disagree on which trip threshold a given
2390    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2391    /// would satisfy validate while the emit path silently read a drifted
2392    /// other value, or vice versa: a validated typed slot would land at
2393    /// the emit boundary as a no-op breaker whose trip threshold is
2394    /// structurally never reached). Lifting the resolution to a typed
2395    /// method on the substrate primitive means every downstream consumer
2396    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2397    /// trip-threshold surface reaches for exactly one typed dispatch —
2398    /// the resolver's accept-set migrates as a unit on any future axis
2399    /// addition.
2400    ///
2401    /// First sub-struct scalar accessor on the M3 mesh-slot family
2402    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2403    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2404    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2405    /// closes the last unlifted per-`:politicas` scalar-value axis after
2406    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2407    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2408    /// Same "one typed dispatch on the substrate primitive, thin
2409    /// projections at each consumer" discipline the peer
2410    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2411    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2412    /// [`Membro::versao_requirement`] (a40b0e3),
2413    /// [`Entrada::destination`] (6db982c) accessors carry on their
2414    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2415    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2416    /// match the storage field's name; the accessor's identity maps onto
2417    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2418    /// docstring already carries.
2419    #[must_use]
2420    pub const fn max_failures(&self) -> u32 {
2421        self.max_failures
2422    }
2423
2424    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2425    /// Envoy-outlier-detection rolling-observation-interval scalar
2426    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2427    /// breaker rolling-window duration keys off — returns the
2428    /// author-declared `:politicas :circuit-breaker :window` typed
2429    /// `Duration` verbatim, copied out of the typed slot's own
2430    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2431    /// by value; no borrow of `&self` past the call). Non-optional (the
2432    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2433    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2434    /// `CircuitBreaker` past pattern-match is definitionally present,
2435    /// and its `:window` field carries the rolling-observation interval
2436    /// as a required-axis scalar).
2437    ///
2438    /// The `:politicas :circuit-breaker :window` axis carries the
2439    /// "consecutive-transient-failure rolling-observation interval"
2440    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2441    /// `Duration` accept-set (zero-floor rejected through
2442    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2443    /// residue rejected through
2444    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2445    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2446    /// Envoy `outlier_detection.interval` per-cluster
2447    /// ejection-observation-interval scalar (equivalently the future
2448    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2449    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2450    /// consumer that reads the rolling-observation interval keys off
2451    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2452    /// integer-millisecond canonical-form + cap bracket at
2453    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2454    /// [`crate::render::require_positive_canonical_bounded_duration`]
2455    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2456    /// materialization pass, the future per-`:contratos`-edge
2457    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2458    /// acknowledges).
2459    ///
2460    /// Prior to this lift the `.window` field was accessed inline at
2461    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2462    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2463    /// call — one open-coded field-access that expressed no compile-
2464    /// time link back to the typed sub-struct axis. A future extension
2465    /// of the `:window` axis to a richer author surface — a
2466    /// per-`:contratos`-edge window override the operator pins through
2467    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2468    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2469    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2470    /// `Duration` observation interval to a richer
2471    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2472    /// once Envoy's `outlier_detection` block's peer axes come into
2473    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2474    /// the window arms — would have had to be threaded through every
2475    /// open-coded copy in lockstep or the validate gate and the future
2476    /// M4 emit path would silently disagree on which observation
2477    /// interval a given [`CircuitBreaker`] resolves to (an author's
2478    /// `:window "60s"` would satisfy validate while the emit path
2479    /// silently read a drifted other value, or vice versa: a validated
2480    /// typed slot would land at the emit boundary as a breaker whose
2481    /// observation window is structurally so wide that no realistic
2482    /// failure-rate shape can trip it). Lifting the resolution to a
2483    /// typed method on the substrate primitive means every downstream
2484    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2485    /// observation-window surface reaches for exactly one typed
2486    /// dispatch — the resolver's accept-set migrates as a unit on any
2487    /// future axis addition.
2488    ///
2489    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2490    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2491    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2492    /// required-axis, extended onto the per-sub-struct required-`Duration`
2493    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2494    /// axis. Same "one typed dispatch on the substrate primitive, thin
2495    /// projections at each consumer" discipline the peer
2496    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2497    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2498    /// [`Membro::versao_requirement`] (a40b0e3),
2499    /// [`Entrada::destination`] (6db982c) accessors carry on their
2500    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2501    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2502    /// match the storage field's name; the accessor's identity maps onto
2503    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2504    /// docstring already carries.
2505    #[must_use]
2506    pub const fn window(&self) -> Duration {
2507        self.window
2508    }
2509}
2510
2511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2512pub struct RateLimit {
2513    /// Requests per window.
2514    pub rate: u32,
2515    /// Window duration.
2516    pub window: Duration,
2517}
2518
2519impl RateLimit {
2520    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2521    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2522    /// every consumer of the Aplicacao's per-`:contratos`-edge
2523    /// rate-limit-bucket capacity keys off — returns the author-declared
2524    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2525    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2526    /// returns by value; no borrow of `&self` past the call). Non-optional
2527    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2528    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2529    /// `RateLimit` past pattern-match is definitionally present, and its
2530    /// `:rate` field carries the token-bucket capacity as a required-axis
2531    /// scalar).
2532    ///
2533    /// The `:politicas :rate-limit` `:rate` axis carries the
2534    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2535    /// the typed slot's `u32` accept-set (zero-floor rejected through
2536    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2537    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2538    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2539    /// token-bucket-capacity scalar (equivalently the future
2540    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2541    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2542    /// consumer that reads the token-bucket capacity keys off this
2543    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2544    /// cap bracket that gates on the canonical
2545    /// [`crate::render::require_positive_bounded_u32`] helper, the
2546    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2547    /// emits the `<n>/<s|m|h>` author surface, the future M4
2548    /// per-Aplicacao Envoy config reconciler materialization pass, the
2549    /// future per-`:contratos`-edge rate-limit-override overlay the
2550    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2551    ///
2552    /// Prior to this lift the `.rate` field was accessed inline at three
2553    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2554    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2555    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2556    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2557    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2558    /// field-accesses that expressed no compile-time link back to the
2559    /// typed sub-struct axis. A future extension of the `:rate` axis
2560    /// to a richer author surface — a per-`:contratos`-edge rate
2561    /// override the operator pins through a future `:contratos :rate`
2562    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2563    /// per-cluster rate-default overlay the M4 CR materializer resolves
2564    /// per-CR, a promotion of the plain `u32` token capacity to a
2565    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2566    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2567    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2568    /// before the token arms — would have had to be threaded through
2569    /// every open-coded copy in lockstep or the validate gate, the
2570    /// codec's render path, and the future M4 emit path would silently
2571    /// disagree on which token capacity a given [`RateLimit`] resolves
2572    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2573    /// while the render / emit paths silently read a drifted other
2574    /// value, or vice versa: a validated typed slot would land at the
2575    /// emit boundary as a no-op limiter whose token capacity is
2576    /// structurally so high that no realistic per-edge traffic shape
2577    /// can drain it). Lifting the resolution to a typed method on the
2578    /// substrate primitive means every downstream consumer of the
2579    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2580    /// reaches for exactly one typed dispatch — the resolver's
2581    /// accept-set migrates as a unit on any future axis addition.
2582    ///
2583    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2584    /// in shape to the peer per-`CircuitBreaker`
2585    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2586    /// on the peer per-sub-struct required-axis, extended onto the
2587    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2588    /// required-axis scalar" projection pattern the sibling
2589    /// [`RateLimit::window`] future lift folds on. Same "one typed
2590    /// dispatch on the substrate primitive, thin projections at each
2591    /// consumer" discipline the peer [`WitContract::source`] /
2592    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2593    /// (0804823), [`Membro::nome`] (4a32abf),
2594    /// [`Membro::versao_requirement`] (a40b0e3),
2595    /// [`Entrada::destination`] (6db982c),
2596    /// [`CircuitBreaker::max_failures`] (3a74062),
2597    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2598    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2599    /// to match the storage field's name; the accessor's identity maps
2600    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2601    /// docstring already carries.
2602    #[must_use]
2603    pub const fn rate(&self) -> u32 {
2604        self.rate
2605    }
2606
2607    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2608    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2609    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2610    /// rate-limit-bucket refill period keys off — returns the
2611    /// author-declared `:politicas :rate-limit` typed `Duration`
2612    /// verbatim, copied out of the typed slot's own `Duration` storage
2613    /// (`Duration` is `Copy`, so the accessor returns by value; no
2614    /// borrow of `&self` past the call). Non-optional (the surrounding
2615    /// `Option<RateLimit>` is the "slot present?" projection at the
2616    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2617    /// pattern-match is definitionally present, and its `:window`
2618    /// field carries the token-bucket refill period as a required-axis
2619    /// scalar).
2620    ///
2621    /// The `:politicas :rate-limit` `:window` axis carries the
2622    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2623    /// — the typed slot's `Duration` accept-set (constrained to the
2624    /// three canonical windows `{1s, 60s, 3600s}` the
2625    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2626    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2627    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2628    /// per-cluster token-bucket-refill-period scalar (equivalently the
2629    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2630    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2631    /// consumer that reads the token-bucket refill period keys off
2632    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2633    /// canonical-window gate that keys off
2634    /// [`is_canonical_rate_limit_window`], the
2635    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2636    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2637    /// [`rate_limit_window_unit`] and non-canonical fallback via
2638    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2639    /// reconciler materialization pass, the future per-`:contratos`-
2640    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2641    /// roadmap acknowledges).
2642    ///
2643    /// Prior to this lift the `.window` field was accessed inline at
2644    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2645    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2646    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2647    /// error-payload construction on refusal, and the two
2648    /// [`rate_limit_codec::render`] arms
2649    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2650    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2651    /// open-coded field-accesses that expressed no compile-time link
2652    /// back to the typed sub-struct axis. A future extension of the
2653    /// `:window` axis to a richer author surface — a per-`:contratos`-
2654    /// edge window override the operator pins through a future
2655    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2656    /// acknowledges, a per-cluster window-default overlay the M4 CR
2657    /// materializer resolves per-CR, a promotion of the plain
2658    /// `Duration` refill period to a richer
2659    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2660    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2661    /// axis comes into scope, an addition of a `"d"` day suffix once
2662    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2663    /// have had to be threaded through every open-coded copy in
2664    /// lockstep or the validate gate, the codec's render path, and
2665    /// the future M4 emit path would silently disagree on which
2666    /// refill period a given [`RateLimit`] resolves to (an author's
2667    /// `:rate-limit "100/s"` would satisfy validate while the render
2668    /// / emit paths silently read a drifted other value, or vice
2669    /// versa: a validated typed slot would land at the emit boundary
2670    /// as a limiter whose refill period is structurally so long that
2671    /// no realistic per-edge traffic shape stays inside the token
2672    /// budget). Lifting the resolution to a typed method on the
2673    /// substrate primitive means every downstream consumer of the
2674    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2675    /// reaches for exactly one typed dispatch — the resolver's
2676    /// accept-set migrates as a unit on any future axis addition.
2677    ///
2678    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2679    /// sibling in shape to the just-landed [`RateLimit::rate`]
2680    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2681    /// required-axis, extended onto the per-sub-struct
2682    /// required-`Duration` axis; closes the last unlifted
2683    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2684    /// per-sub-struct accessor coverage is now complete across both
2685    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2686    /// the substrate primitive, thin projections at each consumer"
2687    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2688    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2689    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2690    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2691    /// [`Membro::nome`] (4a32abf),
2692    /// [`Membro::versao_requirement`] (a40b0e3),
2693    /// [`Entrada::destination`] (6db982c) accessors carry on their
2694    /// respective per-mesh-slot-atom scalar-value axes. Named
2695    /// `window()` to match the storage field's name; the accessor's
2696    /// identity maps onto the canonical MESH-COMPOSITION §III.2
2697    /// vocabulary the slot's docstring already carries.
2698    #[must_use]
2699    pub const fn window(&self) -> Duration {
2700        self.window
2701    }
2702
2703    /// Recognize this rate-limit's `:window` as a canonical
2704    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2705    /// exactly matches one of the three closed-set arm-Durations
2706    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2707    /// non-canonical magnitude the codec's round-trip would break on
2708    /// (sub-second residue, or a second-magnitude outside the set
2709    /// [`RateLimitUnit::ALL`] enumerates).
2710    ///
2711    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2712    /// returns `Some` here — the validate gate's
2713    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2714    /// rejects every window this accessor returns `None` on. Downstream
2715    /// consumers past validate (the codec's [`rate_limit_codec::render`]
2716    /// path, the future M4 per-Aplicacao Envoy config reconciler's
2717    /// materialization pass, the future per-`:contratos`-edge rate-limit-
2718    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2719    /// acknowledges) that read the typed unit off a validated slot can
2720    /// pattern-match on the returned `Some` without re-checking
2721    /// canonicality at the consumer layer — the typed enum surface is
2722    /// the load-bearing carrier of the canonicality invariant.
2723    ///
2724    /// Preferred over the free [`is_canonical_rate_limit_window`]
2725    /// module-private helper at any call site that has the typed
2726    /// [`RateLimit`] in hand (the codec's `render` arm at
2727    /// [`rate_limit_codec::render`], the validate gate's canonical-form
2728    /// arm in [`AplicacaoSpec::validate_politicas`], any future
2729    /// per-`:contratos` edge-override overlay resolver): those consumers
2730    /// reach for the typed enum without going through the
2731    /// `.window()` scalar-projection layer, and get the enum value
2732    /// directly (which the codec's render arm can then format via
2733    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2734    /// "typed sub-struct scalar accessor, one dispatch on the substrate
2735    /// primitive" discipline the sibling [`RateLimit::rate`] and
2736    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2737    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2738    /// projection axis (the third scalar accessor on the [`RateLimit`]
2739    /// axis, first typed-enum-return projection).
2740    #[must_use]
2741    pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2742        RateLimitUnit::from_window(self.window)
2743    }
2744}
2745
2746/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2747/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2748/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2749///
2750/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2751/// the `:politicas :rate-limit` unit surface reads from
2752/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2753/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2754/// [`is_canonical_rate_limit_window`] predicate the
2755/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2756/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2757/// projection) now lives inside this typed enum's `match self` arms — a
2758/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2759/// `rate_limit_action` grows daily-bucket support) is one new variant
2760/// plus the exhaustiveness arms on the four methods, so every consumer
2761/// picks it up by compile-time construction rather than a runtime
2762/// table-scan miss.
2763///
2764/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2765/// scanned via `find_map` at every projection call — an untyped runtime
2766/// walk that carried no compile-time link between the parse arm's
2767/// accepted suffixes, the render arm's emitted suffixes, and the
2768/// validate gate's accepted windows. A future rate-limit-unit addition
2769/// that landed one row without threading through the other consumers
2770/// (or a copy-paste flip that collapsed two rows onto one suffix) would
2771/// silently split the accepted-set across the three consumers — the
2772/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
2773/// for a 24h window that parse can't round-trip, the validate gate
2774/// misses one canonical window. Lifting the pairs onto a typed
2775/// closed-set enum with exhaustive `match` arms makes any such
2776/// half-landed extension a caixa-core build error (the compiler enforces
2777/// arm coverage on every method), not a silent per-consumer drift
2778/// surfacing at apply time. Same "closed-set typed-enum discriminator"
2779/// discipline the sibling [`PlacementStrategy`] (cc8f749),
2780/// [`crate::supervisor::RestartStrategy`],
2781/// [`crate::supervisor::RestartPolicy`],
2782/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
2783/// closed-set typed enums carry on their respective closed-set axes —
2784/// extended onto the seventh closed-set typed-enum discriminator axis
2785/// on the caixa typed surface (the `:politicas :rate-limit :window`
2786/// canonical-unit axis).
2787#[derive(
2788    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
2789)]
2790pub enum RateLimitUnit {
2791    /// 1-second window — canonical author-surface suffix `"s"`
2792    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2793    /// with a 1s magnitude.
2794    Second,
2795    /// 1-minute window — canonical author-surface suffix `"m"`
2796    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2797    /// with a 60s magnitude.
2798    Minute,
2799    /// 1-hour window — canonical author-surface suffix `"h"`
2800    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2801    /// with a 3600s magnitude.
2802    Hour,
2803}
2804
2805impl RateLimitUnit {
2806    /// Exhaustive iteration surface for every consumer that reads the
2807    /// full canonical-unit set (the byte-parity witness against the
2808    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
2809    /// webhook's accepted-suffix listing in its rejection body, any
2810    /// future round-trip fuzz harness). A future variant addition to
2811    /// [`RateLimitUnit`] extends this slice as a single edit and every
2812    /// consumer picks up the new entry by construction — the compiler-
2813    /// checked exhaustiveness on the sibling method `match` arms is the
2814    /// build-time guarantee that no arm forgets to grow.
2815    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
2816
2817    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
2818    /// string every `<n>/<unit>` rate-limit shape carries after its
2819    /// `/` separator. The single source of truth the codec's parse and
2820    /// render arms both dispatch on: the parse arm matches an incoming
2821    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
2822    /// output; the render arm emits the entry's `as_suffix` verbatim
2823    /// after the rate magnitude.
2824    #[must_use]
2825    pub const fn as_suffix(self) -> &'static str {
2826        match self {
2827            Self::Second => "s",
2828            Self::Minute => "m",
2829            Self::Hour => "h",
2830        }
2831    }
2832
2833    /// Canonical `Duration` for this unit — the token-bucket refill
2834    /// period the [`RateLimit::window`] axis carries when the surrounding
2835    /// slot's `:rate-limit` author surface named this unit.
2836    #[must_use]
2837    pub const fn window(self) -> Duration {
2838        Duration::from_secs(match self {
2839            Self::Second => 1,
2840            Self::Minute => 60,
2841            Self::Hour => 3_600,
2842        })
2843    }
2844
2845    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
2846    /// `None` when `suffix` is outside the closed-set arm-string set
2847    /// [`Self::as_suffix`] emits. The single `str → Self` projection
2848    /// [`rate_limit_codec::parse`] consumes.
2849    #[must_use]
2850    pub fn from_suffix(suffix: &str) -> Option<Self> {
2851        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
2852    }
2853
2854    /// Recognize a canonical rate-limit `Duration` as one of the three
2855    /// arms, or `None` when `window` carries sub-second residue or a
2856    /// second-magnitude outside the closed-set arm-window set
2857    /// [`Self::window`] emits. The single `Duration → Self` projection
2858    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
2859    /// both consume.
2860    #[must_use]
2861    pub fn from_window(window: Duration) -> Option<Self> {
2862        if window.subsec_nanos() != 0 {
2863            return None;
2864        }
2865        Self::ALL.iter().copied().find(|u| u.window() == window)
2866    }
2867
2868    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
2869    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
2870    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
2871    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
2872    /// consumes.
2873    ///
2874    /// The peer `Duration → &'static str` axis folded onto the substrate
2875    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
2876    /// production consumers ([`rate_limit_codec::render`] and
2877    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
2878    /// migrated (61421a6): the free helper's `Duration → &str` projection
2879    /// is now the two-step composition
2880    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
2881    /// reads through the typed accessor. This lift closes the peer
2882    /// `&str → Duration` axis by folding the vestigial module-private
2883    /// `rate_limit_window_from_unit` delegate onto this associated method
2884    /// — the codec's parse arm and every future wire-side consumer of the
2885    /// `&str → Duration` projection (a future admission-webhook that
2886    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
2887    /// before it's promoted to a validated typed slot, a future
2888    /// `feira lint` shape-probe that reads the author-surface bytes
2889    /// verbatim) now reach for exactly one typed dispatch on the
2890    /// substrate primitive.
2891    ///
2892    /// Same "closed-set typed-enum discriminator with canonical
2893    /// projections per axis" discipline the sibling [`Self::as_suffix`]
2894    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
2895    /// methods carry — this associated method closes the fifth (and last
2896    /// unlifted) projection axis on the arm-table, so the closed-set enum
2897    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
2898    /// consumer of the `:politicas :rate-limit :window` axis reaches
2899    /// through. A future rate-limit-unit addition (a `"d"` day suffix
2900    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
2901    /// `"ms"` sub-second window once high-throughput per-edge policies
2902    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
2903    /// variant plus one arm per method — the compiler enforces
2904    /// exhaustiveness on every consumer's `match self` arms and picks
2905    /// the new unit up by construction across all five projections.
2906    #[must_use]
2907    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
2908        Self::from_suffix(suffix).map(Self::window)
2909    }
2910}
2911
2912/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
2913/// every consumer that formats a canonical rate-limit unit as user-
2914/// facing text (future M4 admission-webhook rejection bodies naming
2915/// the accepted-suffix set, future `feira app graph` per-`:politicas`
2916/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
2917/// codec's parse arm accepts and the render arm emits. Same
2918/// as_str-through-Display convergence discipline the sibling
2919/// [`PlacementStrategy`], [`crate::CaixaKind`],
2920/// [`crate::supervisor::RestartStrategy`], and
2921/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
2922impl std::fmt::Display for RateLimitUnit {
2923    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2924        f.write_str(self.as_suffix())
2925    }
2926}
2927
2928/// Upper-bound ceiling on the `:politicas :timeout` axis — every
2929/// validated [`MeshPolicy::timeout`] past
2930/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
2931/// (inclusive on both ends, integer-millisecond magnitudes by the
2932/// canonical-form gate immediately preceding).
2933///
2934/// The typed field is `Option<Duration>` (the zero-floor arm
2935/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
2936/// `Duration::ZERO`, and the canonical-form arm
2937/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
2938/// sub-millisecond residue), so a programmatic struct literal
2939/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
2940/// 24h) and the equivalent author-surface form
2941/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
2942/// integer-hour magnitude) both round-trip cleanly through serde — a
2943/// structurally unbounded `Duration` ceiling. A `:timeout` value far
2944/// above the documented production-playbook band (Envoy default `15s`,
2945/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
2946/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
2947/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
2948/// at `~3600s`) silently degenerates the mesh-policy contract: the
2949/// per-call deadline is structurally so long that no realistic
2950/// synchronous-`:contratos` traversal can reach it, so the typed slot
2951/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
2952/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
2953/// blocking" degenerates to a nominal-only contract on the
2954/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
2955/// the sibling `:politicas :retries` axis and the
2956/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
2957/// `:politicas :circuit-breaker :max-failures` axis — all three close
2958/// the "structurally unbounded ceiling on a typed `:politicas` axis"
2959/// footgun the prior zero-floor-and-canonical-form-only checks left
2960/// open.
2961///
2962/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2963/// shared duration codec emits (`"<n>h"` for any integer-hour
2964/// magnitude) — every value in the canonical authoring form's
2965/// `<integer><unit>` grammar at or below this cap renders to a clean
2966/// canonical string. The cap sits an order of magnitude above every
2967/// documented production-playbook recommendation band (Envoy default
2968/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
2969/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
2970/// configured maximum (`proxy_read_timeout` typical max `3600s`),
2971/// below the clearly-pathological "effectively no timeout" floor
2972/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
2973/// want for a long-running synchronous workflow, but a hard wall above
2974/// which the mesh-level deadline is structurally a non-deadline.
2975/// Lifted as a typed `pub const` so the bound has exactly one source
2976/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2977/// materializer's admission webhook and the caixa-mesh-side
2978/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2979/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2980/// other typed upper bound in this crate carries
2981/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2982/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2983/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2984/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2985pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
2986
2987/// Upper-bound ceiling on the `:politicas :retries` axis — every
2988/// validated [`MeshPolicy::retries`] past
2989/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
2990///
2991/// The typed slot is `Option<u32>` (`None` = no retries on transient
2992/// failure; `Some(0)` already rejected by the
2993/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
2994/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
2995/// .. }`) and the equivalent author-surface form
2996/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
2997/// serde / the codec — a structurally unbounded `u32` ceiling. The
2998/// runtime substrate that consumes the value (Envoy's
2999/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3000/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3001/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3002/// admission cap is 10) translates a four-billion-retry policy into a
3003/// thundering-herd amplification vector on transient failure — the
3004/// caller's one request fans out to `retries` server-side calls per
3005/// edge per traversal, multiplying load by `(retries+1)^depth` across
3006/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3007/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3008/// invariant on the retry axis; both belong at the typed-slot layer.
3009///
3010/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3011/// upstream mesh-policy schema that documents one) and sits above the
3012/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3013/// every documented production playbook): a value the author can
3014/// plausibly want, but a hard wall above which the policy is
3015/// structurally a footgun. Lifted as a typed `pub const` so the bound
3016/// has exactly one source of truth — a future axis reaching for the
3017/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3018/// materializer's admission webhook, the caixa-mesh-side
3019/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3020/// one place. Same shape every other typed upper bound in this crate
3021/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3022/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3023/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3024/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3025pub const POLICY_RETRIES_MAX: u32 = 10;
3026
3027/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3028/// axis — every validated [`CircuitBreaker::max_failures`] past
3029/// [`AplicacaoSpec::validate_politicas`] lies in
3030/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3031///
3032/// The typed field is `u32` (the zero-floor arm
3033/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3034/// `0` — a breaker that trips on the first call), so a programmatic
3035/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3036/// and the equivalent author-surface form
3037/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3038/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3039/// `max_failures` value far above the documented production-playbook
3040/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3041/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3042/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3043/// typical 5–50) silently disables the breaker's protection role:
3044/// the threshold is structurally so high that no realistic
3045/// failures-per-`:window` traffic shape can reach it, so the breaker
3046/// never trips and the typed slot becomes a no-op carried on every
3047/// emitted Envoy / Cilium L7 overlay. Pairs with the
3048/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3049/// axis — both close the "structurally unbounded `u32` ceiling on a
3050/// typed policy axis" footgun the prior zero-floor-only checks left
3051/// open.
3052///
3053/// The `1000` ceiling sits an order of magnitude above every
3054/// documented upstream production-playbook recommendation band (the
3055/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3056/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3057/// the clearly-pathological "effectively no protection"
3058/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3059/// plausibly want at hyperscale, but a hard wall above which the
3060/// policy is structurally a no-op. Lifted as a typed `pub const` so
3061/// the bound has exactly one source of truth — the future M4
3062/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3063/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3064/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3065/// one place. Same shape every other typed upper bound in this crate
3066/// carries ([`POLICY_RETRIES_MAX`],
3067/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3068/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3069/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3070pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3071
3072/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3073/// every validated [`CircuitBreaker::window`] past
3074/// [`AplicacaoSpec::validate_politicas`] lies in
3075/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3076/// integer-millisecond magnitudes by the canonical-form gate
3077/// immediately preceding).
3078///
3079/// The typed field is `Duration` (the zero-floor arm
3080/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3081/// `Duration::ZERO`, and the canonical-form arm
3082/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3083/// sub-millisecond residue), so a programmatic struct literal
3084/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3085/// and the equivalent author-surface form
3086/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3087/// integer-hour magnitude) both round-trip cleanly through serde — a
3088/// structurally unbounded `Duration` ceiling. A `:window` value far
3089/// above the documented production-playbook band (Hystrix
3090/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3091/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3092/// Istio `outlierDetection.interval` default `10s`, Envoy
3093/// `outlier_detection.interval` default `10s`, AWS App Mesh
3094/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3095/// breaker's role: a rolling-window failure counter whose window is
3096/// hours long is operationally a lifetime counter, the breaker's
3097/// "recent failures" memory is structurally so long that transient
3098/// failures are never forgotten, and the typed slot becomes a no-op
3099/// trigger that trips once and stays tripped for the lifetime of the
3100/// component carried on every emitted Envoy / Cilium L7 overlay.
3101///
3102/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3103/// shared duration codec emits (`"<n>h"` for any integer-hour
3104/// magnitude) — every value in the canonical authoring form's
3105/// `<integer><unit>` grammar at or below this cap renders to a clean
3106/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3107/// cap on the first typed-`Duration` `:politicas` axis: the two
3108/// duration-typed `:politicas` axes now share a single uniform top
3109/// edge so the next typed-slot wiring (the future caixa-mesh
3110/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3111/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3112/// admission webhook) reaches for either field knowing the value is
3113/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3114/// sits two orders of magnitude above every documented upstream
3115/// production-playbook recommendation band (Hystrix / resilience4j /
3116/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3117/// and below the clearly-pathological "rolling window degenerates to
3118/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3119/// author can plausibly want for a very-low-traffic long-tail
3120/// failure-detection window, but a hard wall above which the breaker's
3121/// rolling-window contract is structurally a lifetime-counter contract.
3122/// Lifted as a typed `pub const` so the bound has exactly one source
3123/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3124/// materializer's admission webhook and the caixa-mesh-side
3125/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3126/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3127/// other typed upper bound in this crate carries
3128/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3129/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3130/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3131/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3132/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3133pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3134
3135/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3136/// every validated [`RateLimit::rate`] past
3137/// [`AplicacaoSpec::validate_politicas`] lies in
3138/// `1..=POLICY_RATE_LIMIT_MAX`.
3139///
3140/// The typed field is `u32` (the zero-floor arm
3141/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3142/// zero-rate limit denies every request, the canonical "I forgot
3143/// that 0 means deny-everything" footgun), so a programmatic struct
3144/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3145/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3146/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3147/// round-trip cleanly through serde — a structurally unbounded `u32`
3148/// ceiling. The runtime substrate consuming the value (Envoy's
3149/// `local_rate_limit.token_bucket.max_tokens`, the future
3150/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3151/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3152/// rate-limit into a no-op rate-limiter: the bucket capacity is
3153/// structurally so high no realistic per-edge traffic shape can
3154/// drain it, the limiter never trips, and the typed slot becomes a
3155/// "rate-limit declared, no enforcement" footgun — the canonical
3156/// declared-but-inert shape every other `:politicas` cap arm
3157/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3158/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3159///
3160/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3161/// above every documented upstream production-playbook recommendation
3162/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3163/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3164/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3165/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3166/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3167/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3168/// `u32::MAX`): a value the author can plausibly want at hyperscale
3169/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3170/// /h-window arm), but a hard wall above which the policy is
3171/// structurally a no-op carried verbatim on every emitted Envoy /
3172/// Cilium L7 overlay. The cap brackets all three canonical windows
3173/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3174/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3175/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3176/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3177/// has exactly one source of truth — the future M4
3178/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3179/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3180/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3181/// one place. Same shape every other typed upper bound in this crate
3182/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3183/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3184/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3185/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3186/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3187/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3188pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3189
3190// `:entrada :host` total-length and per-label cap axes route through
3191// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3192// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3193// pair of aplicacao-private aliases the previous `validate_entrada_host`
3194// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3195// = 63`) were structurally the same K8s Gateway API v1 Hostname
3196// admission-schema bounds — the total-length cap on the OpenAPI
3197// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3198// same regex — that the peer axes at the caixa-core::render level pin,
3199// so hoisting both readers onto the shared lifted constants closes the
3200// third-occurrence duplication threshold structurally: the M4
3201// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3202// label validator, the future per-`Certificate` SAN emitter, and every
3203// other per-Gateway-API-Hostname landing site reach the same one place
3204// as the `:entrada :host` gate does — no per-axis alias drift surface
3205// between them, by construction.
3206
3207/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3208/// extractor expression — the upper bound `validate_placement_shard_key`
3209/// enforces on every well-shaped shard-key past validate. The realistic
3210/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3211/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3212/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3213/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3214/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3215/// in `:shard-key`" footgun at validate time rather than at the future
3216/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3217const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3218
3219/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3220/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3221/// that maps the shared parser-shaped reason into the
3222/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3223/// is self-locating (the offending `caixa:` is named verbatim) and
3224/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3225/// fix it in one edit. Same diagnostic shape as
3226/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3227/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3228fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3229    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3230    // re-checking here keeps the predicate usable from any future
3231    // call site (the M4 CR materializer) without an empty-check
3232    // footgun. The shared
3233    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3234    // the empty-first + shape cascade every peer name axis
3235    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3236    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3237    // `:upgrade-from :module`) routes through, so drift between the
3238    // eight axes' accepted DNS-1123-label sets is structurally
3239    // impossible.
3240    crate::render::require_valid_dns_1123_label(
3241        caixa,
3242        || AplicacaoError::MembroCaixaEmpty,
3243        |reason| AplicacaoError::MembroCaixaInvalid {
3244            caixa: caixa.to_string(),
3245            reason,
3246        },
3247    )
3248}
3249
3250/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3251/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3252/// that maps the shared parser-shaped reason into the
3253/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3254///
3255/// Cluster names land in DNS-1123-label territory across every consumer:
3256/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3257/// the `lareira-fleet-programs` aggregator applies to scope programs to
3258/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3259/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3260/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3261/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3262/// side schema enforces the DNS-1123 label rule on admission; a
3263/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3264/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3265/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3266/// only gate and the failure surfaces as a no-match at filter time —
3267/// the workload doesn't land in the named cluster, with no diagnostic
3268/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3269/// build time mirrors the `:membros :caixa` value-shape trajectory
3270/// (3f9d7a0) on the peer name axis.
3271///
3272/// The diagnostic carries the offending `cluster:` verbatim plus a
3273/// parser-shaped `reason:` naming the specific violation, so the
3274/// author can grep their caixa.lisp for `:clusters` and fix it in
3275/// one edit. Same diagnostic shape as
3276/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3277fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3278    // Empty is already gated by `PlacementClusterEmpty` at the call
3279    // site; re-checking here keeps the predicate usable from any
3280    // future call site (the M4 CR materializer's per-cluster validator)
3281    // without an empty-check footgun. Routes through the shared
3282    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3283    // name axes each land on.
3284    crate::render::require_valid_dns_1123_label(
3285        cluster,
3286        || AplicacaoError::PlacementClusterEmpty,
3287        |reason| AplicacaoError::PlacementClusterInvalid {
3288            cluster: cluster.to_string(),
3289            reason,
3290        },
3291    )
3292}
3293
3294/// Reject `:placement :affinity` hints whose shape can never legitimately
3295/// land in any downstream selector or label-keyed routing axis. Thin
3296/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3297/// shared parser-shaped reason into the
3298/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3299/// diagnostic is self-locating (the offending `:affinity` is named
3300/// verbatim) and the author can grep their caixa.lisp for
3301/// `:affinity "<hint>"` and fix it in one edit.
3302///
3303/// The `:affinity` slot carries a placement-engine hint — canonical
3304/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3305/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3306/// compression overlay and the future M4 placement-engine's per-hint
3307/// routing axis. Each downstream consumer (caixa-mesh's
3308/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3309/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3310/// `spec.placement.affinity` admission rule, the future M4 per-hint
3311/// node-affinity / pod-affinity rule generator keying off the same
3312/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3313/// selector) requires the value to be a DNS-1123 label — K8s label
3314/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3315/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3316/// admission rule the apiserver enforces.
3317///
3318/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3319/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3320/// Python-module-name leak), `:affinity "data.locality"` (the
3321/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3322/// `:affinity "data-locality-"` (boundary-hyphen violation),
3323/// `:affinity "data locality"` (paste-from-doc whitespace),
3324/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3325/// 64-byte over-cap slug silently passed the empty-only check and the
3326/// failure surfaced as a no-match at the M3 Adaptive compression
3327/// overlay's filter time (`placement.affinity` carried a malformed
3328/// value, no node matched, the workload landed on the default
3329/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3330/// the empty-:affinity / empty-shard-key / zero-:politicas /
3331/// empty-:contratos-target gates already close on every other
3332/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3333/// gate closes the fifth typed slot on the Aplicacao surface to land
3334/// on the canonical DNS-1123 label floor (after the four Servico-name
3335/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3336/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3337/// b0e8748).
3338///
3339/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3340/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3341/// validated values are guaranteed-accepted by the apiserver without
3342/// re-validation at any downstream renderer or admission layer.
3343fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3344    // Empty is gated separately at the call site for a self-locating
3345    // diagnostic; re-checking here keeps the predicate usable from any
3346    // future call site (the M4 CR materializer's per-affinity
3347    // validator) without an empty-check footgun. Routes through the
3348    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3349    // peer name axes each land on.
3350    crate::render::require_valid_dns_1123_label(
3351        affinity,
3352        || AplicacaoError::PlacementAffinityEmpty,
3353        |reason| AplicacaoError::PlacementAffinityInvalid {
3354            affinity: affinity.to_string(),
3355            reason,
3356        },
3357    )
3358}
3359
3360/// Reject `:placement :shard-key` extractor expressions whose shape can
3361/// never legitimately drive the future M4 Akka-style cluster-sharding
3362/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3363/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3364/// diagnostic is self-locating (the offending `:shard-key` value is
3365/// named verbatim alongside the parser-shaped reason) and the author can
3366/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3367/// edit.
3368///
3369/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3370/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3371/// expression naming the message property to hash on. The realistic
3372/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3373/// property name; `$tenantId` — Akka entity-id placeholder;
3374/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3375/// `${tenant}` — interpolation-style template) all sit in the printable
3376/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3377/// multi-line blob landing in `:shard-key`, an embedded space from a
3378/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3379/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3380/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3381/// check and the failure surfaces at the future M4 reconciler's hash
3382/// pass as a runtime extractor-evaluation error far from the source
3383/// `caixa.lisp`, with no field naming which member's `:shard-key`
3384/// carried the offending value.
3385///
3386/// The contract — the printable ASCII single-token intersection-floor
3387/// every Akka-style entity-id extractor implementation admits:
3388///
3389///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3390///     peer DNS-1123-label-shaped `:placement :affinity` /
3391///     `:placement :clusters` identifier axes; realistic shard-keys sit
3392///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3393///     blob footguns at validate time;
3394///   - every byte in the printable ASCII range `0x21..=0x7E` —
3395///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3396///     `"$tenantId\n"` from paste-from-aligned-doc /
3397///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3398///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3399///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3400///     un-Punycode-encoded IDN that round-trips inconsistently across
3401///     NFC/NFD normalization).
3402///
3403/// The accepted set is broader than the DNS-1123 label floor the peer
3404/// `:placement :clusters` / `:placement :affinity` axes use because the
3405/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3406/// landing site; it's an extractor expression the future Akka-style
3407/// reconciler reads as a property reference. The realistic forms
3408/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3409/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3410/// but every Akka-style entity-id extractor parses. The
3411/// printable-ASCII-token floor accepts every shape any such extractor
3412/// would accept while rejecting the cross-implementation footguns
3413/// (whitespace breaks token boundaries; non-ASCII round-trips
3414/// inconsistently across YAML emitters and NFC/NFD normalization;
3415/// control characters silently corrupt the next read).
3416///
3417/// Until this gate landed `validate_placement` only refused the
3418/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3419/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3420/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3421/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3422/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3423/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3424/// control character from paste-from-binary, the 64-byte over-cap
3425/// paste-from-doc multi-line slug) silently passed validate. The future
3426/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3427/// would then surface the malformed value either as a runtime
3428/// extractor-evaluation error (whitespace breaks the extractor's token
3429/// boundary, no match) or as a silently-different shard assignment
3430/// across YAML emitters (non-ASCII normalizes differently between the
3431/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3432/// parser, the same entity ID maps to two distinct shards on a
3433/// re-render). Lifting the shape gate to caixa-build time makes the
3434/// extractor-floor invariant a structural property of every validated
3435/// `Placement`: every `Sharded` placement past `validate_placement` has
3436/// a `:shard-key` the future M4 reconciler can hash without
3437/// re-validating at the runtime layer.
3438///
3439/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3440/// [`AplicacaoError::ContratoSubjectInvalid`] /
3441/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3442/// on the peer `:contratos` payload axes — each lifts the
3443/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3444/// closing the canonical "this passed validate but the runtime parser
3445/// rejected it" surprise.
3446fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3447    // Empty is gated separately at the call site via the more
3448    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3449    // re-checking here keeps the predicate usable from any future call
3450    // site (the M4 CR materializer's per-shard-key validator) without
3451    // an empty-check footgun.
3452    if key.is_empty() {
3453        return Err(AplicacaoError::ShardedKeyEmpty);
3454    }
3455    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3456        return Err(AplicacaoError::ShardKeyInvalid {
3457            shard_key: key.to_string(),
3458            reason: format!(
3459                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3460                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3461                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3462                 well under 32 bytes, this length suggests a paste-from-doc \
3463                 multi-line blob landed in `:shard-key` instead of a single-token \
3464                 extractor expression)",
3465                key.len()
3466            ),
3467        });
3468    }
3469    for &b in key.as_bytes() {
3470        if (0x21..=0x7E).contains(&b) {
3471            continue;
3472        }
3473        let reason = if b == b' ' {
3474            "contains a space (Akka-style entity-id extractor expressions are \
3475             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3476             whitespace breaks the extractor's token boundary at the runtime layer, \
3477             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3478             a multi-token blob in one `:shard-key` slot)"
3479                .to_string()
3480        } else if b == b'\t' {
3481            "contains a tab character (paste-from-aligned-doc footgun; the \
3482             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3483             reference, embedded whitespace breaks the token boundary at the \
3484             runtime hash-extractor pass)"
3485                .to_string()
3486        } else if b == b'\n' || b == b'\r' {
3487            format!(
3488                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3489                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3490                 extractor reads `:shard-key` as a single-token reference, embedded \
3491                 newlines either truncate the value at the YAML emitter layer or \
3492                 break the token boundary at the runtime hash-extractor pass)"
3493            )
3494        } else if b < 0x20 || b == 0x7F {
3495            format!(
3496                "contains control character 0x{b:02x} (the canonical \
3497                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3498                 control characters silently corrupt round-trip serialization \
3499                 across YAML emitters and break the runtime hash-extractor's \
3500                 single-token parser)"
3501            )
3502        } else {
3503            format!(
3504                "contains non-ASCII byte 0x{b:02x} (the canonical \
3505                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3506                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3507                 across YAML emitter implementations — the same entity ID can \
3508                 silently map to two distinct shards on a re-render. Use a \
3509                 printable-ASCII extractor expression like `tenantId`, \
3510                 `$tenantId`, or `metadata.tenantId`)"
3511            )
3512        };
3513        return Err(AplicacaoError::ShardKeyInvalid {
3514            shard_key: key.to_string(),
3515            reason,
3516        });
3517    }
3518    Ok(())
3519}
3520
3521/// Reject `:contratos :de` / `:contratos :para` values whose shape
3522/// can never legitimately match a validated `:membros :caixa`. Thin
3523/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3524/// shared parser-shaped reason into the
3525/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3526/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3527/// the offending value verbatim) and the author can grep their
3528/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3529/// one edit.
3530///
3531/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3532/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3533/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3534/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3535/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3536/// un-Punycode-encoded IDN) silently passed the per-axis check and
3537/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3538/// membership lookup — diagnostic-framed as "this caixa is not in
3539/// `:membros`" when the root cause is "this `:de` value is not a
3540/// well-shaped Servico-name identifier and could never legitimately
3541/// match any validated member". Because every `:membros :caixa` is
3542/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3543/// `names` HashSet structurally never contains an empty / malformed
3544/// string, so the membership lookup arm misframes every empty /
3545/// malformed input. Lifting the shape arm ahead of the lookup
3546/// preserves the legitimate `ContratoMemberMissing` arm (a
3547/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3548/// reference) while routing every structurally-impossible-to-match
3549/// input through the narrower self-locating shape diagnostic.
3550///
3551/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3552/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3553/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3554/// to land on the canonical [`crate::render::is_dns_1123_label`]
3555/// floor. The `slot: &'static str` field carries the kebab-case
3556/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3557/// per-callback-slot diagnostic shape and the
3558/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3559/// (85f102c) cross-list-tag pattern.
3560fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3561    // Routes through the shared
3562    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3563    // name axes each land on. The `slot: &'static str` field flows
3564    // through both error variants so the diagnostic names which
3565    // per-edge axis (`:de` vs `:para`) the offending value came from.
3566    crate::render::require_valid_dns_1123_label(
3567        caixa,
3568        || AplicacaoError::ContratoCaixaEmpty { slot },
3569        |reason| AplicacaoError::ContratoCaixaInvalid {
3570            slot,
3571            caixa: caixa.to_string(),
3572            reason,
3573        },
3574    )
3575}
3576
3577/// Reject `:entrada :para` values whose shape can never legitimately
3578/// match a validated `:membros :caixa`. Thin wrapper around
3579/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3580/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3581/// variant, so the diagnostic is self-locating (the offending
3582/// `:entrada :para` value is named verbatim) and the author can grep
3583/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3584///
3585/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3586/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3587/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3588/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3589/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3590/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3591/// silently passed the per-axis check and surfaced as
3592/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3593/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3594/// root cause is "this `:entrada :para` value is not a well-shaped
3595/// Servico-name identifier and could never legitimately match any
3596/// validated member". Because every `:membros :caixa` is shape-
3597/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3598/// `HashSet` structurally never contains an empty / malformed string,
3599/// so the membership lookup arm misframes every empty / malformed
3600/// input. Lifting the shape arm ahead of the lookup preserves the
3601/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3602/// simply isn't in `:membros` — a phantom reference) while routing
3603/// every structurally-impossible-to-match input through the narrower
3604/// self-locating shape diagnostic.
3605///
3606/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3607/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3608/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3609/// fourth and last Aplicacao-level Servico-name reference axis to
3610/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3611/// No `slot: &'static str` field because there is only one axis
3612/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3613/// the simpler shape mirrors [`validate_membro_caixa`] and
3614/// [`validate_placement_cluster`].
3615fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3616    // Empty is gated separately at the call site for a self-locating
3617    // diagnostic; re-checking here keeps the predicate usable from any
3618    // future call site (the M4 CR materializer's per-`:entrada`
3619    // validator) without an empty-check footgun. Routes through the
3620    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3621    // peer name axes each land on.
3622    crate::render::require_valid_dns_1123_label(
3623        para,
3624        || AplicacaoError::EntradaParaEmpty,
3625        |reason| AplicacaoError::EntradaParaInvalid {
3626            para: para.to_string(),
3627            reason,
3628        },
3629    )
3630}
3631
3632/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3633/// would refuse at admission time. The contract — exactly the regex
3634/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3635/// and `HTTPRoute.spec.hostnames[]`,
3636/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3637/// (max length 253; per-label max length 63):
3638///
3639///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3640///     uppercase, no underscore, no Unicode/IDN — IDN must be
3641///     pre-encoded as Punycode `xn--…` by the author);
3642///   - exactly one optional leading wildcard label (`*.`); a wildcard
3643///     in any non-leading label position is rejected;
3644///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
3645///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
3646///   - total length 1..=253 bytes;
3647///   - no IPv4 literal (Gateway API forbids IP literals);
3648///   - no scheme (`https://`, `http://`), no port (`:8080`), no
3649///     whitespace, no path (`/`).
3650///
3651/// Lifted as a typed gate (rather than an inline cascade in
3652/// `validate()`) so the contract lives in one place — every future
3653/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3654/// materializer's host validator, the future per-`:entrada` SAN
3655/// emission for cert-manager Certificates, the multi-`:entrada`
3656/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3657/// for the same predicate, not its own. Same compounding shape as
3658/// `is_canonical_rate_limit_window` (808017c) and
3659/// [`WitTarget::label`] (previously the free `contrato_target_label`
3660/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3661/// per-variant label match is compiler-checked-exhaustive).
3662///
3663/// The diagnostic carries the offending `host:` verbatim plus a
3664/// parser-shaped `reason:` naming the specific violation, so the
3665/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3666/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3667/// (9888b13).
3668fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3669    // Empty is already gated by `EmptyEntradaHost` at the call site;
3670    // re-checking here keeps the predicate usable from any future
3671    // call site (M4 CR materializer) without an empty-check footgun.
3672    if host.is_empty() {
3673        return Err(AplicacaoError::EmptyEntradaHost);
3674    }
3675    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3676        return Err(AplicacaoError::EntradaHostInvalid {
3677            host: host.to_string(),
3678            reason: format!(
3679                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3680                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3681                host.len(),
3682                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3683            ),
3684        });
3685    }
3686    if host.contains("://") {
3687        return Err(AplicacaoError::EntradaHostInvalid {
3688            host: host.to_string(),
3689            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3690                     Gateway API takes the bare hostname)"
3691                .to_string(),
3692        });
3693    }
3694    if host.contains('/') {
3695        return Err(AplicacaoError::EntradaHostInvalid {
3696            host: host.to_string(),
3697            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3698                     matching is in `:entrada :paths`)"
3699                .to_string(),
3700        });
3701    }
3702    // After the `://` scheme-prefix and `/` path arms have ruled out the
3703    // two `:`-bearing shapes the Gateway API actively rejects with
3704    // location-shaped diagnostics, any remaining `:` in the host body is
3705    // either the canonical "I put the port in the `:host` slot"
3706    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3707    // slot lives one axis away on the same `:entrada` block) or an
3708    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3709    // Hostname forbids identically to the IPv4-literal arm below. Both
3710    // shapes silently fell through the `://` and `/` arms before this
3711    // lift and surfaced as a deep `label "<rest>:<port>" contains
3712    // invalid character ':'` diagnostic from the per-byte loop near the
3713    // bottom of this predicate, which named the offending byte but not
3714    // the canonical authoring fix — for the port case the author has to
3715    // know the `:entrada` block carries a separate `:port u16` slot
3716    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3717    // move the value over; for the IPv6 case the author has to know
3718    // Gateway API v1 forbids IP literals across the board. The contract
3719    // doc-comment above already promises "no port (`:8080`)" verbatim
3720    // in the rejected-shape enumeration but the predicate's
3721    // implementation refused the `:` only as a side-effect of the
3722    // per-label `[a-z0-9-]` character-class loop; this arm brings the
3723    // implementation in line with the documented contract by surfacing
3724    // the canonical fix at the top-level shape gate, peer with how the
3725    // `://` arm names the scheme prefix and the `/` arm names the
3726    // `:entrada :paths` axis. Same compounding trajectory the recent
3727    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3728    // — the typed slot's rejected set matches the apiserver's rejected
3729    // set, structurally, with a self-locating diagnostic at the
3730    // offending axis instead of a deep parser-shape leak.
3731    if host.contains(':') {
3732        return Err(AplicacaoError::EntradaHostInvalid {
3733            host: host.to_string(),
3734            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3735                     slot — a separate `u16` axis on the same `:entrada` block, \
3736                     defaulting to 8080 — not in the host body; drop the `:<port>` \
3737                     suffix and author the bare hostname. If you intended an IPv6 \
3738                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3739                     Hostname forbids IP literals identically to the IPv4-literal \
3740                     arm — use a DNS name)"
3741                .to_string(),
3742        });
3743    }
3744    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3745    // predicate — the same single source of truth every peer
3746    // ASCII-whitespace scan in caixa-core flows through: the four
3747    // typed-magnitude codec sites (`limits::parse_byte_size` backing
3748    // `:limits :memory`, `limits::parse_duration` backing `:limits
3749    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3750    // `aplicacao::rate_limit_codec::parse` backing `:politicas
3751    // :rate-limit`) and the shared duration codec
3752    // (`supervisor::duration_codec::parse`) backing `:supervisor
3753    // :restart-window` / `:politicas :timeout` / `:politicas
3754    // :circuit-breaker :window`. This landing closes the last string-typed
3755    // slot in caixa-core still calling `.bytes().any(|b|
3756    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3757    // across every typed slot now shares one predicate, so a future
3758    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3759    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3760    // deliberately excluded from the peer non-ASCII predicate) can
3761    // extend at this shared site in one edit rather than seven
3762    // independent scans diverging over time. Naming the offending byte
3763    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3764    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3765    // the offending byte verbatim" discipline every peer codec site
3766    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
3767    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
3768    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
3769        return Err(AplicacaoError::EntradaHostInvalid {
3770            host: host.to_string(),
3771            reason: format!(
3772                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
3773                 Hostname is a single-token DNS name — leading, trailing, \
3774                 or embedded whitespace breaks the K8s apiserver's Hostname \
3775                 regex at admission time; the paste-from-aligned-doc / \
3776                 paste-from-shell-history / paste-from-CSV footgun silently \
3777                 lands a multi-token blob in `:entrada :host`. Strip every \
3778                 whitespace byte and author the bare hostname — space \
3779                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
3780                 refuse identically)"
3781            ),
3782        });
3783    }
3784    // Peer of the ASCII-whitespace scan above: route the non-ASCII
3785    // subset of Unicode `White_Space` through the shared
3786    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
3787    // single source of truth every peer non-ASCII-whitespace scan in
3788    // caixa-core flows through: `limits::parse_byte_size` (`:limits
3789    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
3790    // `limits::parse_millicores` (`:limits :cpu`),
3791    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
3792    // and `supervisor::duration_codec::parse` (`:supervisor
3793    // :restart-window` / `:politicas :timeout` / `:politicas
3794    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
3795    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
3796    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
3797    // paste-from-web-doc), or an EM-SPACE-split host
3798    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
3799    // survived this predicate's ASCII byte-scan (none of the UTF-8
3800    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
3801    // `u8::is_ascii_whitespace`), then landed on the per-label
3802    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
3803    // predicate with the generic `label "…" must start and end with an
3804    // alphanumeric` diagnostic — a "far from source at build-time"
3805    // leak that names the label-shape violation but not the
3806    // paste-from-typography origin the author actually needs to fix.
3807    // Peer with the four codec sites the 1b75b38 landing pinned: the
3808    // typed slot's diagnostic axis names the offending codepoint
3809    // (`U+XXXX`) verbatim rather than laundering the value through a
3810    // downstream label-shape arm, so the author can grep their
3811    // caixa.lisp for the invisible codepoint at the surfaced position
3812    // rather than eyeball a multi-byte host for embedded NBSP / LINE
3813    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
3814    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
3815    // drift between any two typed-slot sites' non-ASCII-whitespace
3816    // rejection set becomes a single-edit fix at the shared predicate
3817    // rather than N independent inline scans diverging over time, and
3818    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
3819    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
3820    // `char::is_whitespace`" class the peer non-ASCII predicate's
3821    // doc-comment names as the follow-up trajectory) extends at the
3822    // shared predicate in one edit rather than seven.
3823    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
3824        return Err(AplicacaoError::EntradaHostInvalid {
3825            host: host.to_string(),
3826            reason: format!(
3827                "contains non-ASCII Unicode whitespace character {ch:?} \
3828                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
3829                 single-token DNS name limited to `[a-z0-9-]` labels; \
3830                 the paste-from-typography footgun silently lands an \
3831                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
3832                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
3833                 `U+3000`, and every other member of the Unicode \
3834                 `White_Space` property outside the ASCII byte range) \
3835                 in `:entrada :host`, which the K8s apiserver's \
3836                 Hostname regex refuses at admission time far from the \
3837                 caixa.lisp source line. Strip every non-ASCII \
3838                 whitespace character and author the bare hostname \
3839                 with only ASCII bytes (write \"checkout.quero.cloud\" \
3840                 verbatim)",
3841                codepoint = ch as u32,
3842            ),
3843        });
3844    }
3845
3846    // Strip the optional single leading wildcard label *before* the
3847    // trailing-dot check so the bare `"*."` form surfaces the more
3848    // self-locating "wildcard without domain" diagnostic instead of
3849    // the generic "trailing dot" one.
3850    let (had_wildcard, rest) = match host.strip_prefix("*.") {
3851        Some(r) => (true, r),
3852        None => (false, host),
3853    };
3854    if had_wildcard && rest.is_empty() {
3855        return Err(AplicacaoError::EntradaHostInvalid {
3856            host: host.to_string(),
3857            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
3858        });
3859    }
3860    if rest.contains('*') {
3861        return Err(AplicacaoError::EntradaHostInvalid {
3862            host: host.to_string(),
3863            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
3864                     no inner or trailing `*` labels"
3865                .to_string(),
3866        });
3867    }
3868    if rest.ends_with('.') {
3869        return Err(AplicacaoError::EntradaHostInvalid {
3870            host: host.to_string(),
3871            reason: "must not have a trailing `.` (Gateway API hostnames are not \
3872                     fully-qualified with a root dot; the apiserver regex rejects \
3873                     trailing dots)"
3874                .to_string(),
3875        });
3876    }
3877
3878    // Reject pure IPv4 literals: four dot-separated labels, every
3879    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
3880    // literals as Hostnames.
3881    let labels: Vec<&str> = rest.split('.').collect();
3882    if labels.len() == 4
3883        && labels
3884            .iter()
3885            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
3886    {
3887        return Err(AplicacaoError::EntradaHostInvalid {
3888            host: host.to_string(),
3889            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
3890                     literals; use a DNS name)"
3891                .to_string(),
3892        });
3893    }
3894
3895    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
3896    // hyphen, with non-hyphen at both boundaries.
3897    for label in &labels {
3898        if label.is_empty() {
3899            return Err(AplicacaoError::EntradaHostInvalid {
3900                host: host.to_string(),
3901                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
3902            });
3903        }
3904        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
3905            return Err(AplicacaoError::EntradaHostInvalid {
3906                host: host.to_string(),
3907                reason: format!(
3908                    "label {label:?} exceeds DNS-1123 label max length of \
3909                     {cap} bytes (got {} bytes)",
3910                    label.len(),
3911                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
3912                ),
3913            });
3914        }
3915        let bytes = label.as_bytes();
3916        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
3917            return Err(AplicacaoError::EntradaHostInvalid {
3918                host: host.to_string(),
3919                reason: format!(
3920                    "label {label:?} must start and end with an alphanumeric \
3921                     (no leading or trailing `-`)"
3922                ),
3923            });
3924        }
3925        for &b in bytes {
3926            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
3927            if !valid {
3928                let msg = if b.is_ascii_uppercase() {
3929                    format!(
3930                        "label {label:?} contains uppercase character {ch:?} \
3931                         (Gateway API hostnames are lowercase-only; use {lower:?})",
3932                        ch = b as char,
3933                        lower = label.to_ascii_lowercase()
3934                    )
3935                } else if b == b'_' {
3936                    format!(
3937                        "label {label:?} contains `_` (Gateway API hostnames \
3938                         allow only `[a-z0-9-]`; use `-` instead)"
3939                    )
3940                } else {
3941                    format!(
3942                        "label {label:?} contains invalid character {ch:?} \
3943                         (Gateway API hostnames allow only `[a-z0-9-]`)",
3944                        ch = b as char
3945                    )
3946                };
3947                return Err(AplicacaoError::EntradaHostInvalid {
3948                    host: host.to_string(),
3949                    reason: msg,
3950                });
3951            }
3952        }
3953    }
3954    Ok(())
3955}
3956
3957/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
3958/// would refuse at admission time. Thin wrapper around
3959/// [`crate::render::is_gateway_api_http_path`] that maps the shared
3960/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
3961/// variant, preserving the more self-locating
3962/// [`AplicacaoError::EntradaPathEmpty`] /
3963/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
3964/// path fails those narrower invariants first.
3965///
3966/// The contract is the canonical HTTP-path grammar — `1..=
3967/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
3968/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
3969/// whitespace/control/non-ASCII bytes — shared with the
3970/// `:contratos :endpoint` axis through the lifted predicate so drift
3971/// between either landing site and the K8s apiserver-side
3972/// HTTPPathMatch.value OpenAPI schema is a build error visible at
3973/// the predicate, not a per-renderer "this passed validate but failed
3974/// admission" surprise. The diagnostic carries the offending `path:`
3975/// verbatim plus a parser-shaped `reason:` naming the specific
3976/// violation, so the author can grep their caixa.lisp for `:paths`
3977/// and fix it in one edit. Same diagnostic shape as
3978/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
3979/// axis.
3980fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
3981    // Empty and missing-leading-`/` are already gated at the call
3982    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
3983    // checking here keeps the per-axis narrower diagnostics in force
3984    // when the predicate is reached directly (and `is_gateway_api_http_path`
3985    // itself defends against `bytes[0]`-style indexing on empty
3986    // input).
3987    if path.is_empty() {
3988        return Err(AplicacaoError::EntradaPathEmpty);
3989    }
3990    if !path.starts_with('/') {
3991        return Err(AplicacaoError::EntradaPathNotAbsolute {
3992            path: path.to_string(),
3993        });
3994    }
3995    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
3996        AplicacaoError::EntradaPathInvalid {
3997            path: path.to_string(),
3998            reason,
3999        }
4000    })
4001}
4002
4003mod rate_limit_codec {
4004    // `Duration` is no longer named here — the codec routes through
4005    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4006    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4007    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4008    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4009    // closed-set enum's arm-table rather than through vestigial free-helper
4010    // delegates.
4011    use super::{RateLimit, RateLimitUnit};
4012    use serde::{Deserialize, Deserializer, Serializer};
4013
4014    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4015        match v {
4016            Some(rl) => s.serialize_str(&render(*rl)),
4017            None => s.serialize_none(),
4018        }
4019    }
4020
4021    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4022        let opt: Option<String> = Option::deserialize(d)?;
4023        match opt {
4024            None => Ok(None),
4025            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4026        }
4027    }
4028
4029    fn parse(s: &str) -> Result<RateLimit, String> {
4030        // Whitespace-rejection arm — peer with the leading-`+`
4031        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4032        // same canonical-form render-determinism axis. Until this gate
4033        // landed the parser silently tolerated leading / trailing /
4034        // internal whitespace via the top-level `s.trim()` and the
4035        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4036        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4037        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4038        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4039        // serde silently round-tripped to `"100/s"` on the next emit
4040        // (a *different* canonical string) — breaking the THEORY.md
4041        // Part V render-determinism contract on the same
4042        // canonical-form-drift axis the leading-`+` arm below (the
4043        // 4eeae98 predecessor) and the leading-zero arm below (the
4044        // 4f46830 predecessor) already close.
4045        //
4046        // The canonical author shape is `<integer>/<s|m|h>` with no
4047        // whitespace bytes anywhere — every string [`render`] emits
4048        // carries none, so the parser's accepted set must match for
4049        // serialize / deserialize to round-trip losslessly. This gate
4050        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4051        // `unit.trim()` calls below strict no-ops on the accepted set
4052        // (every byte-position match they would perform is now already
4053        // trimmed away by the accepted set itself), while the arm
4054        // surfaces every rejected whitespace-carrying shape with a
4055        // self-locating diagnostic naming the offending byte and the
4056        // canonical form the author intended, peer with every prior
4057        // canonical-form-drift arm on this codec.
4058        //
4059        // Routed through the lifted
4060        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4061        // same source of truth the four peer typed-magnitude codec
4062        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4063        // `limits::parse_millicores`, `supervisor::duration_codec`)
4064        // share. `u8::is_ascii_whitespace()` at the predicate covers
4065        // the five WhatWG-conformant ASCII whitespace bytes (space,
4066        // tab, LF, FF, CR); the "single lifted predicate" discipline
4067        // the peer non-ASCII arm below carries on the strictly-
4068        // complementary Unicode `White_Space` class extends here to
4069        // the ASCII byte set as well.
4070        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4071            return Err(format!(
4072                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4073                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4074                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4075                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4076                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4077                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4078                 on first serialize — breaking the THEORY.md Part V render-determinism \
4079                 contract every typed slot carries. Strip every whitespace byte (write \
4080                 `\"100/s\"` verbatim)"
4081            ));
4082        }
4083        // Non-ASCII Unicode `White_Space` arm — the strictly-
4084        // complementary class the ASCII arm above cannot see.
4085        // `str::trim` at the top of every peer codec uses
4086        // `char::is_whitespace` (Unicode `White_Space`, strictly
4087        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4088        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4089        // survives the byte-scan (its UTF-8 bytes are not in
4090        // `is_ascii_whitespace`), gets silently stripped by the
4091        // top-level `s.trim()` below, and the value round-trips
4092        // through `render` to a *different* canonical form
4093        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4094        // render-determinism contract every typed slot carries.
4095        // Closed here (`:politicas :rate-limit`) and at the three
4096        // peer codec sites (`limits::parse_byte_size`,
4097        // `limits::parse_duration`, `supervisor::duration_codec`)
4098        // through the shared
4099        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4100        // — the "single lifted predicate across all four codec sites
4101        // in one follow-up run" the 24a8ad4 commit body's `Forward
4102        // compounding` bullet named as the next compounding step.
4103        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4104            return Err(format!(
4105                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4106                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4107                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4108                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4109                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4110                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4111                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4112                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4113                 silently strips it at parse entry, and the value round-trips through \
4114                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4115                 serialize — breaking the THEORY.md Part V render-determinism contract \
4116                 every typed slot carries. Strip every non-ASCII whitespace character \
4117                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4118                cp = ch as u32
4119            ));
4120        }
4121        let s = s.trim();
4122        let (rate_str, unit) = s
4123            .split_once('/')
4124            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4125        let rate_trim = rate_str.trim();
4126        // The canonical authoring form for `:politicas :rate-limit` is
4127        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4128        // non-negative integer with no decimal point and no leading
4129        // sign, so the parser's accepted set must match for
4130        // serialize/deserialize to round-trip without canonical-form
4131        // drift. Until this gate landed the parser accepted any
4132        // `u32::from_str`-shaped magnitude — and current Rust
4133        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4134        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4135        // serde silently round-tripped to `"100/s"` on the next emit
4136        // (a *different* canonical string) — breaking the THEORY.md
4137        // Part V render-determinism contract on the fifth typed-codec
4138        // surface in caixa-core (peer with the four duration codecs the
4139        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4140        // already covered: `supervisor::duration_codec` backing three
4141        // typed-duration slots, `limits::parse_duration` backing
4142        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4143        // `:limits :memory`). The fractional / decimal-shaped sibling
4144        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4145        // existing rejection arm, but the diagnostic is value-laundered
4146        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4147        // doesn't name the canonical-form remediation or the round-trip
4148        // drift the next emit would produce); this gate lifts the
4149        // fractional arm onto the same canonical-form diagnostic the
4150        // peer codecs carry.
4151        //
4152        // Strict canonical form: every byte of the magnitude is an
4153        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4154        // inputs the gate distinguishes "non-canonical-but-numeric"
4155        // (parses as f64 or i64 — surfaced with a self-locating
4156        // diagnostic naming the canonical authoring form and the
4157        // round-trip drift the rejected shape would produce on first
4158        // serialize) from "garbage" (parses as neither — surfaced with
4159        // the existing narrower `"not a u32"` wording so its
4160        // diagnostic shape remains stable for the parser-shape footgun
4161        // case).
4162        //
4163        // Routed through the lifted
4164        // [`crate::render::is_digit_only_magnitude`] predicate — the
4165        // same source of truth the four peer typed-magnitude codec
4166        // sites share.
4167        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4168        if !digit_only {
4169            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4170            if numeric {
4171                return Err(format!(
4172                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4173                     canonical authoring form for `:politicas :rate-limit` is \
4174                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4175                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4176                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4177                     through `render` to a *different* canonical form (`\"1/s\"`, \
4178                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4179                     THEORY.md Part V render-determinism contract every typed slot \
4180                     carries. Pick an integer rate that fits the desired window \
4181                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4182                ));
4183            }
4184            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4185        }
4186        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4187        // (4eeae98's predecessor) on the same canonical-form
4188        // render-determinism axis. The digit-only gate accepts
4189        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4190        // them losslessly (= 100, 0, 7), but `render` emits the
4191        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4192        // a *different* canonical string on the next emit, breaking
4193        // the THEORY.md Part V render-determinism contract the same
4194        // way `"+100/s"` did before the leading-`+` arm landed. The
4195        // single-byte magnitude `"0"` itself round-trips losslessly
4196        // through `render` (`render(0)` emits `"0/s"`) — the
4197        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4198        // what refuses rate-zero authoring, so `"0/s"` stays in the
4199        // accepted set at this codec layer and the diagnostic
4200        // partitioning between canonical-form drift (this arm) and
4201        // semantic-zero (the downstream gate) remains stable.
4202        // Peer with the future leading-zero arms on the three peer
4203        // typed-magnitude codecs the trajectory acknowledges:
4204        // `supervisor::duration_codec`, `limits::parse_duration`,
4205        // `limits::parse_byte_size` — each carries the same
4206        // canonical-form-drift class today; this gate lands the
4207        // discipline on the fourth typed-magnitude codec in
4208        // caixa-core first because the peer `"+100/s"` arm above is
4209        // the closest predecessor on the trajectory.
4210        //
4211        // Routed through the lifted
4212        // [`crate::render::is_leading_zero_padded_magnitude`]
4213        // predicate — the same source of truth the four peer
4214        // typed-magnitude codec sites share.
4215        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4216            return Err(format!(
4217                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4218                 canonical authoring form for `:politicas :rate-limit` is \
4219                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4220                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4221                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4222                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4223                 first serialize — breaking the THEORY.md Part V render-determinism \
4224                 contract every typed slot carries. Strip the leading zeros (write \
4225                 `\"100/s\"` instead of `\"0100/s\"`)"
4226            ));
4227        }
4228        // The digit-only gate guarantees every byte is `[0-9]`, and
4229        // the leading-zero arm above guarantees the magnitude is
4230        // either the single byte `"0"` or starts with `[1-9]`, so
4231        // the only way `u32::from_str` can fail here is overflow
4232        // (the magnitude exceeds `u32::MAX`). Surface that with an
4233        // overflow-shaped wording so the diagnostic names the
4234        // offending magnitude verbatim rather than collapsing onto
4235        // the non-canonical arm. Same shape
4236        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4237        // duration-codec axis.
4238        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4239            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4240        })?;
4241        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4242        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4243        // arm reads the `&str → Duration` projection through the
4244        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4245        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4246        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4247        // module-private `rate_limit_window_from_unit` free helper the
4248        // predecessor 61421a6 left as the last unlifted delegate on this
4249        // axis. One typed dispatch on the substrate primitive instead of
4250        // one runtime call through the free-helper delegate; the sole
4251        // production consumer of the `&str → Duration` axis (this parse
4252        // arm) now reaches for exactly one typed method on the closed-set
4253        // enum, sibling to the codec's render arm's
4254        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4255        // `Duration → RateLimitUnit` axis and to the validate gate's
4256        // [`super::RateLimit::canonical_unit`] shape-probe on the
4257        // canonical-window axis. A future rate-limit-unit addition (a
4258        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4259        // daily-bucket support, a `"ms"` sub-second window once
4260        // high-throughput per-edge policies come into scope per
4261        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4262        // on the closed-set enum, and the compiler enforces exhaustiveness
4263        // on every consumer's `match self` arms — this parse arm's
4264        // accepted-suffix set, the render arm's emitted-suffix set, the
4265        // validate gate's canonical-window set, and every future
4266        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4267        // by construction.
4268        let unit = unit.trim();
4269        let window = RateLimitUnit::window_from_suffix(unit)
4270            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4271        Ok(RateLimit { rate, window })
4272    }
4273
4274    fn render(rl: RateLimit) -> String {
4275        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4276        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4277        // this render arm reads the `Duration → RateLimitUnit` projection
4278        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4279        // (returns `None` on every non-canonical window — the sub-second /
4280        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4281        // formats the returned typed enum through its
4282        // [`std::fmt::Display`] impl (which routes through
4283        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4284        // the substrate primitive instead of one runtime `find_map`
4285        // walk through the free-helper delegate chain
4286        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4287        // sole production consumer was this arm; every other consumer of
4288        // the `Duration → unit` axis — the validate gate below and the
4289        // future M4 per-Aplicacao Envoy config reconciler — now reads
4290        // the same typed method).
4291        //
4292        // A future rate-limit-unit addition (a `"d"` day suffix once
4293        // Envoy's `rate_limit_action` grows daily-bucket support) is
4294        // one variant + one arm per method on the closed-set enum, and
4295        // the compiler enforces exhaustiveness on every consumer's
4296        // `match self` arms — the codec's `parse` accepted-suffix set,
4297        // this render arm's emitted-suffix set, the validate gate's
4298        // canonical-window set, and every future per-`:contratos`-edge
4299        // rate-limit-override overlay all pick it up by construction.
4300        if let Some(unit) = rl.canonical_unit() {
4301            format!("{}/{unit}", rl.rate())
4302        } else {
4303            // Defensive fallback for non-canonical windows. Note:
4304            // [`AplicacaoSpec::validate_politicas`] rejects any
4305            // non-canonical `:rate-limit :window` via
4306            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4307            // a validated `RateLimit` never reaches this branch. The
4308            // emitted `<n>/<k>s` form is *not* round-trippable through
4309            // [`parse`] (which accepts only the closed-set
4310            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4311            // explicit count) — the validate gate is what makes the
4312            // round-trip a structural property; this branch exists only
4313            // so a programmatic non-validated serialize doesn't panic.
4314            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4315        }
4316    }
4317}
4318
4319// ── placement strategy ───────────────────────────────────────────────
4320
4321/// How the Aplicacao distributes across clusters. Three options:
4322///
4323/// - `SingleNode` — one cluster runs the app at a time; takeover on
4324///   death (Erlang/OTP distributed-app semantics).
4325/// - `Replicated` — every named cluster runs an instance (active-active).
4326/// - `Sharded` — entities distribute by hash key across clusters
4327///   (Akka cluster sharding).
4328#[derive(
4329    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4330)]
4331pub enum PlacementStrategy {
4332    SingleNode,
4333    Replicated,
4334    Sharded,
4335}
4336
4337impl Default for PlacementStrategy {
4338    fn default() -> Self {
4339        Self::Replicated
4340    }
4341}
4342
4343impl PlacementStrategy {
4344    /// Exhaustive iteration surface for every consumer that reads the
4345    /// full closed-set (the future M4 admission-webhook's accepted-
4346    /// strategy listing in its rejection body, a future `feira app
4347    /// placement --list` CLI-side surfacing of the accepted arm-set,
4348    /// any future round-trip fuzz harness). A future variant addition
4349    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4350    /// names as a trajectory item) extends this slice as a single edit
4351    /// and every consumer picks up the new entry by construction — the
4352    /// compiler-checked exhaustiveness on the sibling method `match`
4353    /// arms is the build-time guarantee that no arm forgets to grow.
4354    /// Same shape as the sibling closed-set typed enums'
4355    /// [`RateLimitUnit::ALL`] (6bce03d) and
4356    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4357    /// surfaces — the third closed-set typed enum on the caixa surface
4358    /// to converge onto the same discipline.
4359    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4360
4361    /// Canonical camelCase-schema discriminator scalar this variant
4362    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4363    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4364    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4365    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4366    /// every substrate consumer that dispatches on the strategy (the
4367    /// `lareira-fleet-programs` aggregator, the future `app-operator`
4368    /// reconciler, the M3 Adaptive compression pass) reads the same
4369    /// byte-string the `Serialize` derive emits — the pin test in
4370    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4371    /// asserts the two paths agree.
4372    #[must_use]
4373    pub const fn as_str(self) -> &'static str {
4374        match self {
4375            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4376            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4377            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4378        }
4379    }
4380
4381    /// Substrate-canonical reverse projection on the `:placement
4382    /// :estrategia` closed-set axis — parses the camelCase-schema
4383    /// discriminator scalar back to the typed variant, or `None` when
4384    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4385    /// emits. Dispatches on the same lifted
4386    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4387    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4388    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4389    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4390    /// the round-trip migrate through one caixa-core edit on any future
4391    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4392    /// §II.5 hint names as a trajectory item lands one variant + one
4393    /// arm per method and the compiler enforces exhaustiveness on every
4394    /// consumer's `match self` arms).
4395    ///
4396    /// Prior to this lift the substrate carried only the forward
4397    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4398    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4399    /// derive that emits the same byte-string under
4400    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4401    /// consumer that wanted to parse a wire-form strategy scalar had to
4402    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4403    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4404    /// compile-time link back to the typed variant's canonical lifted
4405    /// constant. A future variant rename or a per-arm serde-attribute
4406    /// drift would silently split the wire byte-string one non-serde
4407    /// consumer parsed from the one the emitter wrote, with the
4408    /// failure surfacing at parse time far from the rebrand commit.
4409    ///
4410    /// Same closed-set-reverse-projection discipline the sibling
4411    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4412    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4413    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4414    /// defining `:placement :estrategia` closed-set axis, the third
4415    /// substrate-side closed-set typed enum to converge on the two-way
4416    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4417    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4418    /// and side-step the [`std::str::FromStr`]-collision clippy
4419    /// (`clippy::should_implement_trait`) the plain `from_str` name
4420    /// carries; a future explicit [`std::str::FromStr`] impl can layer
4421    /// on top by delegating to this canonical arm-dispatch method.
4422    ///
4423    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4424    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4425    /// picks the diagnostic form appropriate for its use site — a
4426    /// future `feira app placement --set` CLI-side arg-parse that wants
4427    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4428    /// Sharded)"` diagnostic builds one on top by iterating
4429    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4430    /// path folds `None` onto its per-CR structured refusal body.
4431    #[must_use]
4432    pub fn from_wire(s: &str) -> Option<Self> {
4433        match s {
4434            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4435            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4436            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4437            _ => None,
4438        }
4439    }
4440}
4441
4442/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4443/// the pretty-printed byte-string every consumer that formats the strategy
4444/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4445/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4446/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4447/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4448/// admission-webhook rejection body) reaches for the same lifted
4449/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4450/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4451/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4452/// `Serialize` derive already emits under
4453/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4454/// [`PlacementStrategy::as_str`] helper already returns.
4455///
4456/// Until this lift landed the sibling OTP-shape typed enums —
4457/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4458/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4459/// so [`std::fmt::Display`] routes through the same discriminant string
4460/// the wire format emits) — carried a stable [`std::fmt::Display`]
4461/// surface but [`PlacementStrategy`] did not; every consumer reaching
4462/// for a strategy byte-string past the wire format had to pick between
4463/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4464/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4465/// derive), any two of which a future variant rename or
4466/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4467/// desynchronize — with the failure surfacing as a downstream renderer /
4468/// operator's per-strategy dispatch reading one spelling while the wire
4469/// format emitted another, far from the source rebrand commit and with
4470/// no field naming the drift. Routing `Display` through
4471/// [`PlacementStrategy::as_str`] makes the three paths
4472/// (`Debug` for structural inspection, `Display` for user-facing text,
4473/// `Serialize` for the wire format) converge on the same lifted
4474/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4475/// the diagnostic byte-string, and the pretty-printed byte-string move
4476/// as a single unit through one canonical declaration each, by
4477/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4478/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4479/// closes the third path.
4480///
4481/// Pin tests
4482/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4483/// and
4484/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4485/// assert the three paths agree byte-for-byte on every variant, so a
4486/// future variant rename or per-arm serde attribute drift is a build
4487/// error visible at caixa-core test time, not a silent per-consumer
4488/// dispatch miss at apply / reconcile time.
4489impl std::fmt::Display for PlacementStrategy {
4490    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4491        f.write_str(self.as_str())
4492    }
4493}
4494
4495/// Where the Aplicacao runs.
4496#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4497#[serde(rename_all = "camelCase")]
4498pub struct Placement {
4499    /// Distribution strategy.
4500    #[serde(default)]
4501    pub estrategia: PlacementStrategy,
4502
4503    /// Named clusters that host this Aplicacao. Required for
4504    /// `Replicated` and `SingleNode`; for `Sharded` declares the
4505    /// shard pool.
4506    #[serde(default)]
4507    pub clusters: Vec<String>,
4508
4509    /// Optional hint to the placement engine: `"data-locality"`,
4510    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4511    #[serde(default, skip_serializing_if = "Option::is_none")]
4512    pub affinity: Option<String>,
4513
4514    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4515    #[serde(default, skip_serializing_if = "Option::is_none")]
4516    pub shard_key: Option<String>,
4517}
4518
4519impl Placement {
4520    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4521    /// `:shard-key` extractor-expression scalar accessor every consumer
4522    /// of the Aplicacao's hash-keyed distribution routing keys off —
4523    /// returns the author-declared `:placement :shard-key` byte-string
4524    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4525    /// own `Option<String>` storage; `None` when the slot is absent
4526    /// (the canonical shape under `:estrategia Replicated` /
4527    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4528    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4529    /// partition — `validate` refuses any `Placement` past this call
4530    /// that lands `Some` on a non-`Sharded` strategy or `None` on
4531    /// `Sharded`).
4532    ///
4533    /// The `:placement :shard-key` slot carries the Akka-style
4534    /// cluster-sharding entity-id extractor expression
4535    /// (MESH-COMPOSITION §II.4) — validated by
4536    /// [`validate_placement_shard_key`] to be a non-empty printable-
4537    /// ASCII single-token reference (`tenantId`, `$tenantId`,
4538    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4539    /// future M4 Akka-style cluster-sharding reconciler hashes without
4540    /// re-validating at the runtime layer), and every downstream
4541    /// consumer that reads the key keys off this scalar (the
4542    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4543    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4544    /// declared-but-inert refusal diagnostic, the caixa-mesh
4545    /// per-Aplicacao `placement.shardKey` emit path the substrate
4546    /// operator's per-entity hash-routing reader consumes, the future
4547    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4548    /// per-shard-key resolver).
4549    ///
4550    /// Prior to this lift the `.shard_key` field was accessed inline at
4551    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4552    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4553    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4554    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4555    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4556    /// — two open-coded field-accesses that expressed no compile-time
4557    /// link back to the typed slot. A future extension of the
4558    /// `:placement :shard-key` axis to a richer author surface — a
4559    /// per-cluster override the operator pins through a future
4560    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4561    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4562    /// alias table the M4 CR materializer resolves per-CR, a
4563    /// per-Aplicacao dynamic `:shard-key` derivation the future
4564    /// adaptive placement engine computes from `:affinity` weights —
4565    /// would have had to be threaded through both open-coded copies in
4566    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4567    /// arm refusal would silently disagree on which extractor
4568    /// expression a given Placement resolves to. Lifting the resolution
4569    /// rule to a typed method on the substrate primitive means every
4570    /// downstream consumer of the Aplicacao's per-`:placement`
4571    /// hash-key surface reaches for exactly one typed dispatch — the
4572    /// resolver's accept-set migrates as a unit on any future axis
4573    /// addition.
4574    ///
4575    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4576    /// [`WitContract::destination`] / [`WitContract::world_ref`]
4577    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4578    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4579    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4580    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4581    /// typed dispatch on the substrate primitive, thin projections at
4582    /// each consumer" discipline extended onto the per-`:placement`
4583    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4584    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4585    /// — opens the "optional per-slot scalar" projection pattern the
4586    /// sibling per-`:placement` `:affinity`, per-`:politicas`
4587    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4588    /// match the storage field's name; the accessor's identity name
4589    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4590    /// slot's docstring already carries.
4591    #[must_use]
4592    pub fn shard_key(&self) -> Option<&str> {
4593        self.shard_key.as_deref()
4594    }
4595
4596    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4597    /// compression-hint scalar accessor every weighting-consumer of the
4598    /// Aplicacao's per-hint routing surface keys off — returns the
4599    /// author-declared `:placement :affinity` byte-string verbatim as
4600    /// an `Option<&str>`, borrowed from the typed slot's own
4601    /// `Option<String>` storage; `None` when the slot is absent (the
4602    /// canonical shape of an Aplicacao that leaves the compression
4603    /// weighting up to the placement engine's cluster-default arm — no
4604    /// author-authored `data-locality` / `low-latency` / etc. hint
4605    /// biases the routing).
4606    ///
4607    /// The `:placement :affinity` slot carries the M3 Adaptive-
4608    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4609    /// by [`validate_placement_affinity`] to be a DNS-1123 label
4610    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4611    /// K8s-conformant label-selector shape every apiserver-side pod-
4612    /// affinity / node-affinity materializer already gates on
4613    /// admission), and every downstream consumer that reads the hint
4614    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4615    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4616    /// `placement.affinity` overlay emit path the substrate operator's
4617    /// per-hint weighting-consumer reads, the future M4
4618    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4619    /// pod-affinity / node-affinity selector resolver).
4620    ///
4621    /// Prior to this lift the `.affinity` field was accessed inline at
4622    /// the sole caixa-core site — the
4623    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4624    /// `if let Some(a) = &self.placement.affinity { …
4625    /// validate_placement_affinity(a)? … }` cascade — one open-coded
4626    /// field-access that expressed no compile-time link back to the
4627    /// typed slot. A future extension of the `:placement :affinity`
4628    /// axis to a richer author surface — a per-cluster override the
4629    /// operator pins through a future `:placement :affinity-overrides`
4630    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4631    /// tenant hint alias table the M4 CR materializer resolves per-CR,
4632    /// a per-Aplicacao dynamic `:affinity` derivation the future
4633    /// adaptive placement engine computes from `:clusters` topology —
4634    /// would have had to be threaded through the open-coded copy in
4635    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4636    /// materializer reader that landed on the axis, or the per-hint
4637    /// value-shape gate and its downstream weighting consumers would
4638    /// silently disagree on which hint a given Placement resolves to.
4639    /// Lifting the resolution rule to a typed method on the substrate
4640    /// primitive means every downstream consumer of the Aplicacao's
4641    /// per-`:placement` compression-hint surface reaches for exactly
4642    /// one typed dispatch — the resolver's accept-set migrates as a
4643    /// unit on any future axis addition.
4644    ///
4645    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4646    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4647    /// optional-scalar axis — same "one typed dispatch on the substrate
4648    /// primitive, thin projections at each consumer" discipline extended
4649    /// onto the per-`:placement` M3-Adaptive-compression-hint
4650    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4651    /// return accessor on the M3 mesh-slot family; closes the last
4652    /// un-lifted per-`:placement` `Option<String>` axis. Named
4653    /// `affinity()` to match the storage field's name; the accessor's
4654    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4655    /// vocabulary the slot's docstring already carries.
4656    #[must_use]
4657    pub fn affinity(&self) -> Option<&str> {
4658        self.affinity.as_deref()
4659    }
4660
4661    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4662    /// strategy scalar accessor every consumer that dispatches on the
4663    /// Aplicacao's per-cluster distribution shape keys off — returns the
4664    /// author-declared `:placement :estrategia` variant verbatim as a
4665    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4666    /// `PlacementStrategy` storage.
4667    ///
4668    /// The `:placement :estrategia` slot carries the closed-set
4669    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4670    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4671    /// `Replicated` — active-active across every named cluster; `Sharded`
4672    /// — Akka-style hash-keyed entity distribution across the cluster pool
4673    /// per §II.4) that every downstream consumer of the Aplicacao's
4674    /// per-cluster fan-out shape keys off. Validated by
4675    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4676    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4677    /// matches!(estrategia, Sharded)` — the cross-slot partition the
4678    /// [`Placement::shard_key`] accessor's docstring pins), and every
4679    /// downstream consumer that reads the strategy keys off this scalar
4680    /// (the [`AplicacaoSpec::validate_placement`]
4681    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4682    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4683    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4684    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4685    /// declared-but-inert refusal's
4686    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4687    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4688    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4689    /// emit path the substrate operator's per-strategy fan-out reader
4690    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4691    /// materializer's per-strategy admission-webhook resolver).
4692    ///
4693    /// Prior to this lift the `.estrategia` field was accessed inline at
4694    /// four sites — the [`AplicacaoSpec::validate_placement`]
4695    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4696    /// `estrategia: self.placement.estrategia`, the same method's
4697    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4698    /// partition dispatch, the non-`Sharded`-arm
4699    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4700    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4701    /// per-Aplicacao strategy print line at
4702    /// `println!("… {} …", spec.placement.estrategia, …)`
4703    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4704    /// expressed no compile-time link back to the typed slot. A future
4705    /// extension of the `:placement :estrategia` axis to a richer author
4706    /// surface (a per-cluster override the operator pins through a future
4707    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4708    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4709    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4710    /// derivation the future adaptive placement engine computes from
4711    /// `:affinity` + `:clusters` topology) would have had to be threaded
4712    /// through every open-coded copy in lockstep — one consumer reading
4713    /// the raw variant while a peer read the operator-resolved variant
4714    /// would silently split the `PlacementWithoutClusters` /
4715    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4716    /// partition-dispatch input, a two-consumer split at the validator
4717    /// far from the source `caixa.lisp` with no field naming the
4718    /// strategy-drift root cause. Lifting the resolution rule to a typed
4719    /// method on the substrate primitive means every downstream consumer
4720    /// of the Aplicacao's per-`:placement` distribution-strategy surface
4721    /// reaches for exactly one typed dispatch — the resolver's accept-set
4722    /// migrates as a unit on any future axis addition.
4723    ///
4724    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4725    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4726    /// same "one typed dispatch on the substrate primitive, thin
4727    /// projections at each consumer" discipline extended onto the
4728    /// per-`:placement` distribution-strategy `Copy`-composite-enum
4729    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4730    /// family; first `Copy`-return accessor on the M3 mesh-slot
4731    /// `Placement` type — companion to the sibling per-`:placement`
4732    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4733    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4734    /// optional-scalar axes, closing the last unlifted per-`:placement`
4735    /// scalar-value axis (the closed-set `PlacementStrategy`
4736    /// distribution-strategy discriminator) so every downstream
4737    /// per-`:placement` reader now routes through a typed dispatch on
4738    /// the substrate primitive. Named `estrategia()` to match the storage
4739    /// field's name; the accessor's identity name maps onto the
4740    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4741    /// already carries.
4742    #[must_use]
4743    pub fn estrategia(&self) -> PlacementStrategy {
4744        self.estrategia
4745    }
4746
4747    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4748    /// per-cluster distribution-target slice accessor every consumer that
4749    /// walks the Aplicacao's declared cluster-pool keys off — returns the
4750    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4751    /// `&[String]` slice-view, borrowed from the typed slot's own
4752    /// `Vec<String>` storage (a zero-copy slice-view over the same
4753    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4754    /// through). Non-optional: the empty slice is the load-bearing
4755    /// pre-validation sentinel every downstream consumer of the paired
4756    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4757    /// off — every strategy in the closed
4758    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4759    /// requires a non-empty list (`SingleNode` / `Replicated` use the
4760    /// list as hosting / takeover candidates per Erlang/OTP distributed-
4761    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4762    /// shard pool per Akka cluster-sharding convention, §II.4), so the
4763    /// `.is_empty()` probe is the shared pre-condition every
4764    /// [`AplicacaoSpec::validate_placement`] arm heads on.
4765    ///
4766    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4767    /// 1123-label per-cluster distribution-target list — the same
4768    /// set-not-multiset shape the sibling `:membros :caixa` /
4769    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4770    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4771    /// pins the shape). Every downstream consumer that fans on the list
4772    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4773    /// pre-flight `.is_empty()` probe that trips
4774    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4775    /// per-cluster value-shape + duplicate-detection fan-out loop, the
4776    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4777    /// that materializes the list verbatim onto every
4778    /// programs.yaml entry the substrate operator's per-cluster
4779    /// `placement.clusters | contains .Values.cluster` filter reads,
4780    /// the `feira app graph` per-Aplicacao cluster print line, the
4781    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4782    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4783    /// placement engine's cluster-topology reader).
4784    ///
4785    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4786    /// inline at three production sites — the
4787    /// [`AplicacaoSpec::validate_placement`] pre-flight
4788    /// `self.placement.clusters.is_empty()` refusal probe, the same
4789    /// method's per-cluster validate loop's
4790    /// `for c in &self.placement.clusters` traversal head, and the
4791    /// `feira app graph` per-Aplicacao print line's
4792    /// `spec.placement.clusters` `{:?}` formatter argument
4793    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4794    /// that expressed no compile-time link back to the typed slot. A
4795    /// future extension of the `:placement :clusters` axis to a richer
4796    /// author surface (a per-tenant cluster-pool overlay the operator
4797    /// pins through a future `:placement :clusters-overrides` slot the
4798    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4799    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4800    /// the future M5 adaptive-placement engine computes from
4801    /// `:affinity` weights + live cluster-topology probes, a promotion
4802    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4803    /// partition once the substrate operator's cluster-membership
4804    /// reconciler comes into typed scope) would have had to be threaded
4805    /// through all three open-coded copies in lockstep or one consumer
4806    /// would silently disagree with the peers on which cluster-pool a
4807    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4808    /// reading the raw slot while the peer per-cluster validate loop
4809    /// read an operator-resolved slot would silently split the paired
4810    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4811    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4812    /// input from the pre-flight input, a three-consumer split at the
4813    /// validator and formatter far from the source `caixa.lisp` with
4814    /// no field naming the cluster-pool-drift root cause. Lifting the
4815    /// resolution rule to a typed method on the substrate primitive
4816    /// means every downstream consumer of the Aplicacao's
4817    /// per-`:placement` cluster-pool surface reaches for exactly one
4818    /// typed dispatch — the resolver's accept-set migrates as a unit
4819    /// on any future axis addition.
4820    ///
4821    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4822    /// slot — sibling to the seed M2
4823    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4824    /// slice-return accessor on the peer per-`:supervisor` static-
4825    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4826    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4827    /// primitive, thin projections at each consumer" discipline. The
4828    /// three peer `Vec`-carry axes still unlifted at the time of this
4829    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4830    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4831    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4832    /// [`crate::UpgradeFromEntry::instructions`]
4833    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4834    /// — inherit this accessor's discipline as future compounding runs
4835    /// migrate their consumers onto the shared slice-return shape.
4836    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4837    /// type, sibling to the two `Option<&str>`-return
4838    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4839    /// (74ec2d3) accessors and the `Copy`-return
4840    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4841    /// unlifted per-`:placement` field axis (the `Vec<String>`
4842    /// distribution-target-list carrier) so every downstream
4843    /// per-`:placement` reader now routes through a typed dispatch on
4844    /// the substrate primitive. Named `clusters()` to match the storage
4845    /// field's name verbatim and the tatara-lisp author-surface term
4846    /// (`:clusters`) the field's own docstring already carries; the
4847    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4848    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4849    /// for. Returns `&[String]` (not `&Vec<String>`) because every
4850    /// downstream consumer of the cluster list treats it as a read-only
4851    /// sequence — the slice-view is the narrowest borrow that supports
4852    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4853    /// `.len()`) without leaking the backing `Vec`'s
4854    /// grow/push/reserve surface that no consumer of the typed view
4855    /// reaches for (the storage-side `Vec` remains reachable through
4856    /// the `pub clusters` field for the mutation-carrying serde
4857    /// round-trip and per-test fixture-mutation paths).
4858    #[must_use]
4859    pub fn clusters(&self) -> &[String] {
4860        self.clusters.as_slice()
4861    }
4862}
4863
4864impl Default for Placement {
4865    fn default() -> Self {
4866        Self {
4867            estrategia: PlacementStrategy::default(),
4868            clusters: Vec::new(),
4869            affinity: None,
4870            shard_key: None,
4871        }
4872    }
4873}
4874
4875// ── external entry point ─────────────────────────────────────────────
4876
4877/// External entry point — what an outside caller sees. Renders to a
4878/// Gateway / Ingress + a route to the named member Servico.
4879#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4880#[serde(rename_all = "camelCase")]
4881pub struct Entrada {
4882    /// Public hostname (e.g. `"checkout.quero.cloud"`).
4883    pub host: String,
4884
4885    /// Member Servico the gateway routes to. Must be in `:membros`.
4886    pub para: String,
4887
4888    /// Optional path filter — if set, only matching paths route to
4889    /// this Aplicacao (the rest fall through to other route rules).
4890    #[serde(default)]
4891    pub paths: Vec<String>,
4892
4893    /// Default port on the destination Servico (the trigger.service.port).
4894    #[serde(default = "default_port")]
4895    pub port: u16,
4896}
4897
4898impl Entrada {
4899    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4900    /// every HTTPRoute-aware renderer keys off — returns the author-
4901    /// declared `:entrada :paths` list verbatim when non-empty, and the
4902    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4903    /// all fallback otherwise (so an Aplicacao author who declares an
4904    /// external `:entrada` block but no per-path rule surface still
4905    /// gets a route whose sole `HTTPPathMatch` matches every incoming
4906    /// request under the paired
4907    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4908    ///
4909    /// Prior to this lift the "if `:entrada :paths` is empty use the
4910    /// substrate catch-all; else return each declared path verbatim"
4911    /// cascade lived inline at
4912    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4913    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4914    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4915    /// substrate ships today, with no typed method on the substrate
4916    /// primitive that named the rule. A future path-resolution axis
4917    /// addition — a per-cluster `:entrada :default-path` override the
4918    /// operator pins through a future `:placement`-scoped slot, an
4919    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4920    /// admission-webhook floor that materializes the catch-all before
4921    /// the CR lands, a future per-`:entrada :paths` overlay from a
4922    /// per-cluster policy the future `feira app deploy` pipeline
4923    /// consumes — would have to be threaded through every renderer's
4924    /// inline copy of the cascade in lockstep or one consumer would
4925    /// silently disagree with the peers on which path list a given
4926    /// `:entrada` block resolves to. Lifting the rule to a typed
4927    /// method on the substrate primitive means every downstream
4928    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4929    /// per-cluster overlay resolver, every future per-Aplicacao
4930    /// snapshot renderer) reaches for exactly one typed dispatch —
4931    /// the resolver's accept-set moves as a unit on any future axis
4932    /// addition.
4933    ///
4934    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4935    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4936    /// per-`:entrada` scalar-value axes — extends the "one typed
4937    /// dispatch on the substrate primitive, thin projections at each
4938    /// consumer" discipline onto the per-`:entrada` path-list
4939    /// resolution axis every HTTPRoute-aware renderer consumes. Same
4940    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4941    /// sibling `:politicas` primitive — one typed method on the
4942    /// substrate primitive that names the cascade every renderer
4943    /// otherwise re-inlines.
4944    #[must_use]
4945    pub fn resolved_paths(&self) -> Vec<&str> {
4946        // Route the internal cascade-head + per-entry projection reads
4947        // through the lifted [`Self::paths`] slice accessor rather than
4948        // the raw `self.paths` field access — the substrate-primitive
4949        // per-`:entrada` path-list resolver's two internal reads now
4950        // key off the canonical raw-slot surface every downstream
4951        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4952        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4953        // entrada summary line's `{:?}` Debug print) routes through, so
4954        // any future rebrand on the typed slot's raw-slot reader lands
4955        // at exactly one place. Same two-consumer coherence discipline
4956        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4957        // the peer M3 mesh-slot `Vec<String>`-carry axis.
4958        if self.paths().is_empty() {
4959            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4960        } else {
4961            self.paths().iter().map(String::as_str).collect()
4962        }
4963    }
4964
4965    /// Substrate-canonical per-`:entrada` DNS-hostname singular
4966    /// accessor every Gateway-API `Listener.hostname` reader keys off
4967    /// — returns the author-declared `:entrada :host` byte-string
4968    /// verbatim as a `&str`, borrowed from the typed slot's own
4969    /// [`String`] storage.
4970    ///
4971    /// Named the "singular" half of the DNS-hostname resolver pair on
4972    /// the substrate primitive: the parent-Gateway per-listener
4973    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4974    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4975    /// hostname per listener), and this accessor is the typed dispatch
4976    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4977    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4978    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4979    /// per-Aplicacao ingress-hostname surface projects onto.
4980    ///
4981    /// Prior to this lift the `entrada.host.clone()` byte-string was
4982    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4983    /// per-listener singular `hostname:` axis
4984    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4985    /// per-HTTPRoute plural `spec.hostnames[]` axis
4986    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4987    /// consumers read the same `entrada.host` field but the two-site
4988    /// duplication expressed no compile-time contract that the singular
4989    /// Gateway-listener filter and the plural `HTTPRoute` filter list
4990    /// stay in lockstep on future extensions of the `:entrada` slot to
4991    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4992    /// overlay, a per-cluster SNI fan-out the operator pins through a
4993    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4994    /// Aplicacao` CR materializer's per-listener virtual-host filter
4995    /// admission-webhook overlay). Any such extension would have to be
4996    /// threaded through every renderer's inline copy of the resolution
4997    /// in lockstep or the Gateway listener's `hostname:` filter would
4998    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4999    /// — a Gateway-API-conformance divergence whose apply-time symptom
5000    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5001    /// `NoMatchingParent` — the API server rejects the route because
5002    /// its `hostnames[]` filter doesn't intersect the parent listener's
5003    /// `hostname` filter) is far from the source `caixa.lisp` and never
5004    /// surfaces in the emitted YAML. Lifting the singular and plural
5005    /// resolvers to typed methods on the substrate primitive means
5006    /// every consumer of the Aplicacao's ingress-hostname surface
5007    /// reaches for exactly one typed dispatch, and the pair-invariant
5008    /// `hostnames() == vec![hostname()]` pinned by the sibling
5009    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5010    /// keeps the two axes in lockstep by construction.
5011    ///
5012    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5013    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5014    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5015    /// the substrate primitive, thin projections at each consumer"
5016    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5017    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5018    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5019    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5020    /// `:entrada` scalar-value + list-value axes.
5021    #[must_use]
5022    pub fn hostname(&self) -> &str {
5023        self.host.as_str()
5024    }
5025
5026    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5027    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5028    /// keys off — returns the singleton `[hostname()]` list under
5029    /// today's single-hostname-per-Aplicacao author surface, and the
5030    /// authoritative multi-hostname list under a future
5031    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5032    ///
5033    /// Plural half of the DNS-hostname resolver pair — see the
5034    /// companion [`Entrada::hostname`] docstring for the two-consumer
5035    /// lift + pair-invariant discipline (`hostnames() ==
5036    /// vec![hostname()]`, pinned load-bearing by the sibling
5037    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5038    /// test).
5039    ///
5040    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5041    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5042    /// per-rule path-list axis — same `Vec<&str>` shape, same
5043    /// substrate-primitive-owns-the-resolver discipline extended to
5044    /// the per-HTTPRoute virtual-host filter-list axis.
5045    #[must_use]
5046    pub fn hostnames(&self) -> Vec<&str> {
5047        vec![self.hostname()]
5048    }
5049
5050    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5051    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5052    /// the author-declared `:entrada :para` byte-string verbatim as a
5053    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5054    ///
5055    /// The `:entrada :para` slot names the single member Servico the
5056    /// external Gateway routes to (validated by
5057    /// [`AplicacaoSpec::validate`] to be a
5058    /// [`Membro::caixa`] the Aplicacao declares — a stray
5059    /// `:para` that doesn't name a member is
5060    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5061    /// backend-attachment miss at cluster-apply time). Under today's
5062    /// single-destination author surface `:entrada :para` is the ingress
5063    /// apex Servico's canonical identity; under a hypothetical
5064    /// future multi-backend author surface (a `:entrada
5065    /// :split :backends` weighted-fan-out overlay for canary /
5066    /// blue-green traffic-split rollouts, per-path override for
5067    /// path-based per-Servico routing beyond the single-apex model,
5068    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5069    /// per-CR admission-webhook that promotes the scalar to a
5070    /// weighted list) this accessor is the substrate primitive's typed
5071    /// dispatch every downstream `HTTPRoute`-aware consumer routes
5072    /// through, so the resolution shape migrates as a unit on one
5073    /// caixa-core edit rather than a coordinated rewrite across every
5074    /// renderer's inline field-access.
5075    ///
5076    /// Prior to this lift the `entrada.para` byte-string was accessed
5077    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5078    /// `metadata.name` composer's per-destination discriminator arg
5079    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5080    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5081    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5082    /// (`entrada.para.clone()`,
5083    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5084    /// consumers read the same `entrada.para` field but the two-site
5085    /// duplication expressed no compile-time contract that the HTTPRoute
5086    /// name-discriminator and the per-rule backend name stay in
5087    /// lockstep on future extensions of the `:entrada` slot to a
5088    /// multi-destination author surface. Any such extension would have
5089    /// to be threaded through every renderer's inline copy of the
5090    /// destination projection in lockstep or the HTTPRoute
5091    /// `metadata.name` would silently reference a different destination
5092    /// than its own `backendRefs[]` — an operator-side
5093    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5094    /// grep-by-name lookup would land on a route whose `backendRefs[]`
5095    /// silently point at a peer Servico, dropping every external
5096    /// `:entrada` flow at the gateway with the destination-drift root
5097    /// cause invisible in the emitted YAML.
5098    ///
5099    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5100    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5101    /// the per-listener singular / per-HTTPRoute plural filter axes and
5102    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5103    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5104    /// typed dispatch on the substrate primitive, thin projections at
5105    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5106    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5107    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5108    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5109    /// sibling per-`:entrada` scalar-value + list-value axes — this
5110    /// accessor closes the last unlifted per-`:entrada` scalar axis
5111    /// (the destination-Servico byte-string) so every downstream
5112    /// per-`:entrada` reader now routes through a typed dispatch on
5113    /// the substrate primitive.
5114    #[must_use]
5115    pub fn destination(&self) -> &str {
5116        self.para.as_str()
5117    }
5118
5119    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5120    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5121    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5122    /// reader keys off — returns the author-declared `:entrada :port`
5123    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5124    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5125    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5126    /// [`AplicacaoError::EntradaPortZero`], not a silent
5127    /// admission-webhook rejection at cluster-apply time).
5128    ///
5129    /// The `:entrada :port` slot carries the destination Servico's
5130    /// canonical in-cluster L4 listener port (`trigger.service.port` on
5131    /// the `pleme-computeunit` library chart), and every downstream
5132    /// consumer that reads the port keys off this scalar (the
5133    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5134    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5135    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5136    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5137    /// CR materializer's per-Aplicacao gateway port resolver).
5138    ///
5139    /// Prior to this lift the `.port` field was accessed inline at two
5140    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5141    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5142    /// the [`AplicacaoSpec::port_for_destination`] resolver's
5143    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5144    /// open-coded field-accesses that expressed no compile-time link
5145    /// back to the typed slot. A future extension of the `:entrada :port`
5146    /// axis to a richer author surface — a per-cluster override the
5147    /// operator pins through a future `:placement :default-port` slot the
5148    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5149    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5150    /// heterogeneous listener ports, an M4
5151    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5152    /// admission-webhook floor that promotes the scalar to a
5153    /// per-destination map — would have had to be threaded through both
5154    /// open-coded copies in lockstep or the structural-floor validator
5155    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5156    /// silently disagree on which port a given [`Entrada`] resolves to.
5157    /// Lifting the resolution rule to a typed method on the substrate
5158    /// primitive means every downstream consumer of the Aplicacao's
5159    /// per-`:entrada` L4-port surface reaches for exactly one typed
5160    /// dispatch — the resolver's accept-set migrates as a unit on any
5161    /// future axis addition.
5162    ///
5163    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5164    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5165    /// accessors on the per-`:entrada` scalar-value axis — same "one
5166    /// typed dispatch on the substrate primitive, thin projections at
5167    /// each consumer" discipline extended onto the per-`:entrada`
5168    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5169    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5170    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5171    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5172    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5173    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5174    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5175    /// storage field's name; the accessor's identity name maps onto the
5176    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5177    /// already carries.
5178    #[must_use]
5179    pub fn port(&self) -> u16 {
5180        self.port
5181    }
5182
5183    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5184    /// slice accessor every HTTPRoute-aware renderer keys off when it
5185    /// wants the raw author-declared path-list (not the fallback-
5186    /// applied projection [`Self::resolved_paths`] returns) — returns
5187    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5188    /// borrowed from the typed slot's own [`Vec<String>`] storage.
5189    ///
5190    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5191    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5192    /// (1449891) closes the fallback-applying arm every per-Aplicacao
5193    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5194    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5195    /// catch-all; non-empty slot → per-entry verbatim projection); this
5196    /// accessor closes the raw-slot arm every consumer that must see the
5197    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5198    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5199    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5200    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5201    /// external-gateway summary line's `{:?}` Debug print — which must
5202    /// name the author's declaration, not the substrate's fallback, so
5203    /// an author reading their graph output can grep their caixa.lisp
5204    /// for the exact list they authored) routes through.
5205    ///
5206    /// Prior to this lift the `.paths` field was accessed inline at four
5207    /// production sites: the two internal reads in [`Self::resolved_paths`]
5208    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5209    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5210    /// value-shape gate's `for p in &e.paths` traversal head, and the
5211    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5212    /// Debug print — four open-coded field-accesses that expressed no
5213    /// compile-time link back to the typed slot. A future extension of
5214    /// the `:entrada :paths` axis to a richer author surface — a
5215    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5216    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5217    /// spec supports through `matches[].method`), a per-path per-header
5218    /// filter overlay (`matches[].headers[]`), a per-cluster override
5219    /// the operator pins through a future `:placement :path-overlay`
5220    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5221    /// per-CR admission-webhook that normalized the list at admission
5222    /// time — would have had to be threaded through every open-coded
5223    /// copy in lockstep or the validator's per-entry gate would silently
5224    /// disagree with the renderer's per-entry emit on which list a given
5225    /// `:entrada` block resolves to. Lifting the resolution to a typed
5226    /// method on the substrate primitive means every downstream consumer
5227    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5228    /// exactly one typed dispatch — the resolver's accept-set migrates
5229    /// as a unit on any future axis addition.
5230    ///
5231    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5232    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5233    /// carry axis — same "one typed dispatch on the substrate primitive,
5234    /// thin projections at each consumer" discipline extended onto the
5235    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5236    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5237    /// carrier) so every downstream per-`:entrada` reader now routes
5238    /// through a typed dispatch on the substrate primitive. Returns
5239    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5240    /// treats the list as a read-only sequence — the slice-view is the
5241    /// narrowest borrow that supports every present + roadmapped consumer
5242    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5243    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5244    /// view reaches for (the storage-side `Vec` remains reachable through
5245    /// the `pub paths` field for the mutation-carrying serde round-trip
5246    /// and per-test fixture-mutation paths).
5247    #[must_use]
5248    pub fn paths(&self) -> &[String] {
5249        self.paths.as_slice()
5250    }
5251}
5252
5253/// Canonical default L4 port every typed Servico exposes on its
5254/// in-cluster K8s Service (the `trigger.service.port` axis the
5255/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5256/// surface defaults to when the author omits the slot, and the
5257/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5258/// `:entrada` block matches the per-`:contratos` destination Servico).
5259/// The single source of truth all three typed-port consumers reach for:
5260///
5261///   - [`Entrada::port`]'s serde default (via the
5262///     [`default_port`] helper this constant feeds); the author surface
5263///     `(:entrada (:host … :para …))` without an explicit `:port` slot
5264///     reads back as a typed [`Entrada`] carrying this exact value;
5265///   - the
5266///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5267///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5268///     fallback, fired when the typed `:entrada` block doesn't name
5269///     the per-`:contratos` destination Servico — the typed
5270///     `:contratos` graph carries no per-destination port axis (the
5271///     destination port is the destination Servico's
5272///     `lareira-<nome>` chart's `trigger.service.port`, which the
5273///     Aplicacao-level renderer has no visibility into without a
5274///     resolver round-trip), so the renderer falls back to the
5275///     substrate's canonical Servico-port assumption — by
5276///     construction the same value the destination's own
5277///     `pleme-computeunit` chart emits, the same value the
5278///     destination's own typed `:entrada :port` slot defaults to;
5279///   - every future per-Servico renderer the absorption-roadmap
5280///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5281///     CR materializer's per-edge port resolver, the future
5282///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5283///     emitter's per-route bucket key, the future caixa-otel
5284///     collector-pipeline emitter's per-Servico scrape port).
5285///
5286/// Until this lift landed the value `8080` lived at two production-code
5287/// call-sites: the [`default_port`] helper at
5288/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5289/// and the `.unwrap_or(8080)` literal at
5290/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5291/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5292/// resolver). A future Servico-port rebrand — the substrate moving the
5293/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5294/// gateway grows direct `:80` listeners, to `8443` once the substrate
5295/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5296/// override the operator pins through a future
5297/// `:placement :default-port` slot — without a coordinated edit on
5298/// both sides would silently emit Servicos listening on one port and
5299/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5300/// The CNP's apply-time symptom (the policy is admitted but every L4
5301/// flow on the destination Servico's actual port silently drops because
5302/// it doesn't match the whitelisted port) is far from the rebrand
5303/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5304/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5305/// a shared constant closes the drift footgun structurally — both
5306/// consumers read from the same `u16`, so any rebrand reaches both
5307/// sites by construction.
5308///
5309/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5310/// per-renderer canonical-K8s-axis constant — the namespace string
5311/// and the canonical Servico port both lived as duplicated literals
5312/// across caixa-core / caixa-mesh / caixa-flux before their respective
5313/// lifts. Same "the typed constant lives in one place" discipline the
5314/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5315/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5316/// shared-string axes.
5317///
5318/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5319pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5320
5321/// Structural floor for the typed `:entrada :port` axis — every
5322/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5323/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5324///
5325/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5326/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5327/// interprets as "let the kernel pick a free port at bind time", not a
5328/// well-defined destination the substrate's per-`:entrada` Gateway API
5329/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5330/// carrying `port: 0` degenerates to a nominal-only routing target: the
5331/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5332/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5333/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5334/// at build time rather than at `kubectl apply` time), and the
5335/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5336/// (caixa-mesh/src/lib.rs:2657 through
5337/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5338/// [`Entrada::port`] typed value — silently emits a policy whose
5339/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5340/// actual listener, dropping every L4 flow at the eBPF data plane far
5341/// from the source caixa.lisp with no field naming the port-zero-drift
5342/// root cause.
5343///
5344/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5345/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5346/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5347/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5348/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5349/// well below `u32::MAX` and therefore need explicit typed caps).
5350///
5351/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5352/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5353/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5354/// `:port` inherits through the serde default hook; this constant names
5355/// the accept-set floor every declared port must satisfy. The pair is
5356/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5357/// substrate's default must satisfy its own accept-set floor by
5358/// construction) — a future rebrand that accidentally moved
5359/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5360/// negative-cast typo, a per-cluster override the operator pins through
5361/// a future `:placement :default-port` slot that lands out-of-range)
5362/// would silently invalidate the serde-default emission at every
5363/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5364/// invariant pin
5365/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5366/// closes the drift footgun at caixa-core build time.
5367///
5368/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5369/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5370/// has exactly one source of truth — the future M4
5371/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5372/// gateway resolver, the future per-Servico
5373/// `computeunit.trigger.service.port` renderer's per-CR port-value
5374/// validator, and every downstream test-fixture navigator asserting
5375/// the accept-set floor all read from one place. Same shape every
5376/// other typed bracket-floor / bracket-ceiling in this crate carries
5377/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5378/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5379/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5380/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5381/// [`POLICY_RATE_LIMIT_MAX`]).
5382pub const SERVICO_PORT_MIN: u16 = 1;
5383
5384const fn default_port() -> u16 {
5385    DEFAULT_SERVICO_PORT
5386}
5387
5388// ── the typed view ───────────────────────────────────────────────────
5389
5390/// Typed composition view of the flat Aplicacao slots on
5391/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5392/// validation + downstream renderer consumption.
5393#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5394#[serde(rename_all = "camelCase")]
5395pub struct AplicacaoSpec {
5396    pub membros: Vec<Membro>,
5397    pub contratos: Vec<WitContract>,
5398    pub politicas: MeshPolicy,
5399    pub placement: Placement,
5400    pub entrada: Option<Entrada>,
5401}
5402
5403impl AplicacaoSpec {
5404    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5405    /// per-Aplicacao member-list slice-return accessor every
5406    /// per-Aplicacao member-list reader keys off — returns the author-
5407    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5408    /// over the same backing buffer the raw `self.membros.as_slice()`
5409    /// field access borrows from.
5410    ///
5411    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5412    /// member list — the load-bearing identity of the application graph
5413    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5414    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5415    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5416    /// accessor) with a `:versao` semver-requirement string (through
5417    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5418    /// and every downstream consumer that fans on the member-set keys
5419    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5420    /// membership-lookup `HashSet<&str>` seed's collect input, the
5421    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5422    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5423    /// per-member DNS-1123 / semver-requirement / duplicate-detection
5424    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5425    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5426    /// programs.yaml per-`:membros` fan-out emitter's per-entry
5427    /// mapping-composition loop, the `feira app graph` per-Aplicacao
5428    /// member-count print line and per-member tree traversal,
5429    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5430    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5431    /// placement engine's per-member weight-topology reader).
5432    ///
5433    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5434    /// inline at six production sites — the [`AplicacaoSpec::validate`]
5435    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5436    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5437    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5438    /// probe, the same method's per-member `for m in &self.membros`
5439    /// validate-loop traversal head, the
5440    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5441    /// `for m in &self.membros` adjacency-list seed, the
5442    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5443    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5444    /// paired with the peer `for m in &spec.membros` per-entry fan-out
5445    /// loop, and the `feira app graph` per-Aplicacao print line's
5446    /// `spec.membros.len()` count formatter argument paired with the
5447    /// peer `for m in &spec.membros` per-member tree traversal — six
5448    /// open-coded field-accesses that expressed no compile-time link
5449    /// back to the typed slot. A future extension of the `:membros`
5450    /// axis to a richer author surface (a per-cluster member-set
5451    /// overlay the operator pins through a future
5452    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5453    /// roadmap acknowledges, a per-tenant member-alias table the M4
5454    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5455    /// CR at admission time, a per-Aplicacao dynamic member-set
5456    /// derivation the future adaptive-placement engine computes from
5457    /// weighted membership topology, a promotion of the plain
5458    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5459    /// Orleans-style virtual-actor dynamic-membership comes into typed
5460    /// scope) would have had to be threaded through all six open-coded
5461    /// copies in lockstep or one consumer would silently disagree with
5462    /// the peers on which member-set a given Aplicacao resolves to —
5463    /// the `HashSet<&str>` name-set seed reading the raw slot while
5464    /// the peer `.is_empty()` refusal probe read an operator-resolved
5465    /// slot would silently split the `:contratos` membership-lookup
5466    /// input from the pre-flight-refusal input, a six-consumer split
5467    /// at the validator + programs.yaml emitter + graph printer far
5468    /// from the source `caixa.lisp` with no field naming the member-
5469    /// set-drift root cause. Lifting the resolution rule to a typed
5470    /// method on the substrate primitive means every downstream
5471    /// consumer of the Aplicacao's per-`:membros` member-list surface
5472    /// reaches for exactly one typed dispatch — the resolver's accept-
5473    /// set migrates as a unit on any future axis addition.
5474    ///
5475    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5476    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5477    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5478    /// static-child-list `Vec`-carry axis, and to the M3
5479    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5480    /// on the peer per-`:placement` distribution-target-list `Vec`-
5481    /// carry axis. Same "one typed dispatch on the substrate primitive,
5482    /// thin projections at each consumer" discipline. The two peer
5483    /// `Vec`-carry axes still unlifted at the time of this lift —
5484    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5485    /// WIT-typed edge list) and
5486    /// [`crate::UpgradeFromEntry::instructions`]
5487    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5488    /// — inherit this accessor's discipline as future compounding runs
5489    /// migrate their consumers onto the shared slice-return shape.
5490    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5491    /// `AplicacaoSpec` type itself, extending the discipline beyond
5492    /// the inner per-slot types ([`crate::Placement`],
5493    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5494    /// view every renderer consumes. Named `membros()` to match the
5495    /// storage field's name verbatim and the tatara-lisp author-
5496    /// surface term (`:membros`) the field's own docstring already
5497    /// carries; the accessor's identity maps onto the canonical
5498    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5499    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5500    /// every downstream consumer of the member list treats it as a
5501    /// read-only sequence — the slice-view is the narrowest borrow
5502    /// that supports every present + roadmapped consumer
5503    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5504    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5505    /// the typed view reaches for (the storage-side `Vec` remains
5506    /// reachable through the `pub membros` field for the mutation-
5507    /// carrying serde round-trip and per-test fixture-mutation paths).
5508    #[must_use]
5509    pub fn membros(&self) -> &[Membro] {
5510        self.membros.as_slice()
5511    }
5512
5513    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5514    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5515    /// accessor every per-Aplicacao contract-list reader keys off —
5516    /// returns the author-declared `:contratos` list verbatim as a
5517    /// `&[WitContract]` slice-view over the same backing buffer the raw
5518    /// `self.contratos.as_slice()` field access borrows from.
5519    ///
5520    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5521    /// WIT-typed edge list — the load-bearing set of directed edges
5522    /// on the application graph whose nodes are the `:membros` entries
5523    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5524    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5525    /// six-tuple is the edge identity every downstream duplicate gate
5526    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5527    /// Servico caller name + a `:para` destination-Servico callee name
5528    /// (through the lifted [`WitContract::source`] +
5529    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5530    /// caller/callee-Servico axis) with a `:wit` world-reference
5531    /// (through the lifted [`WitContract::world_ref`] (0804823)
5532    /// accessor) and the target-shape-appropriate payload-carrier
5533    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5534    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5535    /// (ed22b66) accessor on the per-target-shape payload-carrier
5536    /// axis). Every downstream consumer that fans on the edge-set
5537    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5538    /// name-set / self-edge / target-shape / dedup fan-out loop, the
5539    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5540    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5541    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5542    /// grouping loop, the `feira app graph` per-Aplicacao contract-
5543    /// count print line and per-contract tree traversal, every future
5544    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5545    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5546    /// mesh-policy overlay resolver's per-contract typed-edge weight
5547    /// reader).
5548    ///
5549    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5550    /// accessed inline at four production sites — the
5551    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5552    /// per-edge validate-loop traversal head (which drives every
5553    /// per-edge name-set membership lookup, self-edge check,
5554    /// target-shape dispatch, and dedup `HashSet` insert), the
5555    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5556    /// `for c in &self.contratos` adjacency-list seed head (which
5557    /// drives every per-edge sync-vs-pub-sub partition and per-edge
5558    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5559    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5560    /// `BTreeMap` grouping loop head (which drives every per-CNP
5561    /// fan-out emit), and the `feira app graph` per-Aplicacao print
5562    /// line's `spec.contratos.len()` count formatter argument paired
5563    /// with the peer `for c in &spec.contratos` per-contract tree
5564    /// traversal — four open-coded field-accesses that expressed no
5565    /// compile-time link back to the typed slot. A future extension
5566    /// of the `:contratos` axis to a richer author surface (a
5567    /// per-cluster contract overlay the operator pins through a
5568    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5569    /// federation roadmap acknowledges, a per-tenant edge-policy
5570    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5571    /// materializer resolves per-CR at admission time, a per-edge
5572    /// weight scalar the future adaptive-placement engine reads to
5573    /// bias sync-subgraph routing, a promotion of the plain
5574    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5575    /// once virtual-actor-style dynamic-edge composition comes into
5576    /// typed scope) would have had to be threaded through all four
5577    /// open-coded copies in lockstep or one consumer would silently
5578    /// disagree with the peers on which edge-set a given Aplicacao
5579    /// resolves to — the validator's per-edge dedup `HashSet` seed
5580    /// reading the raw slot while the peer sync-cycle adjacency-list
5581    /// seed read an operator-resolved slot would silently split the
5582    /// build-time edge-set gate from the runtime deadlock-detection
5583    /// gate, a four-consumer split at the validator, the cycle
5584    /// detector, the CNP emitter, and the graph printer far from
5585    /// the source `caixa.lisp` with no field naming the edge-set-
5586    /// drift root cause. Lifting the resolution rule to a typed method on the
5587    /// substrate primitive means every downstream consumer of the
5588    /// Aplicacao's per-`:contratos` edge-list surface reaches for
5589    /// exactly one typed dispatch — the resolver's accept-set
5590    /// migrates as a unit on any future axis addition.
5591    ///
5592    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5593    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5594    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5595    /// static-child-list `Vec`-carry axis, to the M3
5596    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5597    /// on the peer per-`:placement` distribution-target-list `Vec`-
5598    /// carry axis, and to the immediately-adjacent sibling M3
5599    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5600    /// the peer per-`:membros` node-list `Vec`-carry axis — the
5601    /// per-`:contratos` edge-list accessor is the natural pair of
5602    /// the per-`:membros` node-list accessor (graph edges over graph
5603    /// nodes; every graph-shaped consumer reads both). Same "one
5604    /// typed dispatch on the substrate primitive, thin projections
5605    /// at each consumer" discipline. The last remaining `Vec`-carry
5606    /// axis still unlifted at the time of this lift —
5607    /// [`crate::UpgradeFromEntry::instructions`]
5608    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5609    /// list) — inherits this accessor's discipline as future
5610    /// compounding runs migrate its consumers onto the shared slice-
5611    /// return shape. Second `&[T]`-return accessor on the top-level
5612    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5613    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5614    /// `:contratos` are the two `Vec` fields on the outer typed
5615    /// composition view — `:politicas`, `:placement`, `:entrada` are
5616    /// scalar/option-shaped and already route through their per-slot
5617    /// accessor families). Named `contratos()` to match the storage
5618    /// field's name verbatim and the tatara-lisp author-surface term
5619    /// (`:contratos`) the field's own docstring already carries; the
5620    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5621    /// §III.1 vocabulary the slot's docstring already reaches for.
5622    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5623    /// every downstream consumer of the contract list treats it as a
5624    /// read-only sequence — the slice-view is the narrowest borrow
5625    /// that supports every present + roadmapped consumer
5626    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5627    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5628    /// the typed view reaches for (the storage-side `Vec` remains
5629    /// reachable through the `pub contratos` field for the mutation-
5630    /// carrying serde round-trip and per-test fixture-mutation paths).
5631    #[must_use]
5632    pub fn contratos(&self) -> &[WitContract] {
5633        self.contratos.as_slice()
5634    }
5635
5636    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5637    /// per-Aplicacao mesh-policy composite-reference accessor every
5638    /// per-Aplicacao policy-block reader keys off — returns the author-
5639    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5640    /// reference over the same backing storage the raw `&self.politicas`
5641    /// field access borrows from.
5642    ///
5643    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5644    /// mesh-policy composite — the load-bearing container of every
5645    /// mesh-level operational-policy axis every downstream mesh-artifact
5646    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5647    /// mesh-policy overlay is the single typed surface a
5648    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5649    /// from). Every per-`:politicas` axis threads through a lifted
5650    /// per-slot accessor on the [`MeshPolicy`] type: the
5651    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5652    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5653    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5654    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5655    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5656    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5657    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5658    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5659    /// accessor. Every downstream consumer that reaches for a policy
5660    /// axis first passes through this outer accessor onto the composite
5661    /// and then dispatches onto the per-axis accessor — the two-level
5662    /// dispatch means every per-`:politicas` reader now routes through
5663    /// a typed dispatch on the substrate primitive at both altitudes.
5664    ///
5665    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5666    /// accessed inline at four production sites — the
5667    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5668    /// &self.politicas;` traversal seed (which drives every per-axis
5669    /// zero-floor + upper-cap + canonical-form bracket dispatch through
5670    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5671    /// `p.rate_limit()` on the axis-level lifted accessors), the
5672    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5673    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5674    /// chain (which drives every per-`(:de, :para)` CNP
5675    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5676    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5677    /// timeout + retry overlay emitter's paired
5678    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5679    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5680    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5681    /// open-coded outer-field accesses that expressed no compile-time
5682    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5683    /// future extension of the `:politicas` outer axis to a richer
5684    /// author surface (a per-cluster policy overlay the operator pins
5685    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5686    /// §V federation roadmap acknowledges, a per-tenant policy-alias
5687    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5688    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5689    /// policy-composite derivation the future adaptive-placement engine
5690    /// computes from a per-cluster load-topology reader, a promotion of
5691    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5692    /// partition once virtual-actor-style dynamic-mesh-policy
5693    /// composition comes into typed scope) would have had to be threaded
5694    /// through all four open-coded copies in lockstep or one consumer
5695    /// would silently disagree with the peers on which mesh-policy
5696    /// composite a given Aplicacao resolves to — the validator's
5697    /// per-axis bracket-dispatch seed reading the raw slot while the
5698    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5699    /// would silently split the build-time policy-shape gate from the
5700    /// runtime CNP-emission gate, a four-consumer split at the
5701    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5702    /// the source `caixa.lisp` with no field naming the policy-drift
5703    /// root cause. Lifting the resolution rule to a typed method on the
5704    /// substrate primitive means every downstream consumer of the
5705    /// Aplicacao's per-`:politicas` mesh-policy composite surface
5706    /// reaches for exactly one typed dispatch — the resolver's accept-
5707    /// set migrates as a unit on any future axis addition.
5708    ///
5709    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5710    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5711    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5712    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5713    /// close the two `Vec`-carry axes on the outer typed composition
5714    /// view; the outer `:politicas` composite-reference axis is the
5715    /// natural pair to the paired outer `Vec`-carry accessors on the
5716    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5717    /// emitter reads all four axes as one unit (graph nodes + graph
5718    /// edges + mesh policy + placement pool). Peer to the same
5719    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5720    /// slot: every M2 `SupervisorSpec`-scoped composite reader
5721    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5722    /// `restart_window`, `children`) already routes through the M2
5723    /// `SupervisorSpec` accessor family — this lift extends the same
5724    /// "one typed dispatch on the substrate primitive at the outer
5725    /// composition altitude" discipline to the M3 mesh-slot
5726    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5727    /// remaining peer outer-composite axes still unlifted at the time
5728    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5729    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5730    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5731    /// inherit this accessor's discipline as future compounding runs
5732    /// migrate their consumers onto the shared reference-return shape.
5733    /// Named `politicas()` to match the storage field's name verbatim
5734    /// and the tatara-lisp author-surface term (`:politicas`) the
5735    /// field's own docstring already carries; the accessor's identity
5736    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5737    /// slot's docstring already reaches for. Returns `&MeshPolicy`
5738    /// (not the owning composite by copy or clone) because every
5739    /// downstream consumer of the mesh-policy composite treats it as a
5740    /// read-only per-axis dispatch source — the reference-view is the
5741    /// narrowest borrow that supports every present + roadmapped
5742    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5743    /// emptiness probe) without cloning the composite through every
5744    /// consumer's fast path.
5745    #[must_use]
5746    pub fn politicas(&self) -> &MeshPolicy {
5747        &self.politicas
5748    }
5749
5750    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5751    /// per-Aplicacao distribution-composite composite-reference accessor
5752    /// every per-Aplicacao placement-block reader keys off — returns the
5753    /// author-declared `:placement` composite verbatim as a `&Placement`
5754    /// reference over the same backing storage the raw `&self.placement`
5755    /// field access borrows from.
5756    ///
5757    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5758    /// distribution composite — the load-bearing container of every
5759    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5760    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5761    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5762    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5763    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5764    /// `:affinity` hint). Every per-`:placement` axis threads through a
5765    /// lifted per-slot accessor on the [`Placement`] type: the
5766    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5767    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5768    /// per-cluster distribution-target slice-return accessor, the
5769    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5770    /// optional-scalar accessor, and the [`Placement::shard_key`]
5771    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5772    /// downstream consumer that reaches for a placement axis first passes
5773    /// through this outer accessor onto the composite and then dispatches
5774    /// onto the per-axis accessor — the two-level dispatch means every
5775    /// per-`:placement` reader now routes through a typed dispatch on the
5776    /// substrate primitive at both altitudes.
5777    ///
5778    /// Prior to this lift the `.placement` `Placement` composite was
5779    /// accessed inline at three production sites — the
5780    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5781    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5782    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5783    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5784    /// cluster `.clusters()` validate-loop traversal head, the per-
5785    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5786    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5787    /// paired with the shape-gate cascade's `.shard_key()` /
5788    /// `.estrategia()` diagnostic-carry pair), the
5789    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5790    /// per-entry placement-block emitter's outer
5791    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5792    /// seed (which fans onto every per-cluster `programs[]` entry as a
5793    /// self-describing distribution overlay the aggregator filters by),
5794    /// and the `feira app graph` per-Aplicacao print line's paired
5795    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5796    /// then-inner-accessor chains (which drive the human-readable
5797    /// distribution summary of the typed Aplicacao view) — three open-
5798    /// coded outer-field accesses that expressed no compile-time link
5799    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5800    /// extension of the `:placement` outer axis to a richer author surface
5801    /// (a per-cluster placement overlay the operator pins through a
5802    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5803    /// federation roadmap acknowledges, a per-tenant placement-alias
5804    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5805    /// resolves per-CR at admission time, a per-Aplicacao dynamic
5806    /// placement-composite derivation the future M5 adaptive-placement
5807    /// engine computes from a per-cluster load-topology reader, a
5808    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5809    /// partition once Orleans-style virtual-actor dynamic-placement comes
5810    /// into typed scope) would have had to be threaded through all three
5811    /// open-coded copies in lockstep or one consumer would silently
5812    /// disagree with the peers on which placement composite a given
5813    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5814    /// seed reading the raw slot while the peer
5815    /// `programs_for_aplicacao` emitter read an operator-resolved slot
5816    /// would silently split the build-time distribution-shape gate from
5817    /// the runtime programs.yaml distribution-annotation gate, a three-
5818    /// consumer split at the validator, the programs.yaml emitter, and
5819    /// the `feira app graph` printer far from the source `caixa.lisp`
5820    /// with no field naming the placement-drift root cause. Lifting the
5821    /// resolution rule to a typed method on the substrate primitive
5822    /// means every downstream consumer of the Aplicacao's per-
5823    /// `:placement` distribution composite surface reaches for exactly
5824    /// one typed dispatch — the resolver's accept-set migrates as a unit
5825    /// on any future axis addition.
5826    ///
5827    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5828    /// `AplicacaoSpec` type itself — sibling to the seed
5829    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5830    /// composite-reference accessor on the peer per-`:politicas` outer-
5831    /// composite axis, and to the paired slice-return accessors
5832    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5833    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5834    /// the two `Vec`-carry axes on the outer typed composition view; the
5835    /// outer `:placement` composite-reference axis is the natural pair
5836    /// to the peer `:politicas` composite-reference axis on the two
5837    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5838    /// how-to-run policy overlay, `:placement` carries the where-to-run
5839    /// distribution composite — every whole-Aplicacao mesh-artifact
5840    /// emitter reads both as one unit). Same "one typed dispatch on the
5841    /// substrate primitive, thin projections at each consumer"
5842    /// discipline the peer per-`:politicas` composite-reference axis
5843    /// already routes through. The one remaining outer-composite axis
5844    /// still unlifted at the time of this lift —
5845    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5846    /// external-gateway composite) — inherits this accessor's discipline
5847    /// as the next compounding run migrates its consumers onto the shared
5848    /// reference-return shape, closing the outer-composite altitude on
5849    /// every M3 mesh-slot axis. Named `placement()` to match the storage
5850    /// field's name verbatim and the tatara-lisp author-surface term
5851    /// (`:placement`) the field's own docstring already carries; the
5852    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5853    /// vocabulary the slot's docstring already reaches for. Returns
5854    /// `&Placement` (not the owning composite by copy or clone) because
5855    /// every downstream consumer of the placement composite treats it as
5856    /// a read-only per-axis dispatch source — the reference-view is the
5857    /// narrowest borrow that supports every present + roadmapped consumer
5858    /// (per-axis accessor dispatch, serde composite-serialization) without
5859    /// cloning the composite through every consumer's fast path.
5860    #[must_use]
5861    pub fn placement(&self) -> &Placement {
5862        &self.placement
5863    }
5864
5865    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5866    /// per-Aplicacao external-gateway composite optional-composite-
5867    /// reference accessor every per-Aplicacao gateway-block reader
5868    /// keys off — returns the author-declared `:entrada` composite
5869    /// verbatim as an `Option<&Entrada>` reference over the same
5870    /// backing storage the raw `self.entrada.as_ref()` field access
5871    /// borrows from, with `None` naming the internal-only mesh shape
5872    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5873    /// gateway_routes emitter treats as "emit nothing" and the peer
5874    /// `feira app graph` printer treats as "internal-only mesh").
5875    ///
5876    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5877    /// external-gateway composite — the load-bearing container of
5878    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5879    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5880    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5881    /// hostname axis, §III.4 for the `:para` destination-Servico
5882    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5883    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5884    /// axis threads through a lifted per-slot accessor on the
5885    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5886    /// Gateway-API `Listener.hostname` scalar accessor, the paired
5887    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5888    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5889    /// backendRefs destination-Servico scalar accessor, the
5890    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5891    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5892    /// scalar accessor. Every downstream consumer that reaches for
5893    /// an entrada axis first passes through this outer accessor onto
5894    /// the composite and then dispatches onto the per-axis accessor
5895    /// — the two-level dispatch means every per-`:entrada` reader
5896    /// now routes through a typed dispatch on the substrate primitive
5897    /// at both altitudes.
5898    ///
5899    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5900    /// was accessed inline at four production sites — the
5901    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5902    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5903    /// (which drives every per-axis refusal on the composite: the
5904    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5905    /// `EntradaMemberMissing` membership lookup against the
5906    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5907    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5908    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5909    /// per-path shape gate on each entry of `e.paths`), the
5910    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5911    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5912    /// composite-projection seed (which drives the destination-
5913    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5914    /// backendRefs port emitter fans on), the
5915    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5916    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5917    /// early-return seed (which drives the "no `:entrada` ⇒ no
5918    /// external artifacts" partition on the whole-Aplicacao Gateway-
5919    /// API emitter's fan-out), and the `feira app graph` per-
5920    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5921    /// external-gateway summary emitter (which drives the human-
5922    /// readable `entrada: host → para (paths=…, port=…)` /
5923    /// `entrada: (internal-only mesh)` partition on the typed
5924    /// Aplicacao view) — four open-coded outer-field accesses that
5925    /// expressed no compile-time link back to the typed slot at the
5926    /// [`AplicacaoSpec`] altitude. A future extension of the
5927    /// `:entrada` outer axis to a richer author surface (a
5928    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5929    /// at admission time so an Aplicacao can expose a public-web +
5930    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5931    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5932    /// operator can pin a per-cluster hostname override without
5933    /// re-authoring the `caixa.lisp`, a promotion of the plain
5934    /// `Option<Entrada>` to a richer `{single, multi}` partition once
5935    /// the multi-`:entrada` roadmap lands) would have had to be
5936    /// threaded through all four open-coded copies in lockstep or one
5937    /// consumer would silently disagree with the peers on which
5938    /// entrada composite a given Aplicacao resolves to — the
5939    /// validator's per-axis bracket-dispatch seed reading the raw
5940    /// slot while the peer `gateway_routes` emitter read an
5941    /// operator-resolved slot would silently split the build-time
5942    /// gateway-shape gate from the runtime Gateway + HTTPRoute
5943    /// emission gate, a four-consumer split at the validator, the
5944    /// `port_for_destination` L4-port resolver, the `gateway_routes`
5945    /// emitter, and the `feira app graph` printer far from the
5946    /// source `caixa.lisp` with no field naming the entrada-drift
5947    /// root cause. Lifting the resolution rule to a typed method on
5948    /// the substrate primitive means every downstream consumer of
5949    /// the Aplicacao's per-`:entrada` external-gateway composite
5950    /// surface reaches for exactly one typed dispatch — the
5951    /// resolver's accept-set migrates as a unit on any future axis
5952    /// addition.
5953    ///
5954    /// Third and final `&Composite`-return accessor on the top-level
5955    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5956    /// unlifted outer-composite axis on the outer typed composition
5957    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5958    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5959    /// accessor on the per-`:politicas` outer-composite axis and to
5960    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5961    /// distribution-composite composite-reference accessor on the
5962    /// per-`:placement` outer-composite axis; extends the outer-
5963    /// composite reference-return discipline the two peers already
5964    /// route through onto the last unlifted per-`AplicacaoSpec`
5965    /// outer-composite axis. The `:entrada` outer-composite axis is
5966    /// the natural pair to the two peer outer-composite axes on the
5967    /// three operationally-symmetric M3 mesh-slot outer composites
5968    /// (`:politicas` carries the how-to-run policy overlay,
5969    /// `:placement` carries the where-to-run distribution composite,
5970    /// `:entrada` carries the who-can-reach-it external-gateway
5971    /// composite — every whole-Aplicacao mesh-artifact emitter reads
5972    /// all three as one unit). Same "one typed dispatch on the
5973    /// substrate primitive, thin projections at each consumer"
5974    /// discipline the peer outer-composite axes already route through.
5975    /// Named `entrada()` to match the storage field's name verbatim
5976    /// and the tatara-lisp author-surface term (`:entrada`) the
5977    /// field's own docstring already carries; the accessor's
5978    /// identity maps onto the canonical MESH-COMPOSITION §III.4
5979    /// vocabulary the slot's docstring already reaches for. Returns
5980    /// `Option<&Entrada>` (not the owning composite by copy or
5981    /// clone) because every downstream consumer of the entrada
5982    /// composite treats it as a read-only per-axis dispatch source
5983    /// — the reference-view is the narrowest borrow that supports
5984    /// every present + roadmapped consumer (per-axis accessor
5985    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5986    /// port-fallback projection, early-return partition on the
5987    /// `None` arm) without cloning the composite through every
5988    /// consumer's fast path. The `Option` half of the return-type
5989    /// preserves the load-bearing "author-omitted `:entrada` ⇒
5990    /// internal-only mesh" partition (not a default composite the
5991    /// downstream must reject on emptiness) — the accessor projects
5992    /// the raw `Option<Entrada>` slot's presence bit through the
5993    /// reference-return unchanged.
5994    #[must_use]
5995    pub fn entrada(&self) -> Option<&Entrada> {
5996        self.entrada.as_ref()
5997    }
5998
5999    /// Validate the typed shape:
6000    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6001    ///     and a non-empty `:versao`; no two entries share the same
6002    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6003    ///     not a multiset)
6004    ///   - every `:contratos` :de + :para must be in `:membros`
6005    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6006    ///     contract is an inter-Servico edge, so a Servico contracting
6007    ///     with itself is a build error under every WIT shape
6008    ///     (MESH-COMPOSITION §III.1)
6009    ///   - no two `:contratos` entries agree on
6010    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6011    ///     edges are a set, not a multiset (peer of the `:membros` /
6012    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6013    ///   - `:entrada :para` must be in `:membros`
6014    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6015    ///     `:placement Replicated`/`SingleNode` must NOT declare
6016    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6017    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6018    ///     between strategy and shard-key is symmetric: every validated
6019    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6020    ///     Sharded`
6021    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6022    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6023    ///     the shard pool (MESH-COMPOSITION §III.1)
6024    ///   - every `:clusters` entry is non-empty and unique
6025    ///   - `:placement :affinity`, when set, is non-empty
6026    ///   - the synchronous-`:contratos` subgraph is acyclic
6027    ///     (MESH-COMPOSITION §III.3)
6028    ///   - every declared `:politicas` value is operationally meaningful
6029    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6030    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6031    ///     omit the field instead to express "no policy on this axis")
6032    pub fn validate(&self) -> Result<(), AplicacaoError> {
6033        self.validate_membros()?;
6034        let names: std::collections::HashSet<&str> =
6035            self.membros().iter().map(Membro::nome).collect();
6036
6037        // Identity key for the typed-edge duplicate gate below: every
6038        // field that distinguishes one contract from another. Two
6039        // entries that agree on all six are *the same edge declared
6040        // twice*, the typed-graph analogue of duplicate `:membros` /
6041        // `:placement :clusters` / `:entrada :paths` entries (which
6042        // are already build errors at this layer). Rejecting it at the
6043        // validate gate closes a renderer-side footgun: caixa-mesh's
6044        // `cilium_network_policies` keys each emitted policy by
6045        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6046        // (de, para) and identical payload would land as two K8s
6047        // objects with colliding `metadata.name`, rejected at apply
6048        // time far from the source caixa.lisp.
6049        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6050            std::collections::HashSet::new();
6051        for c in self.contratos() {
6052            // Per-axis value-shape gate on every `:contratos` name
6053            // reference, before any graph-membership lookup. Empty +
6054            // DNS-1123-malformed `:de`/`:para` values silently fell
6055            // through to `ContratoMemberMissing` at the lookup arm
6056            // because every `:membros :caixa` is shape-validated
6057            // (3f9d7a0), so the `names` set structurally cannot contain
6058            // an empty / malformed string and the membership-lookup
6059            // diagnostic always misframed the root cause as
6060            // "this caixa is not in `:membros`". The shape gate runs
6061            // ahead of the lookup so structurally-impossible-to-match
6062            // inputs route through the narrower self-locating
6063            // diagnostic, preserving the legitimate "well-shaped
6064            // phantom reference" arm. `:de` runs before `:para` per
6065            // the canonical edge-direction order the existing
6066            // membership lookup, self-edge check, target dispatch,
6067            // and diagnostic strings already use.
6068            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6069            // + the paired [`AplicacaoError::ContratoMemberMissing`]
6070            // diagnostic's `caixa:` carrier through the lifted
6071            // [`WitContract::source`] / [`WitContract::destination`]
6072            // scalar accessors rather than the raw `&c.de` / `&c.para`
6073            // `&String`-borrow arg site + the raw `c.de.clone()` /
6074            // `c.para.clone()` field-access `String`-carry sites — the
6075            // last unlifted per-`:contratos` raw-field-access sites in
6076            // the M3 mesh-slot validator's per-edge per-arm shape-gate
6077            // arg + phantom-name diagnostic wrap-envelope emit surface.
6078            // `c.source()` is byte-identical to `&c.de` (pinned by the
6079            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6080            // + `wit_contract_source_borrows_from_de_storage` accessor
6081            // tests) and `c.destination()` is byte-identical to `&c.para`
6082            // (pinned by the sibling
6083            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6084            // + `wit_contract_destination_borrows_from_para_storage`
6085            // accessor tests) — so a future rebrand of either underlying
6086            // storage flows through the accessor's one body without a
6087            // coordinated per-consumer rewrite across the M3 mesh
6088            // validator's per-edge shape-gate + phantom-name refusal
6089            // arms. Peer of the sibling per-`:contratos` self-loop
6090            // arm's `.source().to_string()` / `.world_ref().to_string()`
6091            // `String`-carry sites the earlier convergence lifted onto
6092            // the same accessor pair.
6093            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6094            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6095            if !names.contains(c.source()) {
6096                return Err(AplicacaoError::ContratoMemberMissing {
6097                    caixa: c.source().to_string(),
6098                });
6099            }
6100            if !names.contains(c.destination()) {
6101                return Err(AplicacaoError::ContratoMemberMissing {
6102                    caixa: c.destination().to_string(),
6103                });
6104            }
6105            // A `:contratos` entry is an *inter*-Servico contract
6106            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6107            // typed edge between two distinct graph nodes. An edge whose
6108            // `:de` equals its `:para` is a Servico contracting with
6109            // itself — a degenerate edge under every WIT shape. The
6110            // synchronous shapes were caught only incidentally, and with
6111            // a misleading diagnostic: `detect_sync_cycles` reported
6112            // `cart → cart` as a `ContratoCycle` whose path is
6113            // `["cart", "cart"]` — framing a self-edge as a multi-node
6114            // deadlock. The pub-sub shape slipped through entirely
6115            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6116            // `nats:pub-sub` edge from a member to itself silently
6117            // validated, then rendered a `CiliumNetworkPolicy` whose
6118            // endpointSelector and fromEndpoints both name the same
6119            // program — a self-allow rule that is a no-op, since
6120            // intra-pod traffic never traverses the mesh). A self-edge's
6121            // runtime meaning is an in-process call, which doesn't go
6122            // through the mesh at all, so no `:contratos` edge can carry
6123            // it. Firing the gate before the `:wit`/`target()` shape
6124            // checks means the structural "this edge can't exist" error
6125            // precedes the narrower payload-shape diagnostics, and shape-
6126            // agnostically covers all four `WitTarget` arms (HTTP / Store
6127            // / Capability / PubSub) at one point — closing the pub-sub
6128            // hole and replacing the misleading cycle diagnostic in one
6129            // gate. Peer of the duplicate-`:contratos` / duplicate-
6130            // `:membros` set gates: both reject a structurally
6131            // ill-formed graph at the typed surface, before the renderer
6132            // emits a K8s object that fails or no-ops far from the source
6133            // caixa.lisp.
6134            // Route the per-`:contratos` structural self-edge probe
6135            // through the lifted [`WitContract::is_self_loop`] typed
6136            // predicate rather than the raw `c.de == c.para` field-
6137            // equality check — the one production consumer of the per-
6138            // `:contratos` caller-equals-callee endpoint-equality axis
6139            // now keys off exactly one typed dispatch on the substrate
6140            // primitive, so any future rebrand of the axis (an M4-typed-
6141            // caller enum whose identity comparison rule the predicate
6142            // could route through, a per-cluster caller/callee-alias
6143            // table the M4 CR materializer resolves per-CR before the
6144            // equality probe) migrates as a single caixa-core edit
6145            // rather than a coordinated rewrite of the gate + every
6146            // downstream self-edge consumer. Peer of the sibling
6147            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6148            // [`WitContract::is_store`] shape-predicate routing on the
6149            // `:wit` world-ref axis, extended onto the per-edge
6150            // endpoint-equality axis.
6151            //
6152            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6153            // diagnostic's `caixa:` / `wit:` carriers through the
6154            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6155            // scalar accessors rather than the raw `c.de.clone()` /
6156            // `c.wit.clone()` field-access `String`-carry sites — the
6157            // last unlifted per-`:contratos` raw-field-access
6158            // `.clone()` sites in the M3 mesh-slot validator's self-
6159            // edge refusal arm. `.source().to_string()` is byte-
6160            // identical to `.de.clone()` (pinned by the sibling
6161            // `source_returns_de_byte_equal_across_permutations` accessor
6162            // test), and `.world_ref().to_string()` is byte-identical
6163            // to `.wit.clone()` (pinned by the sibling
6164            // `world_ref_returns_wit_byte_equal_across_permutations`
6165            // accessor test) — so a future rebrand of either underlying
6166            // storage flows through the accessor's one body without a
6167            // coordinated per-consumer rewrite across the M3 mesh
6168            // validator.
6169            if c.is_self_loop() {
6170                return Err(AplicacaoError::ContratoSelfLoop {
6171                    caixa: c.source().to_string(),
6172                    wit: c.world_ref().to_string(),
6173                });
6174            }
6175            if c.world_ref().is_empty() {
6176                let (de, para) = c.edge_pair();
6177                return Err(AplicacaoError::EmptyWit { de, para });
6178            }
6179            // Shape ↔ target consistency — surfaces "HTTP wit without
6180            // :endpoint", "NATS wit with :endpoint set", etc. as named
6181            // build errors instead of silent renderer drops. Threaded
6182            // through the duplicate-edge diagnostic below (via
6183            // [`WitTarget::label`]) so the "which typed target arm did
6184            // the duplicate carry" question is answered by the typed
6185            // enum's variant discriminator, not by re-probing the raw
6186            // `Option<String>` payload fields.
6187            let target_view = c.target()?;
6188            // Contract identity: (de, para, wit, endpoint, subject, slot).
6189            // Two contracts that match on all six are the same typed edge
6190            // declared twice — author error, not a legitimate variant of
6191            // "same caller-callee pair, different payload" (e.g.
6192            // cart→catalog at /products vs /search), which keeps distinct
6193            // identity keys via the differing endpoint payloads.
6194            //
6195            // Route the six-axis dedup key through the lifted
6196            // [`WitContract::identity`] composite-projection accessor
6197            // rather than the inline six-tuple builder — the two
6198            // substrate primitives on the per-`:contratos` identity axis
6199            // (the [`ContratoIdentity`] type alias's six axes, this
6200            // dedup-key's six tuple arms) now migrate as a unit on any
6201            // future axis addition. Peer of the sibling per-`:contratos`
6202            // composite-projection [`WitContract::edge_pair`] /
6203            // [`WitContract::edge_triple`] accessors on the
6204            // caller-callee / caller-callee-wit prefix axes; extends
6205            // the discipline onto the full-identity axis that carries
6206            // the three payload-shape arms too.
6207            let key = c.identity();
6208            crate::render::insert_first_seen(&mut seen_contracts, key, || {
6209                // Route the per-`:contratos` duplicate-gate diagnostic's
6210                // `(de, para, wit)` triple through the lifted
6211                // [`WitContract::edge_triple`] typed accessor rather
6212                // than pairing `edge_pair()` for the `(de, para)` prefix
6213                // with a raw `c.wit.clone()` for the `wit:` tail — the
6214                // paired-with-raw-field-access shape was the last
6215                // per-`:contratos` diagnostic constructor bypassing the
6216                // substrate-primitive composite projection, sibling to
6217                // the eight [`AplicacaoError::Contrato*`] triple-
6218                // carrying constructors [`WitContract::target`]'s edge
6219                // closure feeds through the same accessor.
6220                let (de, para, wit) = c.edge_triple();
6221                AplicacaoError::ContratoDuplicate {
6222                    de,
6223                    para,
6224                    wit,
6225                    target: target_view.label(),
6226                }
6227            })?;
6228        }
6229
6230        // Cycles in the synchronous-edge subgraph are build errors
6231        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6232        // are "acyclic by construction" because the publisher fires
6233        // and forgets, so no caller blocks on a downstream that loops
6234        // back to it.
6235        self.detect_sync_cycles()?;
6236
6237        if let Some(e) = self.entrada() {
6238            // Route the per-`:entrada` composite-reference read
6239            // through the lifted [`AplicacaoSpec::entrada`] accessor
6240            // rather than the raw `&self.entrada` field access — the
6241            // shape-and-membership gate's traversal head is now the
6242            // canonical read-side surface every per-Aplicacao entrada
6243            // consumer routes through, closing the fourth of four
6244            // open-coded outer-field accesses on the per-`:entrada`
6245            // outer-composite axis.
6246            //
6247            // Shape gate on `:entrada :para` runs ahead of the
6248            // membership lookup. Every `:membros :caixa` past
6249            // `validate_membro_caixa` is a valid DNS-1123 label
6250            // (3f9d7a0), so the `names` set structurally cannot
6251            // contain an empty / malformed string and the membership-
6252            // lookup diagnostic always misframed the root cause as
6253            // "this caixa is not in `:membros`". The shape gate
6254            // routes structurally-impossible-to-match inputs through
6255            // the narrower self-locating diagnostic, preserving the
6256            // legitimate "well-shaped phantom reference" arm — the
6257            // same trajectory the peer `:membros :caixa` (3f9d7a0),
6258            // `:placement :clusters` (6c8c00b), and `:contratos :de`
6259            // / `:para` (8d5af6b) axes already follow. This closes
6260            // the fourth and last Aplicacao-level Servico-name
6261            // reference axis on the canonical DNS-1123 floor.
6262            // Route the per-`:entrada :para` byte-string reads through
6263            // the lifted [`Entrada::destination`] accessor rather than
6264            // the raw `e.para` field access — the three
6265            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6266            // (shape-gate `validate_entrada_para` arg, membership
6267            // lookup, `EntradaMemberMissing` diagnostic carry) now key
6268            // off exactly one typed dispatch on the substrate
6269            // primitive, closing the last unlifted per-`:entrada :para`
6270            // raw-field-access axis on the M3 mesh-slot validator.
6271            // The `.destination().to_string()` at the diagnostic site
6272            // is byte-identical to `.para.clone()` — pinned by the
6273            // sibling `destination_returns_entrada_para_byte_equal` +
6274            // `destination_borrows_from_entrada_para_storage` accessor
6275            // tests — so a future rebrand of the underlying `:para`
6276            // storage (a lift from `String` to a typed
6277            // `ServicoName(String)` newtype, a per-Aplicacao interning
6278            // arena the M4 CR materializer authors, a
6279            // `smol_str::SmolStr` inline-buffer swap) flows through
6280            // the accessor's one body without a coordinated
6281            // per-consumer rewrite across the M3 mesh validator.
6282            validate_entrada_para(e.destination())?;
6283            if !names.contains(e.destination()) {
6284                return Err(AplicacaoError::EntradaMemberMissing {
6285                    para: e.destination().to_string(),
6286                });
6287            }
6288            // Route the per-`:entrada :host` byte-string reads through
6289            // the lifted [`Entrada::hostname`] accessor rather than
6290            // the raw `e.host` field access — the emptiness gate and
6291            // the shape-gate `validate_entrada_host` arg now key off
6292            // exactly one typed dispatch on the substrate primitive,
6293            // closing the last unlifted per-`:entrada :host` raw-
6294            // field-access axis on the M3 mesh-slot validator. Peer
6295            // of the sibling per-`:entrada :para` convergence above
6296            // and pinned by the existing
6297            // `hostname_returns_entrada_host_byte_equal` +
6298            // `hostnames_returns_singleton_of_hostname_accessor`
6299            // accessor tests, so any future
6300            // Gateway-API-shaped host renormalization (a wildcard-
6301            // label lift, a trailing-`.` FQDN substitution, an IDNA
6302            // Punycode round-trip the SNI fan-out overlay authors)
6303            // flows through the accessor's one body without a
6304            // coordinated per-consumer rewrite across the M3 mesh
6305            // validator.
6306            if e.hostname().is_empty() {
6307                return Err(AplicacaoError::EmptyEntradaHost);
6308            }
6309            // The `:host` lands verbatim as a K8s Gateway API v1
6310            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6311            // both apiserver-validated against the same restrictive
6312            // pattern: lowercase RFC 1123 DNS subdomain, optional
6313            // single leading wildcard label (`*.`), max length 253,
6314            // per-label max length 63, no IP literals, no scheme,
6315            // no port. Until this gate landed `validate()` only
6316            // refused the empty string (`EmptyEntradaHost`); a
6317            // structurally invalid hostname (`"https://example.com"`,
6318            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6319            // `"_underscored.example.com"`, `"FOO.example.com"`,
6320            // `"checkout.quero.cloud."`) silently passed validate
6321            // and the apiserver `field is invalid` error surfaced at
6322            // `kubectl apply` time, far from the source caixa.lisp.
6323            // Lifting the gate to caixa-build time mirrors the
6324            // `:entrada :paths` value-shape trajectory (eb3456d) and
6325            // closes the last unstructured `:entrada` axis.
6326            validate_entrada_host(e.hostname())?;
6327            // Structural-floor gate on `:entrada :port`: every
6328            // validated `Entrada::port` past this gate lies in
6329            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6330            // type-inferred ceiling closes the top edge, so no companion
6331            // upper-cap arm is needed here — unlike the peer capped-
6332            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6333            // `require_positive_bounded_u32` bracket covers both edges).
6334            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6335            // accept-set-floor const rather than the prior inline
6336            // `if e.port == 0` byte-check so a future rebrand of the
6337            // accept-set floor (a hypothetical unprivileged-only
6338            // migration lifting the floor to `1024`, a per-cluster
6339            // scoping the operator pins through a future
6340            // `:placement :port-floor` slot as the M4 typed-slot
6341            // trajectory adds it, the future
6342            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6343            // per-Aplicacao gateway resolver reaching for the same
6344            // floor) is a one-line edit on the canonical
6345            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6346            // rewrite across the emit site + the pin test + every
6347            // future per-target renderer the substrate adds.
6348            if e.port() < SERVICO_PORT_MIN {
6349                return Err(AplicacaoError::EntradaPortZero);
6350            }
6351            // Each `:entrada :paths` entry becomes a K8s Gateway API
6352            // HTTPRoute `matches[].path.value`. The Gateway API rejects
6353            // values that don't start with `/` for `type: PathPrefix`,
6354            // and an empty value is meaningless. Surface those as build
6355            // errors (MESH-COMPOSITION §III.3) rather than apply-time
6356            // failures. Empty `:paths` itself is fine — caixa-mesh
6357            // falls back to a single `/` catch-all.
6358            let mut seen = std::collections::HashSet::new();
6359            // Route the per-entry value-shape gate's traversal head
6360            // through the lifted [`Entrada::paths`] slice accessor
6361            // rather than the raw `&e.paths` field access — the
6362            // per-Aplicacao `:entrada :paths` validate loop now keys
6363            // off the canonical raw-slot surface every downstream
6364            // per-`:entrada` path-list consumer (the sibling
6365            // [`Entrada::resolved_paths`] fallback-applying resolver
6366            // internal reads, `feira app graph`'s per-Aplicacao entrada
6367            // summary line's `{:?}` Debug print) routes through, so any
6368            // future rebrand on the typed slot's raw-slot reader lands
6369            // at exactly one place. Same convergence discipline as the
6370            // sibling [`Placement::clusters`] (a6e18d7) reader-site
6371            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6372            // axis.
6373            for p in e.paths() {
6374                if p.is_empty() {
6375                    return Err(AplicacaoError::EntradaPathEmpty);
6376                }
6377                if !p.starts_with('/') {
6378                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6379                }
6380                // Per-entry value-shape gate: the path lands verbatim
6381                // as a K8s Gateway API HTTPRoute `matches[].path.value`
6382                // (caixa-mesh/src/lib.rs:498), apiserver-validated
6383                // against `maxLength: 1024` + the Gateway API webhook's
6384                // path-grammar rules (no `//`, no `/./`, no `/../`, no
6385                // query/fragment separators, no whitespace, no control
6386                // characters, no non-ASCII bytes). Until this gate
6387                // landed `validate` only refused the empty string and
6388                // missing-leading-slash (eb3456d); a structurally
6389                // invalid path (`"/api?q=1"`, `"/api#frag"`,
6390                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6391                // 1025-byte URL-shaped slug) silently passed validate
6392                // and the failure surfaced at `kubectl apply` time as
6393                // a Gateway API webhook rejection, far from the source
6394                // caixa.lisp, with no field naming the offending
6395                // `:paths` entry. Lifting the gate to caixa-build time
6396                // mirrors the `:entrada :host` value-shape trajectory
6397                // (c7d05ec) on the sibling axis — every author surface
6398                // that emits a Gateway API field now matches the
6399                // apiserver's accepted set at validate time.
6400                validate_entrada_path(p)?;
6401                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6402                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6403                })?;
6404            }
6405        }
6406
6407        self.validate_placement()?;
6408
6409        self.validate_politicas()?;
6410
6411        Ok(())
6412    }
6413
6414    /// Reject `:membros` values that are operationally meaningless. The
6415    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6416    /// every entry names a Servico that participates in the Aplicacao,
6417    /// and the rendered programs.yaml fan-out emits one entry per
6418    /// `:membros`. Three authoring footguns are closed here:
6419    ///
6420    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6421    ///     a `programs:` entry whose `name:` is the empty string, which
6422    ///     downstream `lareira-fleet-programs` rejects at template time
6423    ///     with a non-localized error;
6424    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6425    ///     an empty semver constraint, so the failure surfaces far from
6426    ///     the source caixa.lisp;
6427    ///   - duplicate `:caixa` names — two entries with the same name
6428    ///     produce duplicate programs.yaml entries (one silently
6429    ///     overwrites the other in the cluster's HelmRelease values), and
6430    ///     contract membership lookups against `:contratos` collapse the
6431    ///     two onto one node, masking authoring mistakes.
6432    ///
6433    /// Same value-shape discipline as `:placement :clusters` (where empty
6434    /// + duplicate cluster names are rejected) and `:entrada :paths`
6435    /// (where empty + duplicate path entries are rejected). Lifting these
6436    /// invariants to the typed surface mirrors the MESH-COMPOSITION
6437    /// §III.3 promise that the `:membros` set — the load-bearing identity
6438    /// of the application graph — is well-formed by construction.
6439    fn validate_membros(&self) -> Result<(), AplicacaoError> {
6440        if self.membros().is_empty() {
6441            return Err(AplicacaoError::NoMembros);
6442        }
6443        let mut seen = std::collections::HashSet::new();
6444        for m in self.membros() {
6445            // Route the `MembroCaixaEmpty` refusal-arm's per-member
6446            // empty-`:caixa` shape-gate through the typed
6447            // [`Membro::nome`] accessor rather than the raw `.caixa`
6448            // field access — the last un-lifted `.caixa` production-
6449            // code read site on the per-`:membros` member-caixa `:nome`
6450            // axis, sibling to the six caixa-core validator read sites
6451            // (member-set collector, per-member value-shape gate,
6452            // duplicate dedup key, cycle-detector adjacency-map seed,
6453            // self-loop gate) the 4a32abf lift already routed through
6454            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6455            // per-`programs[]` entry-`name:` `String`-carry converge.
6456            // Prior to this converge the `MembroCaixaEmpty` refusal
6457            // arm was the solitary consumer bypassing the typed
6458            // dispatch — the same-loop iteration's very next call
6459            // `validate_membro_caixa(m.nome())` already routed through
6460            // the accessor, so an author landing an empty-`:caixa`
6461            // entry hit the accessor on the shape-gate line but
6462            // bypassed it on the emptiness line one line above. A
6463            // future extension of the `:membros :caixa` axis to a
6464            // richer author surface (a per-cluster alias table pinned
6465            // through a future `:placement`-scoped slot, a namespace-
6466            // qualified rewrite the M4 CR materializer applies per-CR,
6467            // a per-member overlay from the future `:membros
6468            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6469            // that lands on the accessor would silently disagree
6470            // between the emptiness gate and every peer consumer —
6471            // an author-declared `:caixa "checkout"` value the
6472            // accessor rewrote to `""` under a future alias arm would
6473            // pass the raw `.is_empty()` gate here while the peer
6474            // `validate_membro_caixa(m.nome())` call one line below
6475            // (and every downstream emit-side consumer routing through
6476            // the accessor) tripped on the empty-value shape far from
6477            // this diagnostic. Pinned by the drift-detection test
6478            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6479            // below.
6480            if m.nome().is_empty() {
6481                return Err(AplicacaoError::MembroCaixaEmpty);
6482            }
6483            // Every emitted cluster artifact's `metadata.name` derives
6484            // from a `:membros :caixa` value verbatim — the rendered
6485            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6486            // the [`crate::LABEL_PROGRAM`] label value on every CNP
6487            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6488            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6489            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6490            // `metadata.name` when the member is the `:entrada :para`
6491            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6492            // schema enforces the DNS-1123 label rule on admission;
6493            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6494            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6495            // mistaken-identity slug) silently passes the prior empty-/
6496            // duplicate-only gate and the failure surfaces at `kubectl
6497            // apply` time as a `metadata.name: Invalid value` rejection,
6498            // far from the source caixa.lisp, with no field naming the
6499            // offending `:membros` entry. Lifting the gate to caixa-build
6500            // time mirrors the `:entrada :host` value-shape trajectory
6501            // (c7d05ec) on the peer axis — every author surface that
6502            // emits a K8s name now matches the apiserver's accepted set
6503            // at validate time.
6504            validate_membro_caixa(m.nome())?;
6505            // The author surface for `:versao` is the same Cargo-shaped
6506            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6507            // `"*"`) every `:deps` entry carries — and the lacre pipeline
6508            // resolves both axes through the same
6509            // [`crate::version::parse_requirement`] entry-point. The
6510            // shared [`crate::render::require_valid_versao_requirement`]
6511            // helper brackets the empty-first + parse cascade both peer
6512            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6513            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6514            // route through, so drift between the three axes' accepted
6515            // requirement sets is structurally impossible and the parse-
6516            // side no-op the empty-first arm closes (semver's empty
6517            // parse yields an implicit `*`) lives in exactly one
6518            // predicate.
6519            crate::render::require_valid_versao_requirement(
6520                m.versao_requirement(),
6521                || AplicacaoError::MembroVersaoEmpty {
6522                    caixa: m.nome().to_string(),
6523                },
6524                |reason| AplicacaoError::MembroVersaoInvalid {
6525                    caixa: m.nome().to_string(),
6526                    versao: m.versao_requirement().to_string(),
6527                    reason,
6528                },
6529            )?;
6530            crate::render::insert_first_seen(&mut seen, m.nome(), || {
6531                AplicacaoError::MembroDuplicate {
6532                    caixa: m.nome().to_string(),
6533                }
6534            })?;
6535        }
6536        Ok(())
6537    }
6538
6539    /// Reject `:placement` values that are operationally meaningless or
6540    /// internally contradictory. Each strategy variant has the same
6541    /// invariants on `:clusters` (non-empty list, non-empty unique
6542    /// entries) — the §III.1 author surface is uniform on this axis,
6543    /// even though the *meaning* of the list differs by strategy
6544    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6545    /// shard pool).
6546    ///
6547    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6548    /// are the same authoring footgun closed for `:politicas` zero
6549    /// values and `:entrada` empty paths: the field is *declared* but
6550    /// carries no meaning, so downstream renderers either skip it
6551    /// silently (cluster-fanout drops the empty entry, no diagnostic)
6552    /// or apply it literally and fail at admission time. Lifting both
6553    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6554    /// violation is a build error" promise.
6555    ///
6556    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6557    /// is required exactly when `:estrategia Sharded` (hash-keyed
6558    /// distribution, Akka cluster-sharding convention, §II.4) and
6559    /// refused on `:estrategia Replicated`/`SingleNode` (where no
6560    /// hash-keyed routing axis consumes it). The partition closes the
6561    /// "I think I configured sharding" footgun where an author writes
6562    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6563    /// the typed slot's value silently vanishes at the renderer layer
6564    /// — every validated `Placement` past this call satisfies
6565    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6566    fn validate_placement(&self) -> Result<(), AplicacaoError> {
6567        // Every strategy needs at least one named cluster: `Replicated`
6568        // and `SingleNode` use the list as hosting/takeover candidates
6569        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6570        // §II.1), while `Sharded` uses it as the shard pool
6571        // (Akka cluster-sharding convention — §II.4). An empty list is
6572        // meaningless under any of the three.
6573        //
6574        // Route the paired pre-flight `.is_empty()` refusal probe and
6575        // the per-cluster validate loop's traversal head through the
6576        // lifted [`Placement::clusters`] slice-return accessor rather
6577        // than the raw `self.placement.clusters` field access — the
6578        // two production consumers of the per-`:placement` cluster-
6579        // pool `Vec`-carry now key off exactly one typed dispatch on
6580        // the substrate primitive, so any future rebrand on the axis
6581        // (a per-tenant cluster-pool overlay the operator pins through
6582        // a future `:placement :clusters-overrides` slot, a per-
6583        // Aplicacao dynamic cluster-pool derivation the future M5
6584        // adaptive-placement engine computes from `:affinity` weights)
6585        // migrates as a single caixa-core edit rather than a
6586        // coordinated rewrite of the paired arms — sibling of the
6587        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6588        // arm migration on the per-`:supervisor` static-child-list
6589        // `Vec`-carry axis.
6590        //
6591        // Route the per-`:placement` outer-composite reference read
6592        // through the lifted [`AplicacaoSpec::placement`] outer accessor
6593        // rather than the raw `&self.placement` field access — the
6594        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6595        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6596        // axis-level lifted accessor family) now routes through the
6597        // substrate-primitive typed dispatch at the outer composition
6598        // altitude, the same shape the peer caixa-mesh
6599        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6600        // and the sibling `feira app graph` per-Aplicacao print line
6601        // now key off after this accessor lift.
6602        let p = self.placement();
6603        if p.clusters().is_empty() {
6604            return Err(AplicacaoError::PlacementWithoutClusters {
6605                estrategia: p.estrategia(),
6606            });
6607        }
6608        let mut seen = std::collections::HashSet::new();
6609        for c in p.clusters() {
6610            // Per-entry value-shape gate: the cluster name lands in
6611            // every K8s context / `lareira-fleet-programs` aggregator
6612            // filter / future M4 CR materializer's per-cluster axis
6613            // a validated `:clusters` entry passes through, each
6614            // enforcing the DNS-1123 label rule on admission. Same
6615            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6616            // on the peer name axis — both axes' validated values
6617            // are guaranteed-accepted by the apiserver without
6618            // re-validation at any downstream renderer or admission
6619            // layer.
6620            validate_placement_cluster(c)?;
6621            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6622                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6623            })?;
6624        }
6625        // Route the per-`:placement :affinity` per-hint value-shape
6626        // gate through the typed [`Placement::affinity`] accessor rather
6627        // than the raw `&self.placement.affinity` field access — the
6628        // sole open-coded field-access site on the per-`:placement`
6629        // M3-Adaptive-compression-hint axis the accessor lift now owns.
6630        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6631        // the accessor's `Option<&str>` return type;
6632        // [`validate_placement_affinity`]'s `&str` parameter accepts
6633        // the narrower borrow without a re-allocation, so the routing
6634        // change is byte-for-byte in the pass arm and remains
6635        // byte-for-byte in every failure diagnostic
6636        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6637        // String` field is populated inside
6638        // [`validate_placement_affinity`] via the peer `.to_string()`
6639        // path on the same borrowed slice). Peer of the sibling
6640        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6641        // routing through [`Placement::shard_key`] at the caixa-core
6642        // site above — extends the "read `:placement` optional-scalars
6643        // through the typed accessor" discipline to the second
6644        // `Option<String>`-shape slot on the M3 mesh-slot family.
6645        //
6646        // Per-hint value-shape gate: the `:affinity` value lands
6647        // verbatim in the M3 Adaptive compression overlay
6648        // (caixa-mesh's `placement.affinity` emission) and every
6649        // future M4 placement-engine routing axis keying off the
6650        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6651        // selector — each enforces the DNS-1123 label rule on
6652        // admission. Same typed-shape trajectory as `:placement
6653        // :clusters` (6c8c00b) on the sibling slot and the four
6654        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6655        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6656        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6657        // on the Aplicacao surface to land on the canonical
6658        // [`crate::render::is_dns_1123_label`] floor.
6659        if let Some(a) = p.affinity() {
6660            validate_placement_affinity(a)?;
6661        }
6662        match p.estrategia() {
6663            // Route the `Sharded`-arm shape-gate cascade through the
6664            // typed [`Placement::shard_key`] accessor rather than the
6665            // raw `&self.placement.shard_key` field access — one of the
6666            // two open-coded field-access sites on the per-`:placement`
6667            // Akka-cluster-sharding-key axis the accessor lift now
6668            // owns. The `Some(k)`-bound `k` narrows from `&String` to
6669            // `&str` under the accessor's `Option<&str>` return type;
6670            // `str::is_empty` and [`validate_placement_shard_key`]'s
6671            // `&str` parameter both accept the narrower borrow without
6672            // a re-allocation.
6673            PlacementStrategy::Sharded => match p.shard_key() {
6674                None => return Err(AplicacaoError::ShardedWithoutKey),
6675                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6676                // Per-axis value-shape gate on the Akka-cluster-sharding
6677                // `:shard-key` extractor expression. The shape gate runs
6678                // after the more self-locating `ShardedKeyEmpty` arm so
6679                // a `:shard-key ""` surfaces the narrower empty
6680                // diagnostic first; every non-empty `:shard-key` past
6681                // this call is guaranteed to be a printable-ASCII
6682                // single-token reference the future M4 Akka-style
6683                // cluster-sharding reconciler can hash without
6684                // re-validating at the runtime layer. Mirrors the
6685                // payload-axis shape gates on the peer `:contratos`
6686                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6687                // 63e18a0 / c4213a4) — each lifts the runtime parser's
6688                // intersection-floor to a caixa-build-time gate.
6689                Some(k) => validate_placement_shard_key(k)?,
6690            },
6691            // `:shard-key` is the Akka-cluster-sharding axis
6692            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6693            // across the cluster pool. `Replicated` (active-active across
6694            // every named cluster) and `SingleNode` (Erlang/OTP
6695            // distributed-app takeover/failover, §II.1) have no hash-keyed
6696            // routing axis to consume the slot; downstream renderers
6697            // (caixa-mesh's `placement.shardKey` overlay at
6698            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6699            // sharding reconciler) ignore `:shard-key` outside the
6700            // `Sharded` arm by construction. Until this gate landed an
6701            // author who wrote `:placement (:estrategia Replicated
6702            // :shard-key "tenantId")` (an off-by-one strategy typo, a
6703            // copy-paste from a Sharded sibling caixa, the "I think I
6704            // configured sharding" footgun) silently passed validate and
6705            // the typed slot's value vanished at the renderer layer with
6706            // no diagnostic — the canonical "declared-but-inert" footgun
6707            // the empty-:affinity / empty-shard-key / zero-:politicas /
6708            // empty-:contratos-target gates already close on every other
6709            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6710            // Lifting the rejection to a build-time gate closes the
6711            // Sharded ↔ non-Sharded partition over the typed
6712            // `:placement` slot: every validated `Placement` past this
6713            // call has `shard_key.is_some()` iff `estrategia ==
6714            // Sharded`, structurally — the future Akka reconciler can
6715            // reach for `placement.shard_key` knowing it's `Some` exactly
6716            // when the strategy consumes it, without re-deriving the
6717            // partition from inline strategy probes.
6718            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6719                // Route the non-`Sharded`-arm declared-but-inert refusal
6720                // through the typed [`Placement::shard_key`] accessor —
6721                // the second of the two open-coded field-access sites the
6722                // accessor lift now owns. The `Some(k)`-bound `k` narrows
6723                // from `&String` to `&str`; the `AplicacaoError::
6724                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6725                // materializes the owned `String` via `k.to_string()`
6726                // (peer to the sibling per-Membro `String`-carry sites
6727                // 4127bb6 routed through `m.nome().to_string()` /
6728                // `m.versao_requirement().to_string()`), so the whole
6729                // `Sharded` ↔ non-`Sharded` partition on the
6730                // `:shard-key` axis now flows through the same typed
6731                // dispatch as the sibling `Sharded`-arm shape gate.
6732                if let Some(k) = p.shard_key() {
6733                    return Err(AplicacaoError::ShardKeyOnNonSharded {
6734                        estrategia: p.estrategia(),
6735                        shard_key: k.to_string(),
6736                    });
6737                }
6738            }
6739        }
6740        Ok(())
6741    }
6742
6743    /// Reject `:politicas` values that are operationally meaningless.
6744    /// Each axis is optional — omitting it expresses "no policy on this
6745    /// axis". Carrying a *zero* value for a declared axis is the bug
6746    /// this function rejects: zero is either
6747    ///
6748    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
6749    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
6750    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
6751    ///     "every Aplicacao declares :politicas :timeout (no infinite
6752    ///     blocking)", or
6753    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
6754    ///     first call; a 0-rate rate-limit denies every request).
6755    ///
6756    /// Lifting these "0 means the opposite of what you think" idioms to
6757    /// the typed Aplicacao surface as build errors mirrors the §III.3
6758    /// promise that contract drift, capability leaks, and cycles are all
6759    /// build errors — not runtime surprises.
6760    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6761        // Route the per-`:politicas` composite-reference read through
6762        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6763        // than the raw `&self.politicas` field access — the per-axis
6764        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6765        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6766        // the substrate-primitive typed dispatch at the outer
6767        // composition altitude AND at every per-axis altitude, matching
6768        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6769        // timeout/retry-overlay emitters that already key off the same
6770        // per-axis accessor family. The four-axis fan-out is now
6771        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6772        // `p.retries` field-access sites (co-resident with the peer
6773        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6774        // b0e741a / 21a6c3b already lifted) now route through
6775        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6776        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6777        // access axis on the M3 mesh-slot family.
6778        let p = self.politicas();
6779        if let Some(t) = p.timeout() {
6780            // Zero-floor + integer-millisecond canonical-form +
6781            // upper-cap bracket on the typed `:timeout` axis. See
6782            // [`crate::render::require_positive_canonical_bounded_duration`]
6783            // for the full three-arm ordering discipline (zero-floor
6784            // strictly precedes the canonical-form arm so
6785            // `Duration::ZERO` surfaces the self-locating
6786            // `PolicyTimeoutZero` diagnostic naming the omit-axis
6787            // remediation; canonical-form strictly precedes the cap
6788            // arm so a sub-millisecond above-cap `Duration` surfaces
6789            // the more fundamental round-trip-shape diagnostic first)
6790            // and the four peer typed-`Duration` sites that now share
6791            // this canonical bracket. Every validated value lies in
6792            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6793            // granularity — the same top-and-bottom-edge discipline
6794            // [`POLICY_RETRIES_MAX`] and
6795            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6796            // capped-`u32` `:politicas` axes.
6797            crate::render::require_positive_canonical_bounded_duration(
6798                t,
6799                POLICY_TIMEOUT_MAX,
6800                || AplicacaoError::PolicyTimeoutZero,
6801                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6802                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6803            )?;
6804        }
6805        if let Some(r) = p.retries() {
6806            // Zero-floor + upper-cap bracket on the typed `:retries`
6807            // axis. See [`crate::render::require_positive_bounded_u32`]
6808            // for the ordering discipline (zero-floor arm strictly
6809            // precedes cap arm so `Some(0)` surfaces the self-locating
6810            // `PolicyRetriesZero` diagnostic with its omit-axis
6811            // remediation directly named, not the misleading
6812            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6813            // this bracket landed the top edge ran all the way to
6814            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6815            // Some(100_000), .. }` (or the equivalent author-surface
6816            // `(:retries 100000)` / `(:retries 4294967295)` typo
6817            // landing in the slot) silently passed validate. The
6818            // runtime substrate consuming the value (Envoy's
6819            // `retry_policy.num_retries`, the future
6820            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6821            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6822            // policy into a thundering-herd amplification vector —
6823            // the caller's one request fans out to `retries`
6824            // server-side calls per edge per traversal, multiplying
6825            // load by `(retries+1)^depth` across the
6826            // synchronous-`:contratos` subgraph at the precise moment
6827            // the substrate is already failing (transient failure is
6828            // the trigger), exactly the failure mode AWS App Mesh's
6829            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6830            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6831            // the sibling capped-`u32` `:politicas` axes
6832            // (`max_failures`, `rate_limit.rate`) and the peer capped-
6833            // `u32` axes in `:supervisor :max-restarts` +
6834            // `:limits :cpu`; all five now route through the same
6835            // canonical bracket helper.
6836            crate::render::require_positive_bounded_u32(
6837                r,
6838                POLICY_RETRIES_MAX,
6839                || AplicacaoError::PolicyRetriesZero,
6840                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6841            )?;
6842        }
6843        if let Some(cb) = p.circuit_breaker() {
6844            // Zero-floor + upper-cap bracket on the typed
6845            // `:max-failures` axis. See
6846            // [`crate::render::require_positive_bounded_u32`] for the
6847            // ordering discipline (zero-floor arm strictly precedes
6848            // cap arm so `max_failures == 0` surfaces the
6849            // self-locating `PolicyBreakerZeroFailures` diagnostic
6850            // with its omit-axis remediation directly named, not the
6851            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6852            // false` cap-arm miss). Until this bracket landed the top
6853            // edge ran all the way to `u32::MAX` and a struct-literal
6854            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6855            // equivalent author-surface `(:max-failures 100000)` /
6856            // `(:max-failures 4294967295)` typo landing in the slot)
6857            // silently passed validate. The runtime substrate
6858            // consuming the value (Envoy's
6859            // `outlier_detection.consecutive_5xx`, the future
6860            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6861            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6862            // breaker policy into a no-op — the trip threshold is
6863            // structurally so high that no realistic
6864            // failures-per-`:window` traffic shape can reach it, the
6865            // breaker never trips, and every typed-slot consumer
6866            // emits an Envoy / Cilium L7 overlay carrying a
6867            // protection that is structurally never enforced. The
6868            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6869            // peer with `retries` and `rate_limit.rate` on the same
6870            // helper.
6871            crate::render::require_positive_bounded_u32(
6872                cb.max_failures(),
6873                POLICY_BREAKER_MAX_FAILURES_MAX,
6874                || AplicacaoError::PolicyBreakerZeroFailures,
6875                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6876            )?;
6877            // Zero-floor + integer-millisecond canonical-form +
6878            // upper-cap bracket on the typed `:window` axis. See
6879            // [`crate::render::require_positive_canonical_bounded_duration`]
6880            // for the full three-arm ordering discipline (peer to the
6881            // `:timeout` site immediately above); every validated
6882            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6883            // (1ms..=1h), integer-millisecond granularity — the same
6884            // top-and-bottom-edge discipline
6885            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6886            // duration-typed `:politicas :timeout` axis.
6887            crate::render::require_positive_canonical_bounded_duration(
6888                cb.window(),
6889                POLICY_BREAKER_WINDOW_MAX,
6890                || AplicacaoError::PolicyBreakerZeroWindow,
6891                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6892                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6893            )?;
6894        }
6895        if let Some(rl) = p.rate_limit() {
6896            // Zero-floor + upper-cap bracket on the typed
6897            // `:rate-limit` rate axis. See
6898            // [`crate::render::require_positive_bounded_u32`] for the
6899            // ordering discipline (zero-floor arm strictly precedes
6900            // cap arm so `rl.rate == 0` surfaces the self-locating
6901            // `PolicyRateLimitZero` diagnostic with its omit-axis
6902            // remediation directly named, not the misleading
6903            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6904            // Until this bracket landed the top edge ran all the way
6905            // to `u32::MAX` and a struct-literal
6906            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6907            // author-surface `(:rate-limit "4294967295/s")` /
6908            // `(:rate-limit "100000000/m")` typo landing in the slot)
6909            // silently passed validate. The runtime substrate
6910            // consuming the value (Envoy's
6911            // `local_rate_limit.token_bucket.max_tokens`, the future
6912            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6913            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6914            // rate-limit policy into a no-op limiter: the bucket
6915            // capacity is structurally so high that no realistic
6916            // per-edge traffic shape can drain it, the limiter never
6917            // trips, and every typed-slot consumer emits a "rate
6918            // declared" L7 overlay carrying enforcement that is
6919            // structurally never reached — the canonical
6920            // declared-but-inert footgun the sibling
6921            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6922            // the peer no-op-breaker shape. The bracket set is
6923            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6924            // `max_failures` on the same helper. The rate bracket
6925            // strictly precedes the window-canonical gate so a
6926            // structurally absurd rate magnitude surfaces the more
6927            // fundamental amplification-shape diagnostic before the
6928            // narrower codec-round-trip-shape diagnostic on `:window`.
6929            crate::render::require_positive_bounded_u32(
6930                rl.rate(),
6931                POLICY_RATE_LIMIT_MAX,
6932                || AplicacaoError::PolicyRateLimitZero,
6933                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6934            )?;
6935            // The `:rate-limit` author surface is the canonical
6936            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6937            // accepts exactly the three-unit set (1s/60s/3600s) the
6938            // [`rate_limit_codec::render`] formatter emits the canonical
6939            // unit suffix for. A `RateLimit` whose `:window` is anything
6940            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6941            // programmatically (struct literals in Rust + the typed
6942            // `Duration` field) but renders to a `<n>/<k>s` fragment
6943            // (the codec's fall-through) the parser then rejects on
6944            // round-trip — silently breaking the THEORY.md §V.2.7
6945            // render-determinism contract for any consumer that
6946            // serializes-then-deserializes the typed slot. Lifting the
6947            // canonical-window invariant to a build-time gate at
6948            // `validate_politicas` makes the codec's round-trip property
6949            // a structural property of the validated typed value:
6950            // every `RateLimit` past `AplicacaoSpec::validate` has a
6951            // window the codec round-trips losslessly, so the next
6952            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6953            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6954            // §III.2 #3) reaches for `rate_limit.window` knowing the
6955            // value is in the codec's accepted set without re-validating
6956            // at the renderer layer. Same trajectory as c4213a4 (typed
6957            // WitContract endpoint/subject/slot value-shape gates) and
6958            // the b0c8389 :behavior + :upgrade-from script-path lifts:
6959            // the typed slot's valid set matches its codec's accepted
6960            // set, structurally.
6961            // Route the canonical-window shape-gate through the substrate
6962            // primitive [`RateLimit::canonical_unit`] rather than the free
6963            // module-private [`is_canonical_rate_limit_window`] predicate:
6964            // both projections resolve `Duration → Option<RateLimitUnit>`
6965            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
6966            // arm on the closed-set typed enum), but the accessor is the
6967            // typed method every downstream consumer of the validated slot
6968            // ([`rate_limit_codec::render`]'s canonical arm above, the
6969            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6970            // per-`:politicas :rate-limit` admission webhook, the future
6971            // per-`:contratos`-edge rate-limit-override overlay
6972            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
6973            // production consumers of the canonical-unit axis (the codec
6974            // render and this validate gate) now key off exactly one typed
6975            // dispatch on the substrate primitive, so any future extension
6976            // to `canonical_unit` (a per-cluster canonical-window overlay
6977            // the operator pins through a future `:contratos :rate-limit
6978            // -unit-overrides` slot, a per-tenant unit-alias table the M4
6979            // CR materializer resolves per-CR) reaches both consumers by
6980            // construction rather than a coordinated rewrite of every
6981            // free-helper call site.
6982            if rl.canonical_unit().is_none() {
6983                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6984                    window: rl.window(),
6985                });
6986            }
6987        }
6988        Ok(())
6989    }
6990
6991    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6992    /// A synchronous edge is any contract whose typed [`WitTarget`] is
6993    /// `Http`, `Store`, or `Capability` — the caller blocks on the
6994    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6995    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6996    /// block on its subscribers, so they can never close a sync loop.
6997    ///
6998    /// Iterative DFS with three-coloring; the reported cycle is the
6999    /// path of caixa names traversed from the back-edge target around
7000    /// to itself, in declaration order. Adjacency lists and DFS roots
7001    /// are visited in `BTreeMap` key order so the diagnostic is
7002    /// deterministic across runs.
7003    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7004        use std::collections::{BTreeMap, BTreeSet};
7005
7006        #[derive(Clone, Copy, PartialEq, Eq)]
7007        enum Mark {
7008            White,
7009            Gray,
7010            Black,
7011        }
7012
7013        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7014        for m in self.membros() {
7015            adj.entry(m.nome()).or_default();
7016        }
7017        for c in self.contratos() {
7018            // target() was already called by validate(); re-running here
7019            // keeps detect_sync_cycles self-contained for callers that
7020            // reuse it (M4 per-edge policy resolver) without revalidating.
7021            //
7022            // The pub-sub-arm check routes through the lifted
7023            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7024            // arm-discriminator predicate rather than a raw `matches!(…,
7025            // WitTarget::PubSub { .. })` on the variant so a future
7026            // rebrand on the axis (an M4 per-edge WIT registry split of
7027            // [`WitTarget::PubSub`] into shape-specific peers, a
7028            // per-consumer rename that the accept-set already carries)
7029            // reaches this call site through the derive rather than a
7030            // scattered per-arm `matches!` rewrite — same
7031            // `IsVariant`-derived-arm-discriminator discipline the
7032            // peer closed-set typed enums ([`crate::CaixaKind`] via
7033            // f5bba80, [`PlacementStrategy`] via 766ec63,
7034            // [`crate::supervisor::RestartStrategy`] +
7035            // [`crate::supervisor::RestartPolicy`],
7036            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7037            // already route through on the substrate's other typed-enum
7038            // arm-discriminator axes.
7039            if c.target()?.is_pubsub() {
7040                continue;
7041            }
7042            adj.entry(c.source()).or_default().insert(c.destination());
7043        }
7044
7045        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7046        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7047
7048        // Stable DFS root order — BTreeMap iteration is sorted by key.
7049        let roots: Vec<&str> = adj.keys().copied().collect();
7050
7051        // Frame: (node, sorted-neighbours snapshot, next-edge index).
7052        for root in roots {
7053            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7054                continue;
7055            }
7056            let root_neighbors: Vec<&str> = adj
7057                .get(root)
7058                .map(|s| s.iter().copied().collect())
7059                .unwrap_or_default();
7060            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7061            color.insert(root, Mark::Gray);
7062
7063            loop {
7064                // Read+advance the top frame in one borrow scope so we
7065                // can later mutate the stack (push/pop) without holding
7066                // a borrow across.
7067                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7068                    let node = top.0;
7069                    if top.2 >= top.1.len() {
7070                        (node, None)
7071                    } else {
7072                        let nxt = top.1[top.2];
7073                        top.2 += 1;
7074                        (node, Some(nxt))
7075                    }
7076                });
7077                let Some((node, nxt_opt)) = step else { break };
7078                let Some(nxt) = nxt_opt else {
7079                    color.insert(node, Mark::Black);
7080                    stack.pop();
7081                    continue;
7082                };
7083                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7084                match nxt_color {
7085                    Mark::Gray => {
7086                        // Reconstruct the cycle from `node` back through
7087                        // the parent chain to `nxt`, then close.
7088                        let mut cycle = Vec::new();
7089                        let mut cur = node;
7090                        cycle.push(cur.to_string());
7091                        while cur != nxt {
7092                            match parent.get(cur).copied() {
7093                                Some(p) => {
7094                                    cur = p;
7095                                    cycle.push(cur.to_string());
7096                                }
7097                                None => break,
7098                            }
7099                        }
7100                        cycle.reverse();
7101                        cycle.push(nxt.to_string());
7102                        return Err(AplicacaoError::ContratoCycle { cycle });
7103                    }
7104                    Mark::White => {
7105                        parent.insert(nxt, node);
7106                        color.insert(nxt, Mark::Gray);
7107                        let nxt_neighbors: Vec<&str> = adj
7108                            .get(nxt)
7109                            .map(|s| s.iter().copied().collect())
7110                            .unwrap_or_default();
7111                        stack.push((nxt, nxt_neighbors, 0));
7112                    }
7113                    Mark::Black => {}
7114                }
7115            }
7116        }
7117        Ok(())
7118    }
7119
7120    /// Substrate-canonical destination-facing TCP port every emitted
7121    /// per-Aplicacao artifact must key `destination`-shaped port axes
7122    /// off. Returns the typed `:entrada :port` scalar when this
7123    /// Aplicacao's `:entrada` block names `destination` under its
7124    /// `:para` axis (the destination Servico *is* the ingress apex, so
7125    /// the substrate honors the author-declared listener port
7126    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7127    /// fallback otherwise (every non-apex destination — the internal
7128    /// mesh Servicos `:contratos` reach across, the future per-edge
7129    /// policy resolver's per-destination probe targets, the
7130    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7131    /// L4 port resolver — reads the same substrate-canonical port floor
7132    /// by construction).
7133    ///
7134    /// Prior to this lift the "if :entrada matches this destination use
7135    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7136    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7137    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7138    /// prior to this lift), with no typed method on the substrate primitive
7139    /// that named the rule. A future per-destination port axis addition
7140    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7141    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7142    /// per-Servico listener ports land, a per-cluster override the operator
7143    /// pins through a future `:placement :default-port` slot — would have
7144    /// to be threaded through every renderer's inline cascade in lockstep
7145    /// or one consumer would silently disagree on which port a given
7146    /// destination Servico's ingress lands at. Lifting the rule to a
7147    /// typed method on the substrate primitive means the M4 CR
7148    /// materializer, the future per-edge policy resolver, and every
7149    /// downstream test-fixture navigator reach for exactly one typed
7150    /// dispatch — the resolver's accept-set moves as a unit on any
7151    /// future axis addition.
7152    ///
7153    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7154    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7155    /// the typed primitive, thin projections at each consumer"
7156    /// discipline lifts on the sibling `:contratos` payload / `:politicas
7157    /// :rate-limit` unit-suffix axes; extends the discipline onto the
7158    /// destination-facing port-resolution axis every per-Aplicacao
7159    /// L4-fallback renderer consumes.
7160    #[must_use]
7161    pub fn port_for_destination(&self, destination: &str) -> u16 {
7162        // Route the per-`:entrada` composite-reference read through
7163        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7164        // the raw `self.entrada.as_ref()` field access — the
7165        // per-destination L4-port fallback resolver's composite-
7166        // projection seed is now the canonical read-side surface
7167        // every per-Aplicacao entrada consumer routes through, peer
7168        // of the sibling `validate` per-`:entrada` shape-and-
7169        // membership gate migration on the same outer-composite
7170        // axis.
7171        // Route the per-`:entrada` apex-destination membership probe
7172        // through the lifted [`Entrada::destination`] accessor rather
7173        // than the raw `e.para == destination` field access — the last
7174        // un-lifted `.para` production-code read site on the per-
7175        // `:entrada` `:para` axis, sibling to the four caixa-core
7176        // consumer sites the peer 15ddd8c converge already routed
7177        // through the accessor (the three
7178        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7179        // membership gate sites: the `validate_entrada_para` DNS-1123
7180        // shape gate, the per-`:membros` membership lookup, and the
7181        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7182        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7183        // `entrada.para`-projection converge at
7184        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7185        // route-name projection site). Prior to this converge the
7186        // `port_for_destination` resolver was the solitary consumer
7187        // bypassing the typed dispatch on the `.para` axis — the two
7188        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7189        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7190        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7191        // reach through the same accessor family compose with this
7192        // resolver at the emit boundary via the apex-identity
7193        // invariant `spec.port_for_destination(entrada.destination())
7194        // == entrada.port` the sibling
7195        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7196        // pin pins across four permutations. A future extension of the
7197        // `:entrada :para` axis to a richer author surface (a per-
7198        // cluster alias overlay the operator pins through a future
7199        // `:placement`-scoped slot, a namespace-qualified rewrite the
7200        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7201        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7202        // §III.2 acknowledges) that lands on the accessor would silently
7203        // disagree between this resolver and the two `caixa-mesh` emit
7204        // sites — an author-declared `:para "cart"` value the accessor
7205        // rewrote to `"cart-v2"` under a future canary arm would leave
7206        // the resolver's membership arm falling through to
7207        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7208        // `.para`) while the peer emit-site consumers landed on the
7209        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7210        // silently disagreed on which destination port a given typed
7211        // `:entrada` resolves to at cluster-apply time. Pinned by the
7212        // drift-detection test
7213        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7214        // below.
7215        self.entrada()
7216            .filter(|e| e.destination() == destination)
7217            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7218    }
7219}
7220
7221/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7222/// entry may name the Aplicacao's own `:nome`.
7223///
7224/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7225/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7226/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7227/// Servicos that compose the app; an Aplicacao is never its own constituent),
7228/// and the lacre pipeline's closure-resolution would otherwise be handed a
7229/// node that is its own parent: a one-node cycle it either rejects far from
7230/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7231/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7232/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7233/// label + lacre closure root), a member whose `:caixa` equals the
7234/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7235/// peer.
7236///
7237/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7238/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7239/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7240/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7241/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7242/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7243/// (the Aplicacao :membros set; the supervision-tree :children list was the
7244/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7245/// every validated Supervisor's children are distinct from its `:nome`,
7246/// every validated Aplicacao's membros are distinct from its `:nome`. The
7247/// transitive consequence is that `:entrada :para` and `:contratos`
7248/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7249/// name the Aplicacao itself, without re-deriving the partition.
7250pub fn validate_no_self_membership(
7251    membros: &[Membro],
7252    parent_nome: &str,
7253) -> Result<(), AplicacaoError> {
7254    for m in membros {
7255        if m.nome() == parent_nome {
7256            return Err(AplicacaoError::MembroIsSelfAplicacao {
7257                caixa: parent_nome.to_string(),
7258            });
7259        }
7260    }
7261    Ok(())
7262}
7263
7264#[derive(Debug, Error, PartialEq, Eq)]
7265pub enum AplicacaoError {
7266    #[error("Aplicacao must declare at least one :membros entry")]
7267    NoMembros,
7268    #[error(
7269        ":membros entry has empty :caixa (every member must name a Servico; \
7270         omit the entry instead of carrying an empty name)"
7271    )]
7272    MembroCaixaEmpty,
7273    #[error(
7274        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7275         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7276         name / label value the member name lands in; use a lowercase \
7277         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7278    )]
7279    MembroCaixaInvalid { caixa: String, reason: String },
7280    #[error(
7281        ":membros entry {caixa:?} has empty :versao (every member must pin a \
7282         semver constraint that resolves through the lacre pipeline)"
7283    )]
7284    MembroVersaoEmpty { caixa: String },
7285    #[error(
7286        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7287         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7288         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7289         carries; the lacre pipeline resolves both through the same parser)"
7290    )]
7291    MembroVersaoInvalid {
7292        caixa: String,
7293        versao: String,
7294        reason: String,
7295    },
7296    #[error(
7297        ":membros entry {caixa:?} appears more than once (the graph node set \
7298         is a set, not a multiset; duplicate members produce duplicate \
7299         programs.yaml entries and ambiguous :contratos membership lookups)"
7300    )]
7301    MembroDuplicate { caixa: String },
7302    #[error(
7303        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7304         never its own constituent Servico (the application graph is a DAG rooted \
7305         at the Aplicacao; :membros names the *other* caixas that compose the \
7306         app, not the app itself). Since every :nome is a globally-unique \
7307         substrate identity, a member naming the Aplicacao's own :nome is a \
7308         one-node lacre-closure recursion, not a coincidentally-named peer; \
7309         drop the self-referential :membros entry or rename it to the actual \
7310         constituent caixa."
7311    )]
7312    MembroIsSelfAplicacao { caixa: String },
7313    #[error(
7314        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7315         caixa declared in :membros; omit the contract or fill the {slot} field with a \
7316         member name)"
7317    )]
7318    ContratoCaixaEmpty { slot: &'static str },
7319    #[error(
7320        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7321         :contratos {slot} value names a member of :membros, which is itself a \
7322         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7323         object the member name lands in — Service, Pod, identity-based Cilium \
7324         selector; use a lowercase alphanumeric + hyphen identifier like \
7325         `\"checkout\"` or `\"cart-v2\"`)"
7326    )]
7327    ContratoCaixaInvalid {
7328        slot: &'static str,
7329        caixa: String,
7330        reason: String,
7331    },
7332    #[error("contrato references caixa {caixa:?} not declared in :membros")]
7333    ContratoMemberMissing { caixa: String },
7334    #[error(
7335        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7336         entry is an inter-Servico contract whose :de and :para must name distinct \
7337         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7338         the contract, or point :para at the member it actually calls)"
7339    )]
7340    ContratoSelfLoop { caixa: String, wit: String },
7341    #[error("contrato {de:?} → {para:?} has empty :wit")]
7342    EmptyWit { de: String, para: String },
7343    #[error(
7344        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7345         {reason} (the substrate dispatches `:wit` values on the canonical \
7346         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7347         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7348         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7349         kebab-case identifier per segment)"
7350    )]
7351    ContratoWitInvalid {
7352        de: String,
7353        para: String,
7354        wit: String,
7355        reason: String,
7356    },
7357    #[error(
7358        ":entrada :para is empty (every :entrada must route to a caixa declared in \
7359         :membros; fill the :para field with a member name)"
7360    )]
7361    EntradaParaEmpty,
7362    #[error(
7363        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7364         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7365         label per the K8s apiserver's `metadata.name` rule on every object the \
7366         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7367         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7368         `\"checkout\"` or `\"cart-v2\"`)"
7369    )]
7370    EntradaParaInvalid { para: String, reason: String },
7371    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7372    EntradaMemberMissing { para: String },
7373    #[error(":entrada must declare a non-empty :host")]
7374    EmptyEntradaHost,
7375    #[error(
7376        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7377         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7378         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7379         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7380    )]
7381    EntradaHostInvalid { host: String, reason: String },
7382    #[error(":entrada :port must be in 1..=65535, got 0")]
7383    EntradaPortZero,
7384    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7385    EntradaPathEmpty,
7386    #[error(
7387        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7388    )]
7389    EntradaPathNotAbsolute { path: String },
7390    #[error(
7391        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7392         value: {reason} (the K8s apiserver enforces the same shape on \
7393         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7394         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7395         requires percent-encoding `%XX` for non-ASCII and whitespace)"
7396    )]
7397    EntradaPathInvalid { path: String, reason: String },
7398    #[error(":entrada :paths entry {path:?} appears more than once")]
7399    EntradaPathDuplicate { path: String },
7400    #[error(
7401        ":placement {estrategia} requires at least one :clusters entry \
7402         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7403    )]
7404    PlacementWithoutClusters { estrategia: PlacementStrategy },
7405    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7406    PlacementClusterEmpty,
7407    #[error(
7408        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7409         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7410         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7411         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7412         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7413         identifier like `\"rio\"` or `\"mar-east\"`)"
7414    )]
7415    PlacementClusterInvalid { cluster: String, reason: String },
7416    #[error(":placement :clusters entry {cluster:?} appears more than once")]
7417    PlacementClusterDuplicate { cluster: String },
7418    #[error(
7419        ":placement :affinity must be non-empty when set (omit :affinity to express \
7420         `no placement hint`)"
7421    )]
7422    PlacementAffinityEmpty,
7423    #[error(
7424        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7425         (placement hints land verbatim in the M3 Adaptive compression overlay's \
7426         `placement.affinity` field and in every future M4 placement-engine routing \
7427         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7428         selector — both enforce the DNS-1123 label rule on admission; use a \
7429         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7430         `\"low-latency\"`, or `\"anti-affinity\"`)"
7431    )]
7432    PlacementAffinityInvalid { affinity: String, reason: String },
7433    #[error(":placement Sharded requires :shard-key")]
7434    ShardedWithoutKey,
7435    #[error(
7436        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7437         hashes every entity onto the same shard, defeating sharding entirely)"
7438    )]
7439    ShardedKeyEmpty,
7440    #[error(
7441        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7442         entity-id extractor expression: {reason} (the future M4 Akka-style \
7443         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7444         as a single-token property reference and hashes the extracted entity ID \
7445         to compute shard placement; use a printable-ASCII extractor expression \
7446         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7447         `\"${{tenant}}\"`)"
7448    )]
7449    ShardKeyInvalid { shard_key: String, reason: String },
7450    #[error(
7451        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7452         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7453         convention); :estrategia Replicated runs every cluster active-active and \
7454         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7455         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7456         to :estrategia Sharded if hash-keyed routing is the intent"
7457    )]
7458    ShardKeyOnNonSharded {
7459        estrategia: PlacementStrategy,
7460        shard_key: String,
7461    },
7462    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7463    ContratoMissingTarget {
7464        de: String,
7465        para: String,
7466        wit: String,
7467        expected: &'static str,
7468    },
7469    #[error(
7470        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7471         expected `:{expected}` only"
7472    )]
7473    ContratoWrongTarget {
7474        de: String,
7475        para: String,
7476        wit: String,
7477        expected: &'static str,
7478    },
7479    #[error(
7480        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7481         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7482         that matches no traffic and silently drops every request)"
7483    )]
7484    ContratoEndpointEmpty { de: String, para: String },
7485    #[error(
7486        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7487         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7488         :entrada :paths)"
7489    )]
7490    ContratoEndpointNotAbsolute {
7491        de: String,
7492        para: String,
7493        endpoint: String,
7494    },
7495    #[error(
7496        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7497         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7498         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7499         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7500         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7501         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7502         and whitespace)"
7503    )]
7504    ContratoEndpointInvalid {
7505        de: String,
7506        para: String,
7507        endpoint: String,
7508        reason: String,
7509    },
7510    #[error(
7511        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7512         subject is a no-op subscribe; omit :subject only if the WIT world is not \
7513         pub-sub-shaped)"
7514    )]
7515    ContratoSubjectEmpty { de: String, para: String },
7516    #[error(
7517        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7518         NATS subject: {reason} (the NATS server's subject parser enforces the \
7519         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7520         single-token and `>` multi-token wildcards — at publish/subscribe time; \
7521         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7522         `\"orders.*.completed\"` — a malformed subject silently drops every \
7523         message at runtime far from the source caixa.lisp)"
7524    )]
7525    ContratoSubjectInvalid {
7526        de: String,
7527        para: String,
7528        subject: String,
7529        reason: String,
7530    },
7531    #[error(
7532        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7533         addresses the bucket root, defeating the per-key isolation the slot exists \
7534         for; omit :slot only if the WIT world is not store-shaped)"
7535    )]
7536    ContratoSlotEmpty { de: String, para: String },
7537    #[error(
7538        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7539         WASI keyvalue store slot template: {reason} (the substrate enforces \
7540         the printable-ASCII intersection-floor every kv backend admits — \
7541         use a single-token path / template expression like `\"checkout/$orderId\"`, \
7542         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7543         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7544         slot either gets rejected on write by strict backends or silently \
7545         corrupts the next read on permissive ones, far from the source caixa.lisp)"
7546    )]
7547    ContratoSlotInvalid {
7548        de: String,
7549        para: String,
7550        slot: String,
7551        reason: String,
7552    },
7553    #[error(
7554        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7555         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7556        cycle.join(" → ")
7557    )]
7558    ContratoCycle { cycle: Vec<String> },
7559    #[error(
7560        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7561         than once (the typed graph edges are a set, not a multiset; duplicate \
7562         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7563         values that K8s admission rejects far from the source caixa.lisp)"
7564    )]
7565    ContratoDuplicate {
7566        de: String,
7567        para: String,
7568        wit: String,
7569        target: String,
7570    },
7571    #[error(
7572        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7573         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7574         express `no per-call deadline on this axis`"
7575    )]
7576    PolicyTimeoutZero,
7577    #[error(
7578        ":politicas :retries must be > 0 when set; omit :retries to express \
7579         `no retries on transient failure`"
7580    )]
7581    PolicyRetriesZero,
7582    #[error(
7583        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7584         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7585         retry policy into a thundering-herd amplification vector on transient \
7586         failure (one caller request fans out to `(retries+1)^depth` server-side \
7587         calls across the synchronous-:contratos subgraph), exactly the failure \
7588         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7589         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7590         or omit :retries to disable retries entirely"
7591    )]
7592    PolicyRetriesExceedsCap { retries: u32 },
7593    #[error(
7594        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7595         breaker trips on the first call); omit :circuit-breaker to disable it"
7596    )]
7597    PolicyBreakerZeroFailures,
7598    #[error(
7599        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7600         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7601         above this cap turns the typed breaker policy into a no-op: the trip \
7602         threshold is structurally so high that no realistic failures-per-:window \
7603         traffic shape can reach it, so the breaker never trips and every typed-slot \
7604         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7605         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7606         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7607         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7608         omit :circuit-breaker to disable the breaker entirely"
7609    )]
7610    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7611    #[error(
7612        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7613         tracks no failures); omit :circuit-breaker to disable it"
7614    )]
7615    PolicyBreakerZeroWindow,
7616    #[error(
7617        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7618         request); omit :rate-limit to disable rate limiting"
7619    )]
7620    PolicyRateLimitZero,
7621    #[error(
7622        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7623         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7624         rate-limit policy into a no-op limiter: the token-bucket capacity is \
7625         structurally so high that no realistic per-edge traffic shape can drain it, \
7626         so the limiter never trips and every typed-slot consumer (the future \
7627         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7628         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7629         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7630         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7631         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7632         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7633         to disable rate limiting entirely"
7634    )]
7635    PolicyRateLimitExceedsCap { rate: u32 },
7636    #[error(
7637        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7638         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7639         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7640         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7641         three canonical windows)"
7642    )]
7643    PolicyRateLimitWindowNotCanonical { window: Duration },
7644    #[error(
7645        ":politicas :timeout must be an integer number of milliseconds — the canonical \
7646         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7647         duration codec round-trips losslessly; got {timeout:?} which carries a \
7648         sub-millisecond residue that either truncates to a different `Duration` on \
7649         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7650         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7651         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7652         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7653    )]
7654    PolicyTimeoutNotCanonical { timeout: Duration },
7655    #[error(
7656        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7657         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7658         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7659         overlays carry a deadline so long no realistic synchronous-:contratos \
7660         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7661         CSE invariant degenerates to enforcement only at the per-Servico \
7662         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7663         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7664         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7665         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7666         maxes out at the same `3600s` ceiling) or omit :timeout to express \
7667         `no per-call deadline on this axis` (the synchronous-call deadline then \
7668         relies entirely on the per-Servico `:limits :wall-clock` axis)"
7669    )]
7670    PolicyTimeoutExceedsCap { timeout: Duration },
7671    #[error(
7672        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7673         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7674         the shared duration codec round-trips losslessly; got {window:?} which carries a \
7675         sub-millisecond residue that either truncates to a different `Duration` on \
7676         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7677         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7678    )]
7679    PolicyBreakerWindowNotCanonical { window: Duration },
7680    #[error(
7681        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7682         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7683         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7684         is structurally so long that transient failures are never forgotten, the breaker \
7685         trips once and stays tripped for the lifetime of the component, and every typed-slot \
7686         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7687         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7688         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7689         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7690         the breaker entirely"
7691    )]
7692    PolicyBreakerWindowExceedsCap { window: Duration },
7693}
7694
7695#[cfg(test)]
7696mod tests {
7697    use super::*;
7698
7699    fn membro(name: &str, ver: &str) -> Membro {
7700        Membro {
7701            caixa: name.into(),
7702            versao: ver.into(),
7703        }
7704    }
7705
7706    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7707        WitContract {
7708            de: de.into(),
7709            para: para.into(),
7710            wit: "wasi:http/proxy".into(),
7711            endpoint: Some(ep.into()),
7712            subject: None,
7713            slot: None,
7714        }
7715    }
7716
7717    fn three_member_spec() -> AplicacaoSpec {
7718        AplicacaoSpec {
7719            membros: vec![
7720                membro("catalog", "^0.1"),
7721                membro("cart", "^0.1"),
7722                membro("payment", "^0.2"),
7723            ],
7724            contratos: vec![
7725                contract_http("cart", "catalog", "/products/:id"),
7726                contract_http("cart", "payment", "/charge"),
7727            ],
7728            politicas: MeshPolicy {
7729                timeout: Some(Duration::from_secs(30)),
7730                retries: Some(3),
7731                mtls_required: Some(true),
7732                ..Default::default()
7733            },
7734            placement: Placement {
7735                estrategia: PlacementStrategy::Replicated,
7736                clusters: vec!["rio".into(), "mar".into()],
7737                affinity: Some("data-locality".into()),
7738                shard_key: None,
7739            },
7740            entrada: Some(Entrada {
7741                host: "checkout.quero.cloud".into(),
7742                para: "cart".into(),
7743                paths: vec!["/api/cart".into(), "/api/products".into()],
7744                port: 8080,
7745            }),
7746        }
7747    }
7748
7749    #[test]
7750    fn happy_path_validates() {
7751        three_member_spec().validate().unwrap();
7752    }
7753
7754    #[test]
7755    fn rejects_empty_membros() {
7756        let mut s = three_member_spec();
7757        s.membros = vec![];
7758        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7759    }
7760
7761    #[test]
7762    fn rejects_empty_membro_caixa() {
7763        // A `:caixa ""` entry has no name to render into programs.yaml
7764        // and no caixa.lisp to resolve at lacre time.
7765        let mut s = three_member_spec();
7766        s.membros[1].caixa = String::new();
7767        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7768    }
7769
7770    #[test]
7771    fn rejects_empty_membro_versao() {
7772        // A `:versao ""` entry can't pin a semver constraint, so the
7773        // lacre pipeline fails far from the source.
7774        let mut s = three_member_spec();
7775        s.membros[2].versao = String::new();
7776        let err = s.validate().unwrap_err();
7777        assert!(
7778            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7779            "got {err:?}"
7780        );
7781    }
7782
7783    #[test]
7784    fn rejects_duplicate_membro_caixa() {
7785        // Two `:membros` entries with the same `:caixa` collapse to one
7786        // node in the membership HashSet, which masks `:contratos`
7787        // membership errors and produces duplicate programs.yaml entries.
7788        let mut s = three_member_spec();
7789        s.membros.push(membro("cart", "^0.2"));
7790        let err = s.validate().unwrap_err();
7791        assert!(
7792            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7793            "got {err:?}"
7794        );
7795    }
7796
7797    #[test]
7798    fn rejects_invalid_membro_versao_requirement() {
7799        // The fail-before-pass-after pin: a non-empty but malformed
7800        // semver requirement (`"^bad-version"`) silently passed
7801        // `validate()` on every pre-gate codebase because the prior
7802        // shape only refused the empty string. The parse failure
7803        // surfaced far downstream at lacre-resolve time with a
7804        // `semver::Error` that didn't name which `:membros` entry
7805        // carried the typo. The new gate moves the check to caixa-build
7806        // time at the source caixa.lisp.
7807        let mut s = three_member_spec();
7808        s.membros[2].versao = "^bad-version".into();
7809        let err = s.validate().unwrap_err();
7810        assert!(
7811            matches!(
7812                err,
7813                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7814                    if caixa == "payment" && versao == "^bad-version"
7815            ),
7816            "got {err:?}"
7817        );
7818    }
7819
7820    #[test]
7821    fn rejects_membro_versao_with_double_caret_typo() {
7822        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7823        // Cargo-shaped requirement on first glance but fails the parser
7824        // because semver doesn't accept stacked operators. Pin this
7825        // adjacent-shape footgun explicitly so a future relaxation that
7826        // accepts "looks-canonical-but-isn't" forms surfaces here.
7827        let mut s = three_member_spec();
7828        s.membros[0].versao = "^^0.1".into();
7829        let err = s.validate().unwrap_err();
7830        assert!(
7831            matches!(
7832                err,
7833                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7834                    if caixa == "catalog" && versao == "^^0.1"
7835            ),
7836            "got {err:?}"
7837        );
7838    }
7839
7840    #[test]
7841    fn rejects_membro_versao_with_v_prefixed_tag() {
7842        // `"v0.1"` is the canonical "git-tag-shape leaking into the
7843        // semver requirement slot" typo — an author copies the
7844        // publish-side git-tag string verbatim into `:versao`, but
7845        // Cargo's semver parser rejects the leading `v` (only digits +
7846        // canonical operators are valid in the major-version
7847        // position). The gate's diagnostic names which member entry
7848        // carried the v-prefix so the fix is one edit, not a grep
7849        // through every member's `:versao`. (Note: bare `x`-glob
7850        // shorthands like `^0.1.x` are *accepted* by the semver crate
7851        // as an `*` wildcard on the patch axis — they're a Cargo-side
7852        // valid shape, not a typo, so the gate intentionally lets them
7853        // through.)
7854        let mut s = three_member_spec();
7855        s.membros[1].versao = "v0.1".into();
7856        let err = s.validate().unwrap_err();
7857        assert!(
7858            matches!(
7859                err,
7860                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7861                    if caixa == "cart" && versao == "v0.1"
7862            ),
7863            "got {err:?}"
7864        );
7865    }
7866
7867    #[test]
7868    fn accepts_canonical_membro_versao_forms() {
7869        // The four Cargo-shaped requirement forms `:deps :versao`
7870        // already accepts via `crate::parse_requirement` must pass the
7871        // membros gate without re-validating at the resolver layer.
7872        // Pin every leg so a future tightening of the canonical set
7873        // surfaces here as a test failure.
7874        for form in [
7875            "^0.1",      // caret — minor-range pin (the most common shape)
7876            "~0.1.2",    // tilde — patch-range pin
7877            "0.1.0",     // exact — single-version pin
7878            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
7879            ">=0.1, <2", // multi-range — comma-separated comparators
7880        ] {
7881            let mut s = three_member_spec();
7882            for m in &mut s.membros {
7883                m.versao = form.into();
7884            }
7885            s.validate()
7886                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7887        }
7888    }
7889
7890    #[test]
7891    fn membro_versao_empty_takes_precedence_over_invalid() {
7892        // Order pin: the existing `MembroVersaoEmpty` diagnostic
7893        // (which doesn't try to parse) fires before the new
7894        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7895        // `:versao` keeps its narrower error message — `parse_requirement`
7896        // would also reject `""`, but the empty-string arm is the more
7897        // self-locating diagnostic for the author.
7898        let mut s = three_member_spec();
7899        s.membros[1].versao = String::new();
7900        let err = s.validate().unwrap_err();
7901        assert!(
7902            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7903            "got {err:?}"
7904        );
7905    }
7906
7907    #[test]
7908    fn membro_versao_invalid_fires_before_duplicate_check() {
7909        // Order pin: a malformed requirement on a non-duplicate entry
7910        // surfaces *its own* diagnostic (which names the offending
7911        // `:versao` string), even when a later entry would otherwise
7912        // collapse onto an earlier name. The per-entry shape gate runs
7913        // inline before the duplicate-key insert, parallel to
7914        // `membros_validation_runs_before_contratos_membership_check`
7915        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7916        let mut s = three_member_spec();
7917        s.membros[0].versao = "^bad".into();
7918        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7919        let err = s.validate().unwrap_err();
7920        assert!(
7921            matches!(
7922                err,
7923                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7924            ),
7925            "got {err:?}"
7926        );
7927    }
7928
7929    #[test]
7930    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7931        // The diagnostic-shape pin: the error names the offending
7932        // `:versao` value verbatim so the author can grep their
7933        // caixa.lisp without re-running the build, and carries a
7934        // non-empty `reason` from `semver::VersionReq::parse` so the
7935        // parser's own wording flows through to the diagnostic.
7936        let mut s = three_member_spec();
7937        s.membros[2].versao = "not-a-req".into();
7938        let err = s.validate().unwrap_err();
7939        let AplicacaoError::MembroVersaoInvalid {
7940            caixa,
7941            versao,
7942            reason,
7943        } = err
7944        else {
7945            panic!("expected MembroVersaoInvalid, got other variant");
7946        };
7947        assert_eq!(caixa, "payment");
7948        assert_eq!(versao, "not-a-req");
7949        assert!(
7950            !reason.is_empty(),
7951            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7952        );
7953    }
7954
7955    #[test]
7956    fn membro_versao_invalid_runs_before_contratos_check() {
7957        // A malformed `:versao` on any member must surface its own
7958        // diagnostic (which names *which* member to fix) before any
7959        // `:contratos` membership lookup raises `ContratoMemberMissing`.
7960        // The `:contratos` gate runs after `validate_membros`, so this
7961        // is structurally guaranteed — pin it explicitly so a future
7962        // refactor that reorders the gates surfaces here.
7963        let mut s = three_member_spec();
7964        s.membros[1].versao = "^^0.1".into();
7965        // Add a contrato whose `:para` doesn't exist — would normally
7966        // raise ContratoMemberMissing at the membership lookup, but
7967        // the membros gate must fire first.
7968        s.contratos
7969            .push(contract_http("cart", "phantom", "/never-reached"));
7970        let err = s.validate().unwrap_err();
7971        assert!(
7972            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7973            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7974        );
7975    }
7976
7977    #[test]
7978    fn membros_validation_runs_before_contratos_membership_check() {
7979        // If `:membros` carries a duplicate, the membership-collapse
7980        // would silently accept a `:contratos :para "phantom"` so long
7981        // as some entry hashes to "phantom". Pinning order: the
7982        // duplicate-membros error fires first, regardless of whether
7983        // contratos reference real members.
7984        let mut s = three_member_spec();
7985        s.membros = vec![
7986            membro("cart", "^0.1"),
7987            membro("cart", "^0.2"),
7988            membro("catalog", "^0.1"),
7989            membro("payment", "^0.1"),
7990        ];
7991        let err = s.validate().unwrap_err();
7992        assert!(
7993            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7994            "got {err:?}"
7995        );
7996    }
7997
7998    #[test]
7999    fn distinct_membros_validate() {
8000        // Pin the happy-path: every `:membros` entry has a non-empty
8001        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8002        // The fixture already satisfies this; this test makes the
8003        // invariant explicit so a future refactor of the fixture can't
8004        // silently break the guarantee.
8005        three_member_spec().validate().unwrap();
8006    }
8007
8008    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8009
8010    #[test]
8011    fn rejects_membro_caixa_with_uppercase() {
8012        // The canonical "I copied the Servico's display name verbatim"
8013        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8014        // but author tools often round-trip a TitleCase or CamelCase
8015        // identifier from an ADR or a sketch. Pin the diagnostic names
8016        // the offending name and suggests the lower-cased fix in one
8017        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8018        // gate's shape (c7d05ec).
8019        let mut s = three_member_spec();
8020        s.membros[1].caixa = "Cart".into();
8021        let err = s.validate().unwrap_err();
8022        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8023            panic!("expected MembroCaixaInvalid, got other variant");
8024        };
8025        assert_eq!(caixa, "Cart");
8026        assert!(
8027            reason.contains("uppercase"),
8028            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8029        );
8030        assert!(
8031            reason.contains("\"cart\""),
8032            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8033        );
8034    }
8035
8036    #[test]
8037    fn rejects_membro_caixa_with_underscore() {
8038        // The canonical "I'm thinking of a Python module / Postgres
8039        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8040        // label schema. K8s rejects `metadata.name: my_cart` at admission
8041        // time with an opaque `field is invalid` (no source-citing
8042        // diagnostic). The gate moves it to caixa-build time.
8043        let mut s = three_member_spec();
8044        s.membros[0].caixa = "my_cart".into();
8045        let err = s.validate().unwrap_err();
8046        assert!(
8047            matches!(
8048                err,
8049                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8050                    if caixa == "my_cart" && reason.contains('_')
8051            ),
8052            "got {err:?}"
8053        );
8054    }
8055
8056    #[test]
8057    fn rejects_membro_caixa_with_dot() {
8058        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8059        // subdomain — even though K8s `metadata.name` itself accepts
8060        // dots (DNS-1123 subdomain rule), this string also lands as a
8061        // K8s Service name (DNS-1035 label — no dots) and as a label
8062        // value on identity-based Cilium selectors. The strictest floor
8063        // among the use sites wins. The "I want to namespace my member
8064        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8065        let mut s = three_member_spec();
8066        s.membros[2].caixa = "team.cart".into();
8067        let err = s.validate().unwrap_err();
8068        assert!(
8069            matches!(
8070                err,
8071                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8072                    if caixa == "team.cart" && reason.contains('.')
8073            ),
8074            "got {err:?}"
8075        );
8076    }
8077
8078    #[test]
8079    fn rejects_membro_caixa_with_leading_hyphen() {
8080        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8081        // with an alphanumeric. The K8s apiserver rejects `-cart`
8082        // outright; the renderer would emit a `metadata.name: "-cart"`
8083        // that fails admission far from the source caixa.lisp.
8084        let mut s = three_member_spec();
8085        s.membros[0].caixa = "-cart".into();
8086        let err = s.validate().unwrap_err();
8087        assert!(
8088            matches!(
8089                err,
8090                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8091                    if caixa == "-cart" && reason.contains("start and end")
8092            ),
8093            "got {err:?}"
8094        );
8095    }
8096
8097    #[test]
8098    fn rejects_membro_caixa_with_trailing_hyphen() {
8099        // The symmetric arm of the boundary rule. Pin separately so
8100        // both ends of the label are covered against a future relaxation
8101        // that only checks one boundary.
8102        let mut s = three_member_spec();
8103        s.membros[1].caixa = "cart-".into();
8104        let err = s.validate().unwrap_err();
8105        assert!(
8106            matches!(
8107                err,
8108                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8109                    if caixa == "cart-"
8110            ),
8111            "got {err:?}"
8112        );
8113    }
8114
8115    #[test]
8116    fn rejects_membro_caixa_with_unicode() {
8117        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8118        // (`xn--…`) by the author before it reaches K8s. The byte-by-
8119        // byte ASCII validity check rejects multi-byte UTF-8 sequences
8120        // by the first byte that fails the `[a-z0-9-]` predicate.
8121        let mut s = three_member_spec();
8122        s.membros[2].caixa = "café".into();
8123        let err = s.validate().unwrap_err();
8124        assert!(
8125            matches!(
8126                err,
8127                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8128                    if caixa == "café"
8129            ),
8130            "got {err:?}"
8131        );
8132    }
8133
8134    #[test]
8135    fn rejects_membro_caixa_with_whitespace() {
8136        // Whitespace is the canonical "I pasted from a sketch / doc"
8137        // footgun. The apiserver rejects every `metadata.name` value
8138        // carrying whitespace; pin the gate fires at the right boundary.
8139        let mut s = three_member_spec();
8140        s.membros[0].caixa = "my cart".into();
8141        let err = s.validate().unwrap_err();
8142        assert!(
8143            matches!(
8144                err,
8145                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8146                    if caixa == "my cart"
8147            ),
8148            "got {err:?}"
8149        );
8150    }
8151
8152    #[test]
8153    fn rejects_membro_caixa_too_long() {
8154        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8155        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8156        // exactly. The gate's reason names both the cap and the actual
8157        // length so the author can shorten in one edit.
8158        let mut s = three_member_spec();
8159        let too_long = "a".repeat(64);
8160        s.membros[1].caixa = too_long.clone();
8161        let err = s.validate().unwrap_err();
8162        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8163            panic!("expected MembroCaixaInvalid");
8164        };
8165        assert_eq!(caixa, too_long);
8166        assert!(
8167            reason.contains("63") && reason.contains("64"),
8168            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8169        );
8170    }
8171
8172    #[test]
8173    fn membro_caixa_max_length_validates() {
8174        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8175        // so a future tightening (e.g. dropping to 62) surfaces here as
8176        // a regression, mirroring `entrada_host_max_length_validates`
8177        // (c7d05ec).
8178        let mut s = three_member_spec();
8179        s.membros[2].caixa = "a".repeat(63);
8180        s.entrada.as_mut().unwrap().para = "a".repeat(63);
8181        // remove contratos referencing the renamed member; they'd
8182        // raise ContratoMemberMissing otherwise
8183        s.contratos
8184            .retain(|c| c.de != "payment" && c.para != "payment");
8185        s.validate().unwrap();
8186    }
8187
8188    #[test]
8189    fn accepts_canonical_membro_caixa_forms() {
8190        // The DNS-1123 label shapes a caixa author is realistically
8191        // going to write: single-word lowercase, hyphen-joined, ending
8192        // in a digit-suffixed version (`cart-v2`), starting with a
8193        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8194        // DNS-1035 which requires a letter at position 0), single-
8195        // character (`a` — boundary). Pin every leg so a future
8196        // tightening that bans (e.g.) digit-start identifiers surfaces
8197        // here.
8198        for form in [
8199            "checkout",
8200            "cart",
8201            "cart-v2",
8202            "a",
8203            "c0",
8204            "3rd-party-shim",
8205            "x-1-2-3-4",
8206        ] {
8207            let mut s = three_member_spec();
8208            // Renaming a member also requires updating downstream refs;
8209            // drop everything else and rebuild a minimal spec around
8210            // just the one renamed member.
8211            s.membros = vec![membro(form, "^0.1")];
8212            s.contratos = vec![];
8213            s.entrada = None;
8214            s.validate()
8215                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8216        }
8217    }
8218
8219    #[test]
8220    fn membro_caixa_empty_takes_precedence_over_invalid() {
8221        // Order pin: the existing `MembroCaixaEmpty` diagnostic
8222        // (which doesn't try to parse) fires before the new
8223        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8224        // `:caixa` keeps its narrower error message — the new gate
8225        // would also reject `""`, but the empty-string arm is the more
8226        // self-locating diagnostic for the author. Mirrors the
8227        // `entrada_host_empty_takes_precedence_over_invalid` pin
8228        // (c7d05ec).
8229        let mut s = three_member_spec();
8230        s.membros[1].caixa = String::new();
8231        let err = s.validate().unwrap_err();
8232        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8233    }
8234
8235    #[test]
8236    fn membro_caixa_invalid_fires_before_versao_check() {
8237        // Order pin: an invalid-shape `:caixa` surfaces *its own*
8238        // diagnostic (which names the offending caixa name), even when
8239        // the same entry's `:versao` is also empty/invalid. The shape
8240        // gate runs first because the diagnostic is more self-locating —
8241        // an empty/invalid `:versao` on an invalid-shape caixa name is
8242        // a downstream-fix-after-the-caixa-rename concern.
8243        let mut s = three_member_spec();
8244        s.membros[1].caixa = "Cart".into();
8245        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8246        let err = s.validate().unwrap_err();
8247        assert!(
8248            matches!(
8249                err,
8250                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8251            ),
8252            "got {err:?}"
8253        );
8254    }
8255
8256    #[test]
8257    fn membro_caixa_invalid_fires_before_duplicate_check() {
8258        // Order pin: a malformed-shape `:caixa` on an earlier entry
8259        // surfaces *its own* diagnostic, even when a later entry would
8260        // otherwise collapse onto a duplicate name. The per-entry shape
8261        // gate runs inline before the duplicate-key insert, parallel
8262        // to `membro_versao_invalid_fires_before_duplicate_check`.
8263        let mut s = three_member_spec();
8264        s.membros[0].caixa = "Catalog".into();
8265        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8266        let err = s.validate().unwrap_err();
8267        assert!(
8268            matches!(
8269                err,
8270                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8271            ),
8272            "got {err:?}"
8273        );
8274    }
8275
8276    #[test]
8277    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8278        // The diagnostic-shape pin: the error names the offending
8279        // `:caixa` value verbatim so the author can grep their
8280        // caixa.lisp without re-running the build, and carries a
8281        // non-empty `reason` naming the specific violation. Same
8282        // shape every typed-shape gate enshrines (c7d05ec's
8283        // `entrada_host_diagnostic_carries_offending_host`,
8284        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8285        let mut s = three_member_spec();
8286        s.membros[2].caixa = "BAD_NAME".into();
8287        let err = s.validate().unwrap_err();
8288        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8289            panic!("expected MembroCaixaInvalid");
8290        };
8291        assert_eq!(caixa, "BAD_NAME");
8292        assert!(
8293            !reason.is_empty(),
8294            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8295        );
8296    }
8297
8298    #[test]
8299    fn rejects_contrato_with_unknown_de() {
8300        let mut s = three_member_spec();
8301        s.contratos.push(contract_http("phantom", "catalog", "/x"));
8302        let err = s.validate().unwrap_err();
8303        assert!(
8304            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8305        );
8306    }
8307
8308    #[test]
8309    fn rejects_contrato_with_unknown_para() {
8310        let mut s = three_member_spec();
8311        s.contratos.push(contract_http("cart", "phantom", "/x"));
8312        let err = s.validate().unwrap_err();
8313        assert!(
8314            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8315        );
8316    }
8317
8318    #[test]
8319    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8320        // The read-path pin: the phantom-`:de` refusal arm's
8321        // `ContratoMemberMissing.caixa` carrier must be observed through
8322        // the lifted [`WitContract::source`] accessor, not the raw
8323        // `.de.clone()` field-access `String`-carry. Peer of the sibling
8324        // per-`:contratos` self-loop arm's `.source().to_string()` /
8325        // `.world_ref().to_string()` `String`-carry sites the earlier
8326        // convergence lifted onto the same accessor pair. A future
8327        // silent detour that reintroduced the raw `.de.clone()` at the
8328        // wrap envelope while the shape-gate and membership lookup
8329        // routed through the accessor would surface here as a byte-equal
8330        // miss between the fired diagnostic's `caixa:` field and the
8331        // offending edge's `.source()` — pinning the accessor as the
8332        // sole read path across the phantom-name refusal arm's arg +
8333        // wrap-envelope emit surface.
8334        let mut s = three_member_spec();
8335        let phantom = contract_http("phantom", "catalog", "/x");
8336        s.contratos.push(phantom.clone());
8337        let err = s.validate().unwrap_err();
8338        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8339            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8340        };
8341        assert_eq!(
8342            caixa,
8343            phantom.source(),
8344            "ContratoMemberMissing.caixa on the phantom-:de arm must \
8345             byte-equal WitContract::source — the wrap envelope must \
8346             route through the lifted accessor rather than the raw \
8347             .de.clone() field-access String-carry"
8348        );
8349    }
8350
8351    #[test]
8352    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8353        // The symmetric read-path pin on the `:para` phantom-name
8354        // refusal arm — same shape as the sibling `:de` pin above but
8355        // on the callee-Servico axis. Pins the wrap envelope's
8356        // `caixa:` field is observed through the lifted
8357        // [`WitContract::destination`] accessor, not the raw
8358        // `.para.clone()` field-access `String`-carry.
8359        let mut s = three_member_spec();
8360        let phantom = contract_http("cart", "phantom", "/x");
8361        s.contratos.push(phantom.clone());
8362        let err = s.validate().unwrap_err();
8363        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8364            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8365        };
8366        assert_eq!(
8367            caixa,
8368            phantom.destination(),
8369            "ContratoMemberMissing.caixa on the phantom-:para arm must \
8370             byte-equal WitContract::destination — the wrap envelope \
8371             must route through the lifted accessor rather than the raw \
8372             .para.clone() field-access String-carry"
8373        );
8374    }
8375
8376    #[test]
8377    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8378        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8379        // refusal arm — the `validate_contrato_caixa` arg must be
8380        // observed through the lifted [`WitContract::source`] accessor,
8381        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8382        // value routes through the shared
8383        // [`crate::render::require_valid_dns_1123_label`] floor with the
8384        // accessor-projected value; the fired
8385        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8386        // the offending edge's `.source()`, pinning that the arg + the
8387        // downstream `caixa: caixa.to_string()` wrap route through the
8388        // same accessor's read path.
8389        let mut s = three_member_spec();
8390        let malformed = contract_http("BAD_NAME", "catalog", "/x");
8391        s.contratos.push(malformed.clone());
8392        let err = s.validate().unwrap_err();
8393        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8394            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8395        };
8396        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8397        assert_eq!(
8398            caixa,
8399            malformed.source(),
8400            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8401             byte-equal WitContract::source — the shape-gate arg + wrap \
8402             envelope must route through the lifted accessor rather \
8403             than the raw &c.de &String-borrow"
8404        );
8405    }
8406
8407    #[test]
8408    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8409        // Symmetric arm to the sibling `:de` malformed-shape pin above,
8410        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8411        // route through the lifted [`WitContract::destination`]
8412        // accessor. `:para` runs after the `:de` shape gate in the
8413        // canonical edge-direction order, so the `:de` value must be
8414        // well-shaped for the `:para` gate to fire — the `cart` :de is
8415        // canonical.
8416        let mut s = three_member_spec();
8417        let malformed = contract_http("cart", "BAD_NAME", "/x");
8418        s.contratos.push(malformed.clone());
8419        let err = s.validate().unwrap_err();
8420        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8421            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8422        };
8423        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8424        assert_eq!(
8425            caixa,
8426            malformed.destination(),
8427            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8428             byte-equal WitContract::destination — the shape-gate arg + \
8429             wrap envelope must route through the lifted accessor \
8430             rather than the raw &c.para &String-borrow"
8431        );
8432    }
8433
8434    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8435
8436    #[test]
8437    fn rejects_contrato_de_empty() {
8438        // `:de ""` previously fell through to `ContratoMemberMissing`
8439        // (with `caixa: ""`) because the validated `:membros :caixa`
8440        // set never contains the empty string. The narrower
8441        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8442        // the offending slot.
8443        let mut s = three_member_spec();
8444        s.contratos.push(contract_http("", "catalog", "/x"));
8445        let err = s.validate().unwrap_err();
8446        assert_eq!(
8447            err,
8448            AplicacaoError::ContratoCaixaEmpty {
8449                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8450            },
8451            "got {err:?}"
8452        );
8453    }
8454
8455    #[test]
8456    fn rejects_contrato_para_empty() {
8457        // Symmetric arm to `:de ""` — `:para ""` previously fell
8458        // through to `ContratoMemberMissing { caixa: "" }`.
8459        let mut s = three_member_spec();
8460        s.contratos.push(contract_http("cart", "", "/x"));
8461        let err = s.validate().unwrap_err();
8462        assert_eq!(
8463            err,
8464            AplicacaoError::ContratoCaixaEmpty {
8465                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8466            },
8467            "got {err:?}"
8468        );
8469    }
8470
8471    #[test]
8472    fn rejects_contrato_de_with_uppercase() {
8473        // The canonical "I copied the Servico's TitleCase display
8474        // name from an ADR" typo. Until this gate landed `:de "Cart"`
8475        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8476        // as "this caixa isn't in `:membros`" when the root cause is
8477        // "this `:de` value's shape can never legitimately match a
8478        // validated member (DNS-1123 labels are lowercase)". The
8479        // narrower diagnostic names the offending slot, the value
8480        // verbatim, and the parser-shaped reason.
8481        let mut s = three_member_spec();
8482        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8483        let err = s.validate().unwrap_err();
8484        let AplicacaoError::ContratoCaixaInvalid {
8485            slot,
8486            caixa,
8487            reason,
8488        } = err
8489        else {
8490            panic!("expected ContratoCaixaInvalid, got other variant");
8491        };
8492        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8493        assert_eq!(caixa, "Cart");
8494        assert!(
8495            reason.contains("uppercase"),
8496            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8497        );
8498    }
8499
8500    #[test]
8501    fn rejects_contrato_para_with_underscore() {
8502        // The canonical "I'm thinking of a Python module" leak —
8503        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8504        // Pin the `:para` axis surfaces the same diagnostic shape as
8505        // the `:de` axis on the underscore violation.
8506        let mut s = three_member_spec();
8507        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8508        let err = s.validate().unwrap_err();
8509        assert!(
8510            matches!(
8511                err,
8512                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8513                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8514            ),
8515            "got {err:?}"
8516        );
8517    }
8518
8519    #[test]
8520    fn rejects_contrato_de_with_dot() {
8521        // A `:contratos :de` value is a single DNS-1123 *label*, not
8522        // a subdomain — mirroring the `:membros :caixa` floor. The
8523        // strictest floor among the use sites wins.
8524        let mut s = three_member_spec();
8525        s.contratos
8526            .push(contract_http("team.cart", "catalog", "/x"));
8527        let err = s.validate().unwrap_err();
8528        assert!(
8529            matches!(
8530                err,
8531                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8532                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8533            ),
8534            "got {err:?}"
8535        );
8536    }
8537
8538    #[test]
8539    fn rejects_contrato_para_with_unicode() {
8540        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8541        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8542        // validity check rejects multi-byte UTF-8 by the first
8543        // non-`[a-z0-9-]` byte.
8544        let mut s = three_member_spec();
8545        s.contratos.push(contract_http("cart", "café", "/x"));
8546        let err = s.validate().unwrap_err();
8547        assert!(
8548            matches!(
8549                err,
8550                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8551                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8552            ),
8553            "got {err:?}"
8554        );
8555    }
8556
8557    #[test]
8558    fn rejects_contrato_de_with_leading_hyphen() {
8559        // DNS-1123 boundary rule: labels must start and end with an
8560        // alphanumeric. K8s rejects `-cart` outright; the narrower
8561        // shape diagnostic now names the violation at caixa-build
8562        // time rather than the misframed membership-lookup arm.
8563        let mut s = three_member_spec();
8564        s.contratos.push(contract_http("-cart", "catalog", "/x"));
8565        let err = s.validate().unwrap_err();
8566        assert!(
8567            matches!(
8568                err,
8569                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8570                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8571            ),
8572            "got {err:?}"
8573        );
8574    }
8575
8576    #[test]
8577    fn contrato_de_empty_takes_precedence_over_invalid() {
8578        // Order pin: the `ContratoCaixaEmpty` arm fires before the
8579        // `ContratoCaixaInvalid` parse-side arm — same empty-first
8580        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8581        // / `validate_entrada_host` already establish on their peer
8582        // name axes. The empty string is a structurally distinct
8583        // authoring footgun (the author left the field blank, vs.
8584        // typed a malformed value), so it gets its own diagnostic.
8585        let mut s = three_member_spec();
8586        s.contratos.push(contract_http("", "catalog", "/x"));
8587        let err = s.validate().unwrap_err();
8588        assert_eq!(
8589            err,
8590            AplicacaoError::ContratoCaixaEmpty {
8591                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8592            }
8593        );
8594    }
8595
8596    #[test]
8597    fn contrato_de_shape_fires_before_para_shape() {
8598        // Per-axis order pin: within one `:contratos` entry, the `:de`
8599        // shape gate fires before the `:para` shape gate — same
8600        // edge-direction order the existing `ContratoMemberMissing` /
8601        // `ContratoSelfLoop` / target-dispatch checks use, so the
8602        // diagnostic for a contract with both `:de` and `:para`
8603        // malformed is stable. Authors fixing the surfaced `:de`
8604        // first will see `:para`'s diagnostic on re-run.
8605        let mut s = three_member_spec();
8606        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8607        let err = s.validate().unwrap_err();
8608        assert!(
8609            matches!(
8610                err,
8611                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8612                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8613            ),
8614            "got {err:?}"
8615        );
8616    }
8617
8618    #[test]
8619    fn contrato_shape_fires_before_membership_lookup() {
8620        // The load-bearing pin: an invalid-shape `:de` surfaces its
8621        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8622        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8623        // an invalid-shape `:de` could never legitimately match any
8624        // member — the prior `ContratoMemberMissing` diagnostic was
8625        // a structural impossibility framed as a graph-membership
8626        // failure. The shape gate now routes every such input through
8627        // the narrower self-locating diagnostic.
8628        let mut s = three_member_spec();
8629        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8630        let err = s.validate().unwrap_err();
8631        assert!(
8632            matches!(
8633                err,
8634                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8635            ),
8636            "got {err:?}"
8637        );
8638        // And the symmetric case: an invalid-shape `:para` surfaces
8639        // its own diagnostic too, even when `:de` is well-shaped.
8640        let mut s = three_member_spec();
8641        s.contratos.push(contract_http("cart", "Catalog", "/x"));
8642        let err = s.validate().unwrap_err();
8643        assert!(
8644            matches!(
8645                err,
8646                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8647            ),
8648            "got {err:?}"
8649        );
8650    }
8651
8652    #[test]
8653    fn contrato_shape_fires_before_self_edge_check() {
8654        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8655        // bugs: the shape violation (uppercase) and the self-edge
8656        // violation. The narrower per-axis shape diagnostic surfaces
8657        // first because fixing the shape may reveal that the author
8658        // also meant to point `:para` at a different member — the
8659        // self-edge framing is only useful once both endpoints have
8660        // valid shape.
8661        let mut s = three_member_spec();
8662        s.contratos.push(contract_http("Cart", "Cart", "/x"));
8663        let err = s.validate().unwrap_err();
8664        assert!(
8665            matches!(
8666                err,
8667                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8668                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8669            ),
8670            "got {err:?}"
8671        );
8672    }
8673
8674    #[test]
8675    fn contrato_well_shaped_phantom_still_raises_member_missing() {
8676        // Strict-improvement pin: a well-shaped `:de` that simply
8677        // isn't in `:membros` (a phantom reference — author meant
8678        // to add the member but didn't, or renamed and missed an
8679        // update) still surfaces `ContratoMemberMissing`, unchanged.
8680        // The shape gate only intercepts inputs that could never
8681        // legitimately match a validated member; legitimately-shaped
8682        // phantom references remain on the graph-membership axis.
8683        let mut s = three_member_spec();
8684        s.contratos
8685            .push(contract_http("phantom-shim", "catalog", "/x"));
8686        let err = s.validate().unwrap_err();
8687        assert!(
8688            matches!(
8689                err,
8690                AplicacaoError::ContratoMemberMissing { ref caixa }
8691                    if caixa == "phantom-shim"
8692            ),
8693            "got {err:?}"
8694        );
8695    }
8696
8697    #[test]
8698    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8699        // The diagnostic-shape pin: the error names the offending
8700        // slot (`:de` or `:para`) verbatim and the offending value
8701        // verbatim plus a non-empty parser-shaped reason, so the
8702        // author can grep their caixa.lisp for `:de "<name>"` /
8703        // `:para "<name>"` and fix it in one edit. Same diagnostic
8704        // shape as `MembroCaixaInvalid` (3f9d7a0) and
8705        // `PlacementClusterInvalid` (6c8c00b).
8706        let mut s = three_member_spec();
8707        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8708        let err = s.validate().unwrap_err();
8709        let AplicacaoError::ContratoCaixaInvalid {
8710            slot,
8711            caixa,
8712            reason,
8713        } = err
8714        else {
8715            panic!("expected ContratoCaixaInvalid, got {err:?}");
8716        };
8717        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8718        assert_eq!(caixa, "BAD_NAME");
8719        assert!(
8720            !reason.is_empty(),
8721            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8722        );
8723    }
8724
8725    #[test]
8726    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8727        // Scalar-value pin: the two author-facing kebab-case labels the
8728        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8729        // admits on the `:contratos` per-entry endpoint-shape axis,
8730        // one arm per typed sub-slot. Mirrors the peer scalar-value
8731        // pin the sibling top-level M2 / M3 / Supervisor
8732        // author-facing-label consts carry
8733        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8734        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8735        // slot itself), so every altitude of the typed-slot algebra
8736        // shares the same "one canonical byte-string per arm"
8737        // discipline. A future rebrand (`:de` → `:from` matching the
8738        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8739        // sibling, `:para` → `:to` matching the same, or
8740        // `:de`/`:para` → `:source`/`:target` matching the WIT
8741        // world's `import`/`export` half-vocabulary) lands as an
8742        // edit to exactly one const, and every consumer that reaches
8743        // for the label picks it up at build time rather than at
8744        // runtime as a downstream `ContratoCaixaEmpty` /
8745        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8746        // diagnostic mismatch far from the rename's commit.
8747        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8748        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8749    }
8750
8751    #[test]
8752    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8753        // Production-through-const pin: the two per-axis labels the
8754        // per-`:contratos` entry endpoint-shape gate at
8755        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8756        // argument to [`validate_contrato_caixa`] route through the
8757        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8758        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8759        // future rebrand that reaches the const but not the gate (or
8760        // vice versa) surfaces here at build time rather than at
8761        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8762        // `slot: <stale-kebab-case>` diagnostic far from the rename's
8763        // commit. Mirror of the peer
8764        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8765        // pin (882f498) on the sibling M3 top-level slot axis.
8766        let mut s = three_member_spec();
8767        s.contratos.push(contract_http("", "catalog", "/x"));
8768        assert_eq!(
8769            s.validate().unwrap_err(),
8770            AplicacaoError::ContratoCaixaEmpty {
8771                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8772            }
8773        );
8774        let mut s = three_member_spec();
8775        s.contratos.push(contract_http("cart", "", "/x"));
8776        assert_eq!(
8777            s.validate().unwrap_err(),
8778            AplicacaoError::ContratoCaixaEmpty {
8779                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8780            }
8781        );
8782    }
8783
8784    #[test]
8785    fn accepts_canonical_contrato_caixa_forms() {
8786        // The DNS-1123 label shapes a caixa author is realistically
8787        // going to write on a `:contratos :de` / `:para`. Pin every
8788        // leg so a future tightening that bans (e.g.) digit-start
8789        // identifiers surfaces here, mirroring
8790        // `accepts_canonical_membro_caixa_forms` on the peer name
8791        // axis.
8792        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8793            let mut s = three_member_spec();
8794            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8795            s.contratos = vec![contract_http("checkout", form, "/x")];
8796            s.entrada = None;
8797            s.validate().unwrap_or_else(|e| {
8798                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8799            });
8800
8801            let mut s = three_member_spec();
8802            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8803            s.contratos = vec![contract_http(form, "catalog", "/x")];
8804            s.entrada = None;
8805            s.validate().unwrap_or_else(|e| {
8806                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8807            });
8808        }
8809    }
8810
8811    #[test]
8812    fn rejects_empty_wit() {
8813        let mut s = three_member_spec();
8814        s.contratos.push(WitContract {
8815            de: "cart".into(),
8816            para: "catalog".into(),
8817            wit: "".into(),
8818            endpoint: None,
8819            subject: None,
8820            slot: None,
8821        });
8822        let err = s.validate().unwrap_err();
8823        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8824    }
8825
8826    #[test]
8827    fn rejects_entrada_to_unknown_member() {
8828        let mut s = three_member_spec();
8829        s.entrada.as_mut().unwrap().para = "phantom".into();
8830        assert!(matches!(
8831            s.validate().unwrap_err(),
8832            AplicacaoError::EntradaMemberMissing { .. }
8833        ));
8834    }
8835
8836    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8837
8838    #[test]
8839    fn rejects_entrada_para_empty() {
8840        // `:para ""` previously fell through to
8841        // `EntradaMemberMissing { para: "" }` because the validated
8842        // `:membros :caixa` set never contains the empty string. The
8843        // narrower `EntradaParaEmpty` diagnostic now names the
8844        // offending slot directly — same empty-first cascade
8845        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8846        // `ContratoCaixaEmpty` establish on the peer name axes.
8847        let mut s = three_member_spec();
8848        s.entrada.as_mut().unwrap().para = String::new();
8849        let err = s.validate().unwrap_err();
8850        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8851    }
8852
8853    #[test]
8854    fn rejects_entrada_para_with_uppercase() {
8855        // The canonical "I copied the Servico's TitleCase display
8856        // name from an ADR" typo. Until this gate landed `:para "Cart"`
8857        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8858        // as "this caixa isn't in `:membros`" when the root cause is
8859        // "this `:para` value's shape can never legitimately match a
8860        // validated member (DNS-1123 labels are lowercase)". The
8861        // narrower diagnostic names the value verbatim plus the
8862        // parser-shaped reason.
8863        let mut s = three_member_spec();
8864        s.entrada.as_mut().unwrap().para = "Cart".into();
8865        let err = s.validate().unwrap_err();
8866        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8867            panic!("expected EntradaParaInvalid, got other variant");
8868        };
8869        assert_eq!(para, "Cart");
8870        assert!(
8871            reason.contains("uppercase"),
8872            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8873        );
8874    }
8875
8876    #[test]
8877    fn rejects_entrada_para_with_underscore() {
8878        // The canonical "I'm thinking of a Python module" leak —
8879        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8880        let mut s = three_member_spec();
8881        s.entrada.as_mut().unwrap().para = "my_cart".into();
8882        let err = s.validate().unwrap_err();
8883        assert!(
8884            matches!(
8885                err,
8886                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8887                    if para == "my_cart" && reason.contains('_')
8888            ),
8889            "got {err:?}"
8890        );
8891    }
8892
8893    #[test]
8894    fn rejects_entrada_para_with_dot() {
8895        // An `:entrada :para` value is a single DNS-1123 *label*, not
8896        // a subdomain — mirroring the `:membros :caixa` floor. The
8897        // strictest floor among the use sites wins.
8898        let mut s = three_member_spec();
8899        s.entrada.as_mut().unwrap().para = "team.cart".into();
8900        let err = s.validate().unwrap_err();
8901        assert!(
8902            matches!(
8903                err,
8904                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8905                    if para == "team.cart" && reason.contains('.')
8906            ),
8907            "got {err:?}"
8908        );
8909    }
8910
8911    #[test]
8912    fn rejects_entrada_para_with_unicode() {
8913        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8914        // (`xn--…`) before it reaches K8s.
8915        let mut s = three_member_spec();
8916        s.entrada.as_mut().unwrap().para = "café".into();
8917        let err = s.validate().unwrap_err();
8918        assert!(
8919            matches!(
8920                err,
8921                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8922            ),
8923            "got {err:?}"
8924        );
8925    }
8926
8927    #[test]
8928    fn rejects_entrada_para_with_leading_hyphen() {
8929        // DNS-1123 boundary rule: labels must start and end with an
8930        // alphanumeric. K8s rejects `-cart` outright.
8931        let mut s = three_member_spec();
8932        s.entrada.as_mut().unwrap().para = "-cart".into();
8933        let err = s.validate().unwrap_err();
8934        assert!(
8935            matches!(
8936                err,
8937                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8938                    if para == "-cart" && reason.contains("start and end")
8939            ),
8940            "got {err:?}"
8941        );
8942    }
8943
8944    #[test]
8945    fn rejects_entrada_para_with_trailing_hyphen() {
8946        // Symmetric boundary arm.
8947        let mut s = three_member_spec();
8948        s.entrada.as_mut().unwrap().para = "cart-".into();
8949        let err = s.validate().unwrap_err();
8950        assert!(
8951            matches!(
8952                err,
8953                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8954                    if para == "cart-" && reason.contains("start and end")
8955            ),
8956            "got {err:?}"
8957        );
8958    }
8959
8960    #[test]
8961    fn rejects_entrada_para_too_long() {
8962        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8963        // bytes per label. K8s rejects longer names at admission on
8964        // every `metadata.name` axis.
8965        let mut s = three_member_spec();
8966        s.entrada.as_mut().unwrap().para = "a".repeat(64);
8967        let err = s.validate().unwrap_err();
8968        assert!(
8969            matches!(
8970                err,
8971                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8972                    if para.len() == 64 && reason.contains("max length")
8973            ),
8974            "got {err:?}"
8975        );
8976    }
8977
8978    #[test]
8979    fn entrada_para_empty_takes_precedence_over_invalid() {
8980        // Order pin: the `EntradaParaEmpty` arm fires before the
8981        // `EntradaParaInvalid` parse-side arm — same empty-first
8982        // cascade `validate_membro_caixa` / `validate_placement_cluster`
8983        // / `validate_contrato_caixa` already establish.
8984        let mut s = three_member_spec();
8985        s.entrada.as_mut().unwrap().para = String::new();
8986        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8987    }
8988
8989    #[test]
8990    fn entrada_para_shape_fires_before_membership_lookup() {
8991        // The load-bearing pin: an invalid-shape `:para` surfaces its
8992        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8993        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8994        // an invalid-shape `:para` could never legitimately match any
8995        // member — the prior `EntradaMemberMissing` diagnostic framed
8996        // a structural impossibility as a graph-membership failure.
8997        let mut s = three_member_spec();
8998        s.entrada.as_mut().unwrap().para = "Cart".into();
8999        let err = s.validate().unwrap_err();
9000        assert!(
9001            matches!(
9002                err,
9003                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9004            ),
9005            "got {err:?}"
9006        );
9007    }
9008
9009    #[test]
9010    fn entrada_para_shape_fires_before_host_gate() {
9011        // Per-`:entrada` order pin: the `:para` shape gate fires
9012        // before the `:host` gate, mirroring the existing
9013        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9014        // ordering where the member-lookup arm preceded the host gate.
9015        // The shape gate slots ahead of that, so a malformed `:para`
9016        // surfaces its own diagnostic even when `:host` is also wrong.
9017        let mut s = three_member_spec();
9018        let e = s.entrada.as_mut().unwrap();
9019        e.para = "Cart".into();
9020        e.host = "BAD HOST".into();
9021        let err = s.validate().unwrap_err();
9022        assert!(
9023            matches!(
9024                err,
9025                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9026            ),
9027            "got {err:?}"
9028        );
9029    }
9030
9031    #[test]
9032    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9033        // Strict-improvement pin: a well-shaped `:para` that simply
9034        // isn't in `:membros` (a phantom reference — author meant to
9035        // add the member but didn't, or renamed and missed an
9036        // update) still surfaces `EntradaMemberMissing`, unchanged.
9037        // The shape gate only intercepts inputs that could never
9038        // legitimately match a validated member.
9039        let mut s = three_member_spec();
9040        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9041        let err = s.validate().unwrap_err();
9042        assert!(
9043            matches!(
9044                err,
9045                AplicacaoError::EntradaMemberMissing { ref para }
9046                    if para == "phantom-shim"
9047            ),
9048            "got {err:?}"
9049        );
9050    }
9051
9052    #[test]
9053    fn entrada_para_invalid_diagnostic_carries_offending_para() {
9054        // The diagnostic-shape pin: the error names the offending
9055        // `:para` value verbatim plus a non-empty parser-shaped
9056        // reason, so the author can grep their caixa.lisp for
9057        // `:para "<name>"` and fix it in one edit. Same diagnostic
9058        // shape as `MembroCaixaInvalid` (3f9d7a0),
9059        // `PlacementClusterInvalid` (6c8c00b), and
9060        // `ContratoCaixaInvalid` (8d5af6b).
9061        let mut s = three_member_spec();
9062        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9063        let err = s.validate().unwrap_err();
9064        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9065            panic!("expected EntradaParaInvalid, got {err:?}");
9066        };
9067        assert_eq!(para, "BAD_NAME");
9068        assert!(
9069            !reason.is_empty(),
9070            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9071        );
9072    }
9073
9074    #[test]
9075    fn accepts_canonical_entrada_para_forms() {
9076        // Positive-control sweep covering the DNS-1123 label shapes a
9077        // caixa author is realistically going to write on `:entrada
9078        // :para`. Pin every leg so a future tightening that bans
9079        // (e.g.) digit-start identifiers surfaces here, mirroring
9080        // `accepts_canonical_membro_caixa_forms` and
9081        // `accepts_canonical_contrato_caixa_forms` on the peer name
9082        // axes.
9083        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9084            let mut s = three_member_spec();
9085            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9086            s.contratos = vec![contract_http(form, "catalog", "/x")];
9087            s.entrada = Some(Entrada {
9088                host: "checkout.quero.cloud".into(),
9089                para: form.into(),
9090                paths: vec!["/api".into()],
9091                port: 8080,
9092            });
9093            s.validate().unwrap_or_else(|e| {
9094                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9095            });
9096        }
9097    }
9098
9099    #[test]
9100    fn rejects_replicated_without_clusters() {
9101        let mut s = three_member_spec();
9102        s.placement.clusters = vec![];
9103        assert!(matches!(
9104            s.validate().unwrap_err(),
9105            AplicacaoError::PlacementWithoutClusters { .. }
9106        ));
9107    }
9108
9109    #[test]
9110    fn rejects_sharded_without_key() {
9111        let mut s = three_member_spec();
9112        s.placement.estrategia = PlacementStrategy::Sharded;
9113        s.placement.shard_key = None;
9114        s.placement.clusters = vec!["rio".into()];
9115        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9116    }
9117
9118    #[test]
9119    fn sharded_with_key_validates() {
9120        let mut s = three_member_spec();
9121        s.placement.estrategia = PlacementStrategy::Sharded;
9122        s.placement.shard_key = Some("$tenantId".into());
9123        s.validate().unwrap();
9124    }
9125
9126    #[test]
9127    fn round_trip_via_json_preserves_shape() {
9128        let s = three_member_spec();
9129        let json = serde_json::to_string(&s.membros).unwrap();
9130        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9131        assert_eq!(back, s.membros);
9132
9133        let json = serde_json::to_string(&s.contratos).unwrap();
9134        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9135        assert_eq!(back, s.contratos);
9136
9137        let json = serde_json::to_string(&s.placement).unwrap();
9138        let back: Placement = serde_json::from_str(&json).unwrap();
9139        assert_eq!(back, s.placement);
9140
9141        let json = serde_json::to_string(&s.entrada).unwrap();
9142        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9143        assert_eq!(back, s.entrada);
9144    }
9145
9146    #[test]
9147    fn rate_limit_round_trip_seconds() {
9148        let policy = MeshPolicy {
9149            rate_limit: Some(RateLimit {
9150                rate: 100,
9151                window: Duration::from_secs(1),
9152            }),
9153            ..Default::default()
9154        };
9155        let json = serde_json::to_string(&policy).unwrap();
9156        assert!(json.contains("\"100/s\""));
9157        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9158        assert_eq!(back.rate_limit.unwrap().rate, 100);
9159        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9160    }
9161
9162    #[test]
9163    fn rate_limit_round_trip_minutes() {
9164        let policy = MeshPolicy {
9165            rate_limit: Some(RateLimit {
9166                rate: 5000,
9167                window: Duration::from_secs(60),
9168            }),
9169            ..Default::default()
9170        };
9171        let json = serde_json::to_string(&policy).unwrap();
9172        assert!(json.contains("\"5000/m\""));
9173    }
9174
9175    #[test]
9176    fn circuit_breaker_round_trip() {
9177        let policy = MeshPolicy {
9178            circuit_breaker: Some(CircuitBreaker {
9179                max_failures: 5,
9180                window: Duration::from_secs(60),
9181            }),
9182            ..Default::default()
9183        };
9184        let json = serde_json::to_string(&policy).unwrap();
9185        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9186        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9187        assert_eq!(
9188            back.circuit_breaker.unwrap().window,
9189            Duration::from_secs(60)
9190        );
9191    }
9192
9193    #[test]
9194    fn rejects_http_contrato_without_endpoint() {
9195        let mut s = three_member_spec();
9196        s.contratos.push(WitContract {
9197            de: "cart".into(),
9198            para: "catalog".into(),
9199            wit: "wasi:http/proxy".into(),
9200            endpoint: None,
9201            subject: None,
9202            slot: None,
9203        });
9204        let err = s.validate().unwrap_err();
9205        assert!(matches!(
9206            err,
9207            AplicacaoError::ContratoMissingTarget {
9208                expected: WitTarget::HTTP_FIELD_NAME,
9209                ..
9210            }
9211        ));
9212    }
9213
9214    #[test]
9215    fn rejects_http_contrato_with_subject() {
9216        let mut s = three_member_spec();
9217        s.contratos.push(WitContract {
9218            de: "cart".into(),
9219            para: "catalog".into(),
9220            wit: "wasi:http/proxy".into(),
9221            endpoint: Some("/x".into()),
9222            subject: Some("not.allowed.here".into()),
9223            slot: None,
9224        });
9225        let err = s.validate().unwrap_err();
9226        assert!(matches!(
9227            err,
9228            AplicacaoError::ContratoWrongTarget {
9229                expected: WitTarget::HTTP_FIELD_NAME,
9230                ..
9231            }
9232        ));
9233    }
9234
9235    #[test]
9236    fn rejects_pubsub_contrato_without_subject() {
9237        let mut s = three_member_spec();
9238        s.contratos.push(WitContract {
9239            de: "cart".into(),
9240            para: "catalog".into(),
9241            wit: "nats:pub-sub".into(),
9242            endpoint: None,
9243            subject: None,
9244            slot: None,
9245        });
9246        let err = s.validate().unwrap_err();
9247        assert!(matches!(
9248            err,
9249            AplicacaoError::ContratoMissingTarget {
9250                expected: WitTarget::PUBSUB_FIELD_NAME,
9251                ..
9252            }
9253        ));
9254    }
9255
9256    #[test]
9257    fn rejects_pubsub_contrato_with_endpoint() {
9258        let mut s = three_member_spec();
9259        s.contratos.push(WitContract {
9260            de: "cart".into(),
9261            para: "catalog".into(),
9262            wit: "kafka:topic".into(),
9263            endpoint: Some("/wrong".into()),
9264            subject: Some("topic.x".into()),
9265            slot: None,
9266        });
9267        let err = s.validate().unwrap_err();
9268        assert!(matches!(
9269            err,
9270            AplicacaoError::ContratoWrongTarget {
9271                expected: WitTarget::PUBSUB_FIELD_NAME,
9272                ..
9273            }
9274        ));
9275    }
9276
9277    #[test]
9278    fn rejects_store_contrato_without_slot() {
9279        let mut s = three_member_spec();
9280        s.contratos.push(WitContract {
9281            de: "cart".into(),
9282            para: "catalog".into(),
9283            wit: "wasi:keyvalue/store".into(),
9284            endpoint: None,
9285            subject: None,
9286            slot: None,
9287        });
9288        let err = s.validate().unwrap_err();
9289        assert!(matches!(
9290            err,
9291            AplicacaoError::ContratoMissingTarget {
9292                expected: WitTarget::STORE_FIELD_NAME,
9293                ..
9294            }
9295        ));
9296    }
9297
9298    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9299
9300    #[test]
9301    fn rejects_http_contrato_with_empty_endpoint() {
9302        // `Some("")` for an HTTP endpoint passes the presence check
9303        // (target() previously returned WitTarget::Http { endpoint: "" })
9304        // but renders as a `path: ""` Cilium L7 rule that matches no
9305        // traffic. Same value-shape footgun closed for :entrada :paths
9306        // entries (eb3456d).
9307        let mut s = three_member_spec();
9308        s.contratos.push(WitContract {
9309            de: "cart".into(),
9310            para: "catalog".into(),
9311            wit: "wasi:http/proxy".into(),
9312            endpoint: Some(String::new()),
9313            subject: None,
9314            slot: None,
9315        });
9316        let err = s.validate().unwrap_err();
9317        assert!(
9318            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9319                if de == "cart" && para == "catalog"),
9320            "got {err:?}"
9321        );
9322    }
9323
9324    #[test]
9325    fn rejects_http_contrato_with_relative_endpoint() {
9326        // Cilium L7 :path + Gateway API PathPrefix both require a
9327        // leading `/`. Same shape required of :entrada :paths
9328        // (eb3456d). Lifted into target() so every consumer of the
9329        // typed WitTarget view inherits the guarantee.
9330        let mut s = three_member_spec();
9331        s.contratos.push(WitContract {
9332            de: "cart".into(),
9333            para: "catalog".into(),
9334            wit: "wasi:http/proxy".into(),
9335            endpoint: Some("products/:id".into()),
9336            subject: None,
9337            slot: None,
9338        });
9339        let err = s.validate().unwrap_err();
9340        assert!(
9341            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9342                if endpoint == "products/:id"),
9343            "got {err:?}"
9344        );
9345    }
9346
9347    #[test]
9348    fn rejects_pubsub_contrato_with_empty_subject() {
9349        // NATS / Kafka publish without a subject is a no-op subscribe;
9350        // never the author's intent. Same empty-string rejection as
9351        // :membros :caixa, :placement :clusters entries, :entrada
9352        // :paths entries — every value carried by every typed slot is
9353        // value-shape-checked at validate().
9354        let mut s = three_member_spec();
9355        s.contratos.push(WitContract {
9356            de: "cart".into(),
9357            para: "catalog".into(),
9358            wit: "nats:pub-sub".into(),
9359            endpoint: None,
9360            subject: Some(String::new()),
9361            slot: None,
9362        });
9363        let err = s.validate().unwrap_err();
9364        assert!(
9365            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9366                if de == "cart" && para == "catalog"),
9367            "got {err:?}"
9368        );
9369    }
9370
9371    #[test]
9372    fn rejects_store_contrato_with_empty_slot() {
9373        // An empty slot template addresses the bucket root, defeating
9374        // the per-key isolation the slot exists for — a footgun on
9375        // `wasi:keyvalue/store` whose closest analog is the empty
9376        // shard-key rejected on :placement Sharded (c7c7799).
9377        let mut s = three_member_spec();
9378        s.contratos.push(WitContract {
9379            de: "cart".into(),
9380            para: "catalog".into(),
9381            wit: "wasi:keyvalue/store".into(),
9382            endpoint: None,
9383            subject: None,
9384            slot: Some(String::new()),
9385        });
9386        let err = s.validate().unwrap_err();
9387        assert!(
9388            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9389                if de == "cart" && para == "catalog"),
9390            "got {err:?}"
9391        );
9392    }
9393
9394    #[test]
9395    fn http_contrato_root_endpoint_validates() {
9396        // Pin the boundary case: a single-`/` endpoint is the catch-all
9397        // form the Gateway HTTPRoute renderer falls back to when
9398        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9399        // must remain a valid contrato endpoint too.
9400        let mut s = three_member_spec();
9401        s.contratos.push(contract_http("cart", "catalog", "/"));
9402        s.validate().unwrap();
9403    }
9404
9405    // ── :contratos :endpoint value-shape gate ────────────────────────────
9406    //
9407    // Mirrors the `:entrada :paths` value-shape suite on the peer
9408    // HTTP-path axis. Until this gate landed `WitContract::target()`
9409    // only refused the empty string + the missing-leading-`/` form
9410    // (c4213a4); a structurally invalid endpoint passed validate and
9411    // landed verbatim as a Cilium L7 `path:` rule
9412    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9413    // traffic or was rejected at apply time by Cilium policy admission.
9414    // Every authoring footgun the K8s Gateway API webhook / Cilium
9415    // policy validator would catch on admission now becomes a caixa-
9416    // build-time `ContratoEndpointInvalid` with the offending
9417    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9418    // shape as `EntradaPathInvalid` on the sibling axis; same shared
9419    // predicate (`crate::render::is_gateway_api_http_path`) ensures
9420    // drift between the two axes' rule enforcement is a build error
9421    // at the predicate.
9422
9423    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9424        // Fresh spec per call so the would-be-duplicate edge
9425        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9426        // `three_member_spec`'s pre-existing
9427        // `(cart, catalog, …, /products/:id)` entry — only the
9428        // endpoint payload differs.
9429        let mut s = three_member_spec();
9430        s.contratos.push(contract_http("cart", "catalog", ep));
9431        s.validate().unwrap_err()
9432    }
9433
9434    #[test]
9435    fn rejects_http_contrato_endpoint_with_query() {
9436        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9437        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9438        // rule the L7 matcher would never satisfy.
9439        let err = contrato_endpoint_err("/charge?token=X");
9440        assert!(
9441            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9442                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9443            "got {err:?}"
9444        );
9445    }
9446
9447    #[test]
9448    fn rejects_http_contrato_endpoint_with_fragment() {
9449        let err = contrato_endpoint_err("/charge#frag");
9450        assert!(
9451            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9452                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9453            "got {err:?}"
9454        );
9455    }
9456
9457    #[test]
9458    fn rejects_http_contrato_endpoint_with_whitespace() {
9459        let err = contrato_endpoint_err("/foo bar");
9460        assert!(
9461            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9462                if endpoint == "/foo bar" && reason.contains("whitespace")),
9463            "got {err:?}"
9464        );
9465    }
9466
9467    #[test]
9468    fn rejects_http_contrato_endpoint_with_control_char() {
9469        let err = contrato_endpoint_err("/api/\x01bar");
9470        assert!(
9471            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9472                if endpoint == "/api/\x01bar" && reason.contains("control character")),
9473            "got {err:?}"
9474        );
9475    }
9476
9477    #[test]
9478    fn rejects_http_contrato_endpoint_with_non_ascii() {
9479        let err = contrato_endpoint_err("/api/café");
9480        assert!(
9481            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9482                if endpoint == "/api/café" && reason.contains("non-ASCII")),
9483            "got {err:?}"
9484        );
9485    }
9486
9487    #[test]
9488    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9489        let err = contrato_endpoint_err("/api//cart");
9490        assert!(
9491            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9492                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9493            "got {err:?}"
9494        );
9495    }
9496
9497    #[test]
9498    fn rejects_http_contrato_endpoint_with_dot_segment() {
9499        let err = contrato_endpoint_err("/api/./cart");
9500        assert!(
9501            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9502                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9503            "got {err:?}"
9504        );
9505    }
9506
9507    #[test]
9508    fn rejects_http_contrato_endpoint_with_parent_segment() {
9509        // Path-traversal in a contrato endpoint is the canonical
9510        // "L7 rule that the workload's HTTP server's path-resolution
9511        // logic interprets differently than the policy enforcer"
9512        // footgun. Rejected outright at validate time.
9513        let err = contrato_endpoint_err("/api/../etc");
9514        assert!(
9515            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9516                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9517            "got {err:?}"
9518        );
9519    }
9520
9521    #[test]
9522    fn rejects_http_contrato_endpoint_too_long() {
9523        // 1025-byte endpoint — one over the Gateway API
9524        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9525        // path matcher has no inherent length limit but the policy
9526        // CR itself rides through the K8s apiserver, which enforces
9527        // ConfigMap-shaped limits; sharing the Gateway API cap is the
9528        // conservative floor.
9529        let big = format!("/api/{}", "a".repeat(1020));
9530        assert_eq!(big.len(), 1025);
9531        let err = contrato_endpoint_err(&big);
9532        assert!(
9533            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9534                if endpoint == &big && reason.contains("max length of 1024")),
9535            "got {err:?}"
9536        );
9537    }
9538
9539    #[test]
9540    fn http_contrato_endpoint_max_length_validates() {
9541        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9542        // in the cap surfaces here and at
9543        // `rejects_http_contrato_endpoint_too_long` simultaneously,
9544        // mirroring `entrada_path_max_length_validates` on the peer
9545        // axis.
9546        let big = format!("/api/{}", "a".repeat(1019));
9547        assert_eq!(big.len(), 1024);
9548        let mut s = three_member_spec();
9549        s.contratos.push(contract_http("cart", "catalog", &big));
9550        s.validate().unwrap();
9551    }
9552
9553    #[test]
9554    fn http_contrato_endpoint_accepts_canonical_forms() {
9555        // Positive-set sweep: every canonical HTTP-path shape the
9556        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9557        // plain paths, hidden-file-style `.config` segments distinct
9558        // from the `.` segment, digit-bearing segments, the canonical
9559        // route-template `:param` form, trailing-slash form,
9560        // percent-encoded segments, the `/foo..bar` interior-`..`-
9561        // substring forms that are NOT `..` segments) must remain a
9562        // valid contrato endpoint too. Drift between this list and
9563        // the entrada path positive sweep surfaces at the shared
9564        // `is_gateway_api_http_path` substrate-side suite — one
9565        // source of truth. Uses a fresh `(payment, catalog)` edge so
9566        // none of the swept endpoints collide with the pre-existing
9567        // `(cart, catalog, /products/:id)` / `(cart, payment,
9568        // /charge)` entries in `three_member_spec`.
9569        for ep in [
9570            "/",
9571            "/charge",
9572            "/v1/charge",
9573            "/api/.config",
9574            "/products/:id",
9575            "/api/cart/",
9576            "/api/caf%C3%A9",
9577            "/foo..bar",
9578            "/...",
9579        ] {
9580            let mut s = three_member_spec();
9581            s.contratos.push(contract_http("payment", "catalog", ep));
9582            s.validate()
9583                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9584        }
9585    }
9586
9587    #[test]
9588    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9589        // Ordering pin: `ContratoEndpointEmpty` is the more self-
9590        // locating diagnostic on `""` and must lead — the value-
9591        // shape gate is only reached after the empty-check fires.
9592        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9593        // on the peer axis.
9594        let mut s = three_member_spec();
9595        s.contratos.push(WitContract {
9596            de: "cart".into(),
9597            para: "catalog".into(),
9598            wit: "wasi:http/proxy".into(),
9599            endpoint: Some(String::new()),
9600            subject: None,
9601            slot: None,
9602        });
9603        let err = s.validate().unwrap_err();
9604        assert!(
9605            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9606            "got {err:?}"
9607        );
9608    }
9609
9610    #[test]
9611    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9612        // Ordering pin: an endpoint without a leading `/` surfaces the
9613        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9614        // value-shape gate is only consulted on endpoints that already
9615        // satisfy the absolute-prefix invariant. Mirrors
9616        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9617        let err = contrato_endpoint_err("bad path");
9618        assert!(
9619            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9620                if endpoint == "bad path"),
9621            "got {err:?}"
9622        );
9623    }
9624
9625    #[test]
9626    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9627        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9628        // `:para` + a non-empty reason flow through verbatim so the
9629        // author can grep their caixa.lisp for the offending contrato
9630        // block and fix it in one edit. Same shape as
9631        // `entrada_path_diagnostic_carries_offending_path`.
9632        let err = contrato_endpoint_err("/api?q=1");
9633        match err {
9634            AplicacaoError::ContratoEndpointInvalid {
9635                de,
9636                para,
9637                endpoint,
9638                reason,
9639            } => {
9640                assert_eq!(de, "cart");
9641                assert_eq!(para, "catalog");
9642                assert_eq!(endpoint, "/api?q=1");
9643                assert!(!reason.is_empty(), "reason field must be non-empty");
9644            }
9645            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9646        }
9647    }
9648
9649    #[test]
9650    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9651        // The compounding theorem: every &str inside a WitTarget
9652        // returned by target() is non-empty (and absolute, for Http).
9653        // Renderers downstream of typed_view() can rely on this
9654        // without re-checking — the type system carries the proof.
9655        let http = contract_http("cart", "catalog", "/x");
9656        match http.target().unwrap() {
9657            WitTarget::Http { endpoint } => {
9658                assert!(!endpoint.is_empty());
9659                assert!(endpoint.starts_with('/'));
9660            }
9661            other => panic!("expected Http, got {other:?}"),
9662        }
9663        let nats = WitContract {
9664            de: "a".into(),
9665            para: "b".into(),
9666            wit: "nats:pub-sub".into(),
9667            endpoint: None,
9668            subject: Some("topic.x".into()),
9669            slot: None,
9670        };
9671        match nats.target().unwrap() {
9672            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9673            other => panic!("expected PubSub, got {other:?}"),
9674        }
9675        let kv = WitContract {
9676            de: "a".into(),
9677            para: "b".into(),
9678            wit: "wasi:keyvalue/store".into(),
9679            endpoint: None,
9680            subject: None,
9681            slot: Some("checkout/$orderId".into()),
9682        };
9683        match kv.target().unwrap() {
9684            WitTarget::Store { slot } => assert!(!slot.is_empty()),
9685            other => panic!("expected Store, got {other:?}"),
9686        }
9687    }
9688
9689    #[test]
9690    fn target_diagnostic_names_offending_endpoint_value() {
9691        // When the malformed endpoint string is non-trivial, the
9692        // diagnostic carries the actual value back to the author —
9693        // not a generic "endpoint malformed" error.
9694        let bad = WitContract {
9695            de: "src".into(),
9696            para: "dst".into(),
9697            wit: "wasi:http/proxy".into(),
9698            endpoint: Some("api/v1/charge".into()),
9699            subject: None,
9700            slot: None,
9701        };
9702        match bad.target().unwrap_err() {
9703            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9704                assert_eq!(de, "src");
9705                assert_eq!(para, "dst");
9706                assert_eq!(endpoint, "api/v1/charge");
9707            }
9708            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9709        }
9710    }
9711
9712    #[test]
9713    fn rejects_unknown_wit_with_target_set() {
9714        let mut s = three_member_spec();
9715        s.contratos.push(WitContract {
9716            de: "cart".into(),
9717            para: "catalog".into(),
9718            wit: "custom:exchange".into(),
9719            endpoint: Some("/leaked".into()),
9720            subject: None,
9721            slot: None,
9722        });
9723        let err = s.validate().unwrap_err();
9724        assert!(matches!(
9725            err,
9726            AplicacaoError::ContratoWrongTarget {
9727                expected: WitTarget::CAPABILITY_EXPECTED,
9728                ..
9729            }
9730        ));
9731    }
9732
9733    #[test]
9734    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9735        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9736        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9737        // fourth arm of the same "which payload field name goes in the
9738        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9739        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9740        // consts cover on the peer HTTP / PubSub / Store arms
9741        // (`wit_target_field_name_pins_per_variant`). Until this lift
9742        // landed the byte-string sat twice — once inline in the
9743        // [`WitContract::target`] Capability-arm rejection at the
9744        // production dispatch, once in `rejects_unknown_wit_with_target_set`
9745        // pinning against the same literal — with no compile-time link
9746        // between them. Same "one canonical declaration, next to the
9747        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9748        // lift established for the payload-less arm's human-readable
9749        // label axis; this test is the shape peer of
9750        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9751        // pair (routes-through-const + scalar-value pin) on the
9752        // wrong-target diagnostic-scalar axis.
9753        //
9754        // Fail-before-pass-after was verified locally by mutating the
9755        // const declaration to `"capability"` — the scalar-value pin
9756        // below fires (`"capability" != "none"`) and the routes-through
9757        // assertion below still holds (production and const walk in
9758        // lockstep), which is the correct behavior: a rename on the
9759        // const drifts here first, not at a downstream consumer.
9760        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9761
9762        let mut s = three_member_spec();
9763        s.contratos.push(WitContract {
9764            de: "cart".into(),
9765            para: "catalog".into(),
9766            wit: "custom:exchange".into(),
9767            endpoint: Some("/leaked".into()),
9768            subject: None,
9769            slot: None,
9770        });
9771        match s.validate().unwrap_err() {
9772            AplicacaoError::ContratoWrongTarget { expected, .. } => {
9773                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9774            }
9775            other => panic!("expected ContratoWrongTarget, got {other:?}"),
9776        }
9777    }
9778
9779    #[test]
9780    fn unknown_wit_capability_only_validates() {
9781        let mut s = three_member_spec();
9782        s.contratos.push(WitContract {
9783            de: "cart".into(),
9784            para: "catalog".into(),
9785            // A WIT world we haven't yet shaped — accept it as a typed
9786            // capability edge so authors aren't blocked while the WIT
9787            // registry catches up. No payload field may be carried.
9788            wit: "custom:exchange".into(),
9789            endpoint: None,
9790            subject: None,
9791            slot: None,
9792        });
9793        s.validate().unwrap();
9794        let added = s.contratos.last().unwrap();
9795        assert_eq!(added.target().unwrap(), WitTarget::Capability);
9796    }
9797
9798    #[test]
9799    fn target_typed_view_round_trips_each_shape() {
9800        let http = contract_http("cart", "catalog", "/products/:id");
9801        assert_eq!(
9802            http.target().unwrap(),
9803            WitTarget::Http {
9804                endpoint: "/products/:id"
9805            }
9806        );
9807        let nats = WitContract {
9808            de: "a".into(),
9809            para: "b".into(),
9810            wit: "nats:pub-sub".into(),
9811            endpoint: None,
9812            subject: Some("topic.x".into()),
9813            slot: None,
9814        };
9815        assert_eq!(
9816            nats.target().unwrap(),
9817            WitTarget::PubSub { subject: "topic.x" }
9818        );
9819        let kv = WitContract {
9820            de: "a".into(),
9821            para: "b".into(),
9822            wit: "wasi:keyvalue/store".into(),
9823            endpoint: None,
9824            subject: None,
9825            slot: Some("checkout/$orderId".into()),
9826        };
9827        assert_eq!(
9828            kv.target().unwrap(),
9829            WitTarget::Store {
9830                slot: "checkout/$orderId"
9831            }
9832        );
9833    }
9834
9835    #[test]
9836    fn wit_contract_kind_predicates() {
9837        let http = contract_http("a", "b", "/x");
9838        assert!(http.is_http());
9839        assert!(!http.is_pubsub());
9840        assert!(!http.is_store());
9841
9842        let nats = WitContract {
9843            de: "a".into(),
9844            para: "b".into(),
9845            wit: "nats:pub-sub".into(),
9846            endpoint: None,
9847            subject: Some("topic.x".into()),
9848            slot: None,
9849        };
9850        assert!(nats.is_pubsub());
9851        assert!(!nats.is_http());
9852
9853        let kv = WitContract {
9854            de: "a".into(),
9855            para: "b".into(),
9856            wit: "wasi:keyvalue/store".into(),
9857            endpoint: None,
9858            subject: None,
9859            slot: Some("checkout/$orderId".into()),
9860        };
9861        assert!(kv.is_store());
9862        assert!(!kv.is_http());
9863    }
9864
9865    // ── :contratos :wit value-shape gate ─────────────────────────────────
9866    //
9867    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9868    // dispatch-discriminator axis. Until this gate landed
9869    // `WitContract::target()` accepted any non-empty string and
9870    // silently demoted unrecognized shapes to a capability-only L4
9871    // edge — the canonical "I thought I had L7 HTTP routing, got
9872    // L4-only" footgun. Every authoring footgun the WIT registry's
9873    // own grammar rejects (uppercase, hyphen-for-colon typo,
9874    // whitespace, empty package, doubled `@`, …) now becomes a
9875    // caixa-build-time `ContratoWitInvalid` with the offending
9876    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9877    // as `ContratoEndpointInvalid` on the sibling axis; same shared
9878    // predicate (`crate::render::is_wit_world_ref`) ensures drift
9879    // between any two axes' rule enforcement is a build error at the
9880    // predicate, not piecemeal across renderers.
9881
9882    fn contrato_wit_err(wit: &str) -> AplicacaoError {
9883        // Fresh spec per call so the new contract doesn't collide on
9884        // identity with `three_member_spec`'s pre-existing entries.
9885        // The new edge uses `(payment, catalog)` — a pair the fixture
9886        // doesn't already declare — with no payload field set, so the
9887        // wit-shape gate fires before any payload-shape arm.
9888        let mut s = three_member_spec();
9889        s.contratos.push(WitContract {
9890            de: "payment".into(),
9891            para: "catalog".into(),
9892            wit: wit.into(),
9893            endpoint: None,
9894            subject: None,
9895            slot: None,
9896        });
9897        s.validate().unwrap_err()
9898    }
9899
9900    #[test]
9901    fn rejects_wit_with_uppercase_namespace() {
9902        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9903        // didn't match the lowercase `wasi:http/` prefix is_http() keys
9904        // off, so the dispatch fell through to the capability arm and
9905        // the contract silently rendered as an L4-only Cilium edge.
9906        // The new gate surfaces the uppercase typo at validate time
9907        // with the offending `:wit` named.
9908        let err = contrato_wit_err("WASI:http/proxy");
9909        assert!(
9910            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9911                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9912            "got {err:?}"
9913        );
9914    }
9915
9916    #[test]
9917    fn rejects_wit_with_hyphen_for_colon_typo() {
9918        // The canonical "I forgot the `:` separator" typo — pre-gate
9919        // this passed as Capability silently, so the renderer emitted
9920        // an L4-only policy where the author expected L7 HTTP rules.
9921        let err = contrato_wit_err("wasi-http/proxy");
9922        assert!(
9923            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9924                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9925            "got {err:?}"
9926        );
9927    }
9928
9929    #[test]
9930    fn rejects_wit_with_multiple_colons() {
9931        // Doubled `:` — the namespace/package split has nowhere to
9932        // anchor, so the dispatch silently demotes to Capability.
9933        let err = contrato_wit_err("wasi:http:proxy");
9934        assert!(
9935            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9936                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9937            "got {err:?}"
9938        );
9939    }
9940
9941    #[test]
9942    fn rejects_wit_with_empty_package() {
9943        // `wasi:` — namespace alone with no package. Pre-gate this
9944        // failed neither the is_http nor is_pubsub nor is_store
9945        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9946        // a bare `wasi:`), so it silently demoted to Capability.
9947        let err = contrato_wit_err("wasi:");
9948        assert!(
9949            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9950                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9951            "got {err:?}"
9952        );
9953    }
9954
9955    #[test]
9956    fn rejects_wit_with_underscore() {
9957        // Underscore — WIT identifiers are kebab-case, same rule
9958        // DNS-1123 enforces on its peer axes. The diagnostic carries
9959        // the explicit "use `-` instead" remediation.
9960        let err = contrato_wit_err("wasi:http_proxy");
9961        assert!(
9962            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9963                if wit == "wasi:http_proxy" && reason.contains('_')),
9964            "got {err:?}"
9965        );
9966    }
9967
9968    #[test]
9969    fn rejects_wit_with_whitespace() {
9970        // Whitespace mid-token — the prefix check matches but the
9971        // package-and-onward parse silently demoted to Capability.
9972        let err = contrato_wit_err("wasi:http proxy");
9973        assert!(
9974            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9975                if wit == "wasi:http proxy" && reason.contains("whitespace")),
9976            "got {err:?}"
9977        );
9978    }
9979
9980    #[test]
9981    fn rejects_wit_with_non_ascii() {
9982        // Un-percent-encoded non-ASCII byte — the canonical "I copied
9983        // the package name from a doc with smart quotes / accented
9984        // characters" footgun.
9985        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9986        assert!(
9987            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9988                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9989            "got {err:?}"
9990        );
9991    }
9992
9993    #[test]
9994    fn rejects_wit_with_consecutive_hyphens() {
9995        // `pub--sub` — WIT identifiers join words with single hyphens.
9996        let err = contrato_wit_err("nats:pub--sub");
9997        assert!(
9998            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9999                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10000            "got {err:?}"
10001        );
10002    }
10003
10004    #[test]
10005    fn rejects_wit_with_trailing_at_no_version() {
10006        // `wasi:http/proxy@` — the version-suffix author started to
10007        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10008        // parser would reject this; surface it at validate time.
10009        let err = contrato_wit_err("wasi:http/proxy@");
10010        assert!(
10011            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10012                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10013            "got {err:?}"
10014        );
10015    }
10016
10017    #[test]
10018    fn rejects_wit_too_long() {
10019        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10020        // The legitimate-shape arms all pass (lowercase, single `:`,
10021        // kebab-case identifiers); only the cap arm fires. Surfaces
10022        // the paste-from-binary / accidental-multi-line-blob landing
10023        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10024        // on the peer axis.
10025        let big = format!("wasi:{}", "a".repeat(124));
10026        assert_eq!(big.len(), 129);
10027        let err = contrato_wit_err(&big);
10028        assert!(
10029            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10030                if wit == &big && reason.contains("max length of 128")),
10031            "got {err:?}"
10032        );
10033    }
10034
10035    #[test]
10036    fn wit_max_length_validates() {
10037        // 128-byte WIT reference — exactly the cap. Boundary pin:
10038        // drift in the cap surfaces here and at `rejects_wit_too_long`
10039        // simultaneously, mirroring
10040        // `http_contrato_endpoint_max_length_validates` on the peer
10041        // axis.
10042        let big = format!("wasi:{}", "a".repeat(123));
10043        assert_eq!(big.len(), 128);
10044        let mut s = three_member_spec();
10045        s.contratos.push(WitContract {
10046            de: "payment".into(),
10047            para: "catalog".into(),
10048            wit: big,
10049            endpoint: None,
10050            subject: None,
10051            slot: None,
10052        });
10053        s.validate().unwrap();
10054    }
10055
10056    #[test]
10057    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10058        // Positive-set sweep through the AplicacaoSpec::validate
10059        // surface (rather than the substrate-side predicate directly)
10060        // — pins every shape the existing test fixtures + the
10061        // checkout-aplicacao example carry, so the gate's accept-set
10062        // matches the substrate's emit-set. Drift between this list
10063        // and `render::tests::wit_world_ref_accepts_canonical_forms`
10064        // surfaces at the substrate layer's positive sweep — one
10065        // source of truth for the rule.
10066        for wit in [
10067            "wasi:http/proxy",
10068            "wasi:keyvalue/store",
10069            "nats:pub-sub",
10070            "kafka:topic",
10071            "custom:exchange",
10072            "pleme:cap/audit",
10073            "wasi:http/proxy@0.2.0",
10074        ] {
10075            // Payload field paired to the dispatched WIT shape so the
10076            // shape-↔-target arm doesn't fire instead of the wit-shape
10077            // arm we're exercising. Routes off the same
10078            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10079            // `wit_shape_is_store` free functions the production
10080            // `WitContract::is_http` / `is_pubsub` / `is_store`
10081            // methods delegate to (both consult the lifted
10082            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10083            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10084            // future prefix addition to the routing accept-set
10085            // reaches this test's payload-dispatch arm by
10086            // construction — no per-test-site drift can hide a
10087            // shape-→-target-slot mismatch that would silently
10088            // demote a canonical `:wit` value to the
10089            // `(None, None, None)` capability-only arm and let the
10090            // `AplicacaoSpec::validate` positive sweep pass on a
10091            // shape it should exercise as HTTP / pub-sub / store.
10092            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10093                (Some("/x".into()), None, None)
10094            } else if wit_shape_is_pubsub(wit) {
10095                (None, Some("topic.x".into()), None)
10096            } else if wit_shape_is_store(wit) {
10097                (None, None, Some("bucket/$key".into()))
10098            } else {
10099                (None, None, None)
10100            };
10101            let mut s = three_member_spec();
10102            s.contratos.push(WitContract {
10103                de: "payment".into(),
10104                para: "catalog".into(),
10105                wit: wit.into(),
10106                endpoint,
10107                subject,
10108                slot,
10109            });
10110            s.validate()
10111                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10112        }
10113    }
10114
10115    #[test]
10116    fn wit_shape_predicates_accept_canonical_prefix_set() {
10117        // Positive-set sweep pinning every prefix in
10118        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10119        // WIT_STORE_SHAPE_PREFIXES against the three free-function
10120        // dispatch predicates. The six prefixes are the load-bearing
10121        // routing keys the substrate's WIT-shape dispatch consults
10122        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10123        // key/value-store-slot admission); any drift between the
10124        // free-function accept-set and this list surfaces here
10125        // rather than at apply time as a silent
10126        // shape-→-capability-only demotion.
10127        assert!(wit_shape_is_http("wasi:http/proxy"));
10128        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10129        assert!(wit_shape_is_http("http:incoming"));
10130
10131        assert!(wit_shape_is_pubsub("nats:pub-sub"));
10132        assert!(wit_shape_is_pubsub("kafka:topic"));
10133
10134        assert!(wit_shape_is_store("wasi:keyvalue/store"));
10135        assert!(wit_shape_is_store("kv:cache/session"));
10136    }
10137
10138    #[test]
10139    fn wit_shape_predicates_reject_uncanonical_forms() {
10140        // Negative-set pin: the six canonical prefixes are
10141        // lowercase-only (mirrors the `is_wit_world_ref` substrate
10142        // predicate's lowercase invariant — see its docstring on the
10143        // "I thought I had L7 HTTP routing, got L4-only" footgun).
10144        // The empty string, an uppercase-prefixed form, a hyphen-
10145        // instead-of-colon typo, and a bare kebab identifier all miss
10146        // every shape arm — reachable-by-construction only via the
10147        // `is_wit_world_ref` gate that admission-checks the `:wit`
10148        // value first, but pinned here so any future
10149        // free-function change (e.g. a case-insensitive
10150        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10151        // this unit level.
10152        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10153            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10154            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10155            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10156        }
10157    }
10158
10159    #[test]
10160    fn wit_shape_predicates_partition_canonical_set() {
10161        // Every canonical prefix routes to exactly one shape arm —
10162        // the three prefix sets are pairwise disjoint. Pins the
10163        // routing property [`WitContract::target`] relies on: an
10164        // `is_http()` return of `true` guarantees `is_pubsub()` and
10165        // `is_store()` return `false`, so the shape-→-target-slot
10166        // dispatch (endpoint vs subject vs slot) is unambiguous.
10167        // Drift (e.g. a future `"kv:"` moved into the HTTP set
10168        // without removal from the store set) would silently route
10169        // one prefix to two arms and the first-matching-arm order
10170        // becomes load-bearing — this pin surfaces it as a build
10171        // error instead.
10172        for prefix in WIT_HTTP_SHAPE_PREFIXES {
10173            let sample = format!("{prefix}x");
10174            assert!(wit_shape_is_http(&sample));
10175            assert!(!wit_shape_is_pubsub(&sample));
10176            assert!(!wit_shape_is_store(&sample));
10177        }
10178        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10179            let sample = format!("{prefix}x");
10180            assert!(!wit_shape_is_http(&sample));
10181            assert!(wit_shape_is_pubsub(&sample));
10182            assert!(!wit_shape_is_store(&sample));
10183        }
10184        for prefix in WIT_STORE_SHAPE_PREFIXES {
10185            let sample = format!("{prefix}x");
10186            assert!(!wit_shape_is_http(&sample));
10187            assert!(!wit_shape_is_pubsub(&sample));
10188            assert!(wit_shape_is_store(&sample));
10189        }
10190    }
10191
10192    #[test]
10193    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10194        // Positive pin: [`wit_shape_matches`] is exactly the
10195        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10196        // parameterized on the accept-set. Two-prefix accept-set,
10197        // one-prefix accept-set, and empty accept-set (which must
10198        // reject everything, including the empty string — an empty
10199        // `any()` fold returns `false`) all pinned so a future
10200        // reimplementation that swaps `starts_with` for `contains`,
10201        // `==`, or a case-folded comparator surfaces at unit-test
10202        // time.
10203        let two = &["wasi:http/", "http:"];
10204        assert!(wit_shape_matches("wasi:http/proxy", two));
10205        assert!(wit_shape_matches("http:incoming", two));
10206        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10207
10208        let one = &["nats:"];
10209        assert!(wit_shape_matches("nats:pub-sub", one));
10210        assert!(!wit_shape_matches("kafka:topic", one));
10211
10212        // Empty accept-set matches nothing — the identity element
10213        // for the disjunctive `any()` fold across the prefix set.
10214        // Reachable via a future `wit_shape_is_<name>` const paired
10215        // to a still-empty prefix table on a nascent shape-arm draft.
10216        let empty: &[&str] = &[];
10217        assert!(!wit_shape_matches("wasi:http/proxy", empty));
10218        assert!(!wit_shape_matches("", empty));
10219
10220        // starts_with, not contains: a prefix embedded mid-string
10221        // never matches. Pins the routing invariant [`WitContract::target`]
10222        // relies on (an authored `:wit "custom:wasi:http/"` string
10223        // does not silently route through the HTTP arm just because
10224        // it happens to contain the canonical HTTP prefix).
10225        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10226    }
10227
10228    #[test]
10229    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10230        // Equivalence pin: each per-shape predicate is exactly
10231        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10232        // every canonical prefix + the empty string + one negative
10233        // sample against every peer so a future predicate that grew
10234        // its own inline `iter().any(starts_with)` (rather than
10235        // delegating through the lifted combinator) drifts loudly here
10236        // — the peer-const table's contents must agree with the
10237        // predicate's accept-set by construction.
10238        let samples = [
10239            String::new(),
10240            "wasi:http/proxy".to_string(),
10241            "http:incoming".to_string(),
10242            "nats:pub-sub".to_string(),
10243            "kafka:topic".to_string(),
10244            "wasi:keyvalue/store".to_string(),
10245            "kv:cache/session".to_string(),
10246            "custom-shape".to_string(),
10247            "WASI:HTTP/proxy".to_string(),
10248        ];
10249        for wit in &samples {
10250            assert_eq!(
10251                wit_shape_is_http(wit),
10252                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10253                "wit_shape_is_http drifted from combinator on {wit:?}",
10254            );
10255            assert_eq!(
10256                wit_shape_is_pubsub(wit),
10257                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10258                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10259            );
10260            assert_eq!(
10261                wit_shape_is_store(wit),
10262                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10263                "wit_shape_is_store drifted from combinator on {wit:?}",
10264            );
10265        }
10266    }
10267
10268    #[test]
10269    fn wit_contract_shape_methods_delegate_to_free_functions() {
10270        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10271        // `is_store` are `&self` conveniences on top of the free
10272        // functions — for every canonical prefix the method's return
10273        // matches its free-function peer. Sweeps the union of the
10274        // three prefix sets so a future method that grew its own
10275        // inline prefix logic (rather than delegating) drifts loudly
10276        // here on the first prefix the free function accepts and the
10277        // method doesn't.
10278        for shape_set in [
10279            WIT_HTTP_SHAPE_PREFIXES,
10280            WIT_PUBSUB_SHAPE_PREFIXES,
10281            WIT_STORE_SHAPE_PREFIXES,
10282        ] {
10283            for prefix in shape_set {
10284                let c = WitContract {
10285                    de: "cart".into(),
10286                    para: "catalog".into(),
10287                    wit: format!("{prefix}x"),
10288                    endpoint: None,
10289                    subject: None,
10290                    slot: None,
10291                };
10292                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10293                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10294                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10295            }
10296        }
10297    }
10298
10299    #[test]
10300    fn empty_wit_takes_precedence_over_invalid() {
10301        // Ordering pin: `EmptyWit` is the more self-locating
10302        // diagnostic on `""` and must lead — the value-shape gate is
10303        // only reached after the empty-check fires. Mirrors
10304        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10305        // the peer payload axis.
10306        let mut s = three_member_spec();
10307        s.contratos.push(WitContract {
10308            de: "payment".into(),
10309            para: "catalog".into(),
10310            wit: String::new(),
10311            endpoint: None,
10312            subject: None,
10313            slot: None,
10314        });
10315        let err = s.validate().unwrap_err();
10316        assert!(
10317            matches!(err, AplicacaoError::EmptyWit { .. }),
10318            "got {err:?}"
10319        );
10320    }
10321
10322    #[test]
10323    fn wit_invalid_fires_before_payload_shape_arm() {
10324        // Ordering pin: a malformed `:wit` surfaces *its own*
10325        // diagnostic (which names the offending wit verbatim) before
10326        // any payload-field check — a contrato whose wit is
10327        // structurally invalid AND carries a wrong target field
10328        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
10329        // because the dispatch on the wit is what decides which
10330        // payload field is "right" in the first place. Without this
10331        // ordering, the author would see "wrong target field" for a
10332        // wit that hasn't even been parsed, which doesn't name the
10333        // root cause.
10334        let mut s = three_member_spec();
10335        s.contratos.push(WitContract {
10336            de: "payment".into(),
10337            para: "catalog".into(),
10338            // Hyphen-for-colon typo + endpoint set: pre-gate this
10339            // raised `ContratoWrongTarget { expected: "none" }` (the
10340            // Capability arm rejecting the endpoint), masking the
10341            // real authoring mistake (the wit isn't `wasi:http/proxy`).
10342            wit: "wasi-http/proxy".into(),
10343            endpoint: Some("/x".into()),
10344            subject: None,
10345            slot: None,
10346        });
10347        let err = s.validate().unwrap_err();
10348        assert!(
10349            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10350                if wit == "wasi-http/proxy"),
10351            "got {err:?}"
10352        );
10353    }
10354
10355    #[test]
10356    fn wit_invalid_diagnostic_carries_offending_wit() {
10357        // Diagnostic-shape pin — the offending `:wit` + `:de` +
10358        // `:para` + a non-empty reason flow through verbatim so the
10359        // author can grep their caixa.lisp for the offending contrato
10360        // block and fix it in one edit. Same shape as
10361        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10362        let err = contrato_wit_err("WASI:HTTP/proxy");
10363        match err {
10364            AplicacaoError::ContratoWitInvalid {
10365                de,
10366                para,
10367                wit,
10368                reason,
10369            } => {
10370                assert_eq!(de, "payment");
10371                assert_eq!(para, "catalog");
10372                assert_eq!(wit, "WASI:HTTP/proxy");
10373                assert!(!reason.is_empty(), "reason field must be non-empty");
10374            }
10375            other => panic!("expected ContratoWitInvalid, got {other:?}"),
10376        }
10377    }
10378
10379    // ── :contratos :subject value-shape gate ─────────────────────────────
10380    //
10381    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10382    // suites on the peer payload axes. Until this gate landed
10383    // `WitContract::target()` only refused the empty string; a
10384    // structurally invalid subject silently passed validate and the
10385    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10386    // Subject'` on publish / subscribe, or as a silent message drop,
10387    // far from the source caixa.lisp. Every authoring footgun the
10388    // NATS server's subject parser would catch on admission now
10389    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10390    // offending `:subject` + `:de` + `:para` named verbatim. Same
10391    // diagnostic shape as `ContratoEndpointInvalid` /
10392    // `ContratoWitInvalid` on the peer payload axes; same shared
10393    // predicate (`crate::render::is_nats_subject`) ensures drift
10394    // between any two axes' rule enforcement is a build error at the
10395    // predicate, not piecemeal across renderers.
10396
10397    fn contrato_subject_err(subject: &str) -> AplicacaoError {
10398        // Fresh spec per call so the new contract doesn't collide on
10399        // identity with `three_member_spec`'s pre-existing entries.
10400        // The new edge uses `(payment, catalog)` — a pair the fixture
10401        // doesn't already declare — with `:wit "nats:pub-sub"` and the
10402        // varying `:subject`, so the subject-shape gate fires cleanly
10403        // after the wit-shape gate (which `"nats:pub-sub"` passes).
10404        let mut s = three_member_spec();
10405        s.contratos.push(WitContract {
10406            de: "payment".into(),
10407            para: "catalog".into(),
10408            wit: "nats:pub-sub".into(),
10409            endpoint: None,
10410            subject: Some(subject.into()),
10411            slot: None,
10412        });
10413        s.validate().unwrap_err()
10414    }
10415
10416    #[test]
10417    fn rejects_pubsub_contrato_subject_with_whitespace() {
10418        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10419        // landed at the NATS server as a malformed subject the parser
10420        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
10421        // source caixa.lisp.
10422        let err = contrato_subject_err("foo bar");
10423        assert!(
10424            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10425                if subject == "foo bar" && reason.contains("whitespace")),
10426            "got {err:?}"
10427        );
10428    }
10429
10430    #[test]
10431    fn rejects_pubsub_contrato_subject_with_control_char() {
10432        let err = contrato_subject_err("foo\x01bar");
10433        assert!(
10434            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10435                if subject == "foo\x01bar" && reason.contains("control character")),
10436            "got {err:?}"
10437        );
10438    }
10439
10440    #[test]
10441    fn rejects_pubsub_contrato_subject_with_non_ascii() {
10442        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10443        // the subject from a doc with smart quotes / accented
10444        // characters" footgun.
10445        let err = contrato_subject_err("foo.caf\u{e9}");
10446        assert!(
10447            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10448                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
10449            "got {err:?}"
10450        );
10451    }
10452
10453    #[test]
10454    fn rejects_pubsub_contrato_subject_with_leading_dot() {
10455        // Empty leading token — NATS rejects.
10456        let err = contrato_subject_err(".foo");
10457        assert!(
10458            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10459                if subject == ".foo" && reason.contains("must not start with `.`")),
10460            "got {err:?}"
10461        );
10462    }
10463
10464    #[test]
10465    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
10466        // Empty trailing token — NATS rejects. The remediation
10467        // (use `>` instead) is in the reason string.
10468        let err = contrato_subject_err("foo.");
10469        assert!(
10470            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10471                if subject == "foo." && reason.contains("must not end with `.`")),
10472            "got {err:?}"
10473        );
10474    }
10475
10476    #[test]
10477    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
10478        // The canonical "I forgot to fill in the middle segment"
10479        // typo — `"foo..bar"`. NATS rejects empty tokens.
10480        let err = contrato_subject_err("foo..bar");
10481        assert!(
10482            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10483                if subject == "foo..bar" && reason.contains("consecutive `.`")),
10484            "got {err:?}"
10485        );
10486    }
10487
10488    #[test]
10489    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10490        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10491        // as the final segment. Pre-gate this passed as a typed edge
10492        // and surfaced at runtime as a NATS subscribe rejection.
10493        let err = contrato_subject_err("foo.>.bar");
10494        assert!(
10495            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10496                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10497            "got {err:?}"
10498        );
10499    }
10500
10501    #[test]
10502    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10503        // `foo*.bar` — NATS wildcards are standalone tokens. The
10504        // remediation is in the reason string.
10505        let err = contrato_subject_err("foo*.bar");
10506        assert!(
10507            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10508                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10509            "got {err:?}"
10510        );
10511    }
10512
10513    #[test]
10514    fn rejects_pubsub_contrato_subject_with_invalid_char() {
10515        // `foo,bar` — comma is not a valid NATS subject character.
10516        // Pinned separately from the wildcard arms so the invalid-
10517        // character diagnostic is in force.
10518        let err = contrato_subject_err("foo,bar");
10519        assert!(
10520            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10521                if subject == "foo,bar" && reason.contains("invalid character")),
10522            "got {err:?}"
10523        );
10524    }
10525
10526    #[test]
10527    fn rejects_pubsub_contrato_subject_too_long() {
10528        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10529        // The legitimate-shape arms all pass (one all-`a` token, no
10530        // `.`, no wildcards); only the cap arm fires. Surfaces the
10531        // paste-from-binary / accidental-multi-line-blob landing
10532        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10533        // on the peer axis.
10534        let big = "a".repeat(257);
10535        assert_eq!(big.len(), 257);
10536        let err = contrato_subject_err(&big);
10537        assert!(
10538            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10539                if subject == &big && reason.contains("max length of 256")),
10540            "got {err:?}"
10541        );
10542    }
10543
10544    #[test]
10545    fn pubsub_contrato_subject_max_length_validates() {
10546        // 256-byte subject — exactly the cap. Boundary pin: drift in
10547        // the cap surfaces here and at
10548        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10549        // mirroring `http_contrato_endpoint_max_length_validates` and
10550        // `wit_max_length_validates` on the peer axes.
10551        let big = "a".repeat(256);
10552        assert_eq!(big.len(), 256);
10553        let mut s = three_member_spec();
10554        s.contratos.push(WitContract {
10555            de: "payment".into(),
10556            para: "catalog".into(),
10557            wit: "nats:pub-sub".into(),
10558            endpoint: None,
10559            subject: Some(big),
10560            slot: None,
10561        });
10562        s.validate().unwrap();
10563    }
10564
10565    #[test]
10566    fn pubsub_contrato_subject_accepts_canonical_forms() {
10567        // Positive-set sweep: every canonical NATS subject shape the
10568        // substrate-side `is_nats_subject` predicate accepts (the
10569        // multi-dot `events.order.charged`, the snake_case / kebab-
10570        // case / mixed-case tokens, the digit-bearing tokens, the
10571        // single-token wildcard `*` at every segment position, and
10572        // the trailing `>` multi-token wildcard) must remain a valid
10573        // contrato subject too. Drift between this list and the
10574        // substrate-side `nats_subject_accepts_canonical_forms` sweep
10575        // surfaces at the shared predicate — one source of truth.
10576        // Uses a fresh `(payment, catalog)` edge so none of the swept
10577        // subjects collide with the pre-existing entries in
10578        // `three_member_spec`.
10579        for subject in [
10580            "checkout.events.charge.failed",
10581            "rio.events.order.charged",
10582            "orders",
10583            "orders.123",
10584            "snake_case.token",
10585            "kebab-case.token",
10586            "MixedCase.Token",
10587            "orders.*.charged",
10588            "*.events.*",
10589            "orders.>",
10590        ] {
10591            let mut s = three_member_spec();
10592            s.contratos.push(WitContract {
10593                de: "payment".into(),
10594                para: "catalog".into(),
10595                wit: "nats:pub-sub".into(),
10596                endpoint: None,
10597                subject: Some(subject.into()),
10598                slot: None,
10599            });
10600            s.validate()
10601                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10602        }
10603    }
10604
10605    #[test]
10606    fn contrato_subject_empty_takes_precedence_over_invalid() {
10607        // Ordering pin: `ContratoSubjectEmpty` is the more self-
10608        // locating diagnostic on `""` and must lead — the value-shape
10609        // gate is only reached after the empty-check fires. Mirrors
10610        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10611        // the peer payload axis.
10612        let mut s = three_member_spec();
10613        s.contratos.push(WitContract {
10614            de: "payment".into(),
10615            para: "catalog".into(),
10616            wit: "nats:pub-sub".into(),
10617            endpoint: None,
10618            subject: Some(String::new()),
10619            slot: None,
10620        });
10621        let err = s.validate().unwrap_err();
10622        assert!(
10623            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10624            "got {err:?}"
10625        );
10626    }
10627
10628    #[test]
10629    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10630        // Diagnostic-shape pin — the offending `:subject` + `:de` +
10631        // `:para` + a non-empty reason flow through verbatim so the
10632        // author can grep their caixa.lisp for the offending contrato
10633        // block and fix it in one edit. Same shape as
10634        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10635        // and `wit_invalid_diagnostic_carries_offending_wit`.
10636        let err = contrato_subject_err("foo..bar");
10637        match err {
10638            AplicacaoError::ContratoSubjectInvalid {
10639                de,
10640                para,
10641                subject,
10642                reason,
10643            } => {
10644                assert_eq!(de, "payment");
10645                assert_eq!(para, "catalog");
10646                assert_eq!(subject, "foo..bar");
10647                assert!(!reason.is_empty(), "reason field must be non-empty");
10648            }
10649            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10650        }
10651    }
10652
10653    #[test]
10654    fn target_view_pubsub_subject_passes_through_to_typed_view() {
10655        // The compounding theorem on the pub-sub axis: every
10656        // `WitTarget::PubSub { subject }` returned by `target()` carries
10657        // a NATS-server-accepted subject. Renderers downstream of
10658        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10659        // NATS Stream/Consumer CR emitter, the future `feira app graph`
10660        // view's subject labeller) can rely on this without re-checking
10661        // — the type system carries the proof. Mirrors
10662        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10663        // on the peer axes.
10664        let nats = WitContract {
10665            de: "a".into(),
10666            para: "b".into(),
10667            wit: "nats:pub-sub".into(),
10668            endpoint: None,
10669            subject: Some("orders.events.*.charged".into()),
10670            slot: None,
10671        };
10672        match nats.target().unwrap() {
10673            WitTarget::PubSub { subject } => {
10674                assert_eq!(subject, "orders.events.*.charged");
10675            }
10676            other => panic!("expected PubSub, got {other:?}"),
10677        }
10678    }
10679
10680    // ── :contratos :slot value-shape gate ────────────────────────────────
10681    //
10682    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10683    // (63e18a0) value-shape suites on the peer payload axes. Until this
10684    // gate landed `WitContract::target()` only refused the empty string
10685    // for the Store arm; a structurally invalid slot (raw whitespace,
10686    // control character, non-ASCII byte, paste-from-binary multi-line
10687    // blob) silently passed validate and surfaced at runtime as a
10688    // per-backend kv write rejection or a silent next-read corruption,
10689    // far from the source caixa.lisp with no field naming which
10690    // `:contratos` edge carried the typo. Every authoring footgun the
10691    // kv backend intersection-floor would catch on write now becomes a
10692    // caixa-build-time `ContratoSlotInvalid` with the offending
10693    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10694    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10695    // peer payload axes; same shared predicate
10696    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10697    // any two axes' rule enforcement is a build error at the
10698    // predicate, not piecemeal across renderers. Closes the typed
10699    // payload-axis value-shape trajectory across all three legs of the
10700    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10701
10702    fn contrato_slot_err(slot: &str) -> AplicacaoError {
10703        // Fresh spec per call so the new contract doesn't collide on
10704        // identity with `three_member_spec`'s pre-existing entries
10705        // and doesn't close a synchronous cycle the cycle detector
10706        // would reject before the slot-shape gate fires. The new edge
10707        // uses `(payment, catalog)` — a pair the fixture doesn't
10708        // already declare in either direction (the fixture carries
10709        // `cart -> catalog` and `cart -> payment`, so `payment ->
10710        // catalog` doesn't form a cycle on the sync subgraph) — with
10711        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10712        // slot-shape gate fires cleanly after the wit-shape gate
10713        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10714        // peer `contrato_subject_err` helper uses (63e18a0).
10715        let mut s = three_member_spec();
10716        s.contratos.push(WitContract {
10717            de: "payment".into(),
10718            para: "catalog".into(),
10719            wit: "wasi:keyvalue/store".into(),
10720            endpoint: None,
10721            subject: None,
10722            slot: Some(slot.into()),
10723        });
10724        s.validate().unwrap_err()
10725    }
10726
10727    #[test]
10728    fn rejects_store_contrato_slot_with_whitespace() {
10729        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10730        // silently landed at the kv backend with whitespace whose
10731        // runtime behavior varies unpredictably across backends (etcd
10732        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10733        // rejects on write). Now caught at the source caixa.lisp.
10734        let err = contrato_slot_err("check out/$order");
10735        assert!(
10736            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10737                if slot == "check out/$order" && reason.contains("whitespace")),
10738            "got {err:?}"
10739        );
10740    }
10741
10742    #[test]
10743    fn rejects_store_contrato_slot_with_tab() {
10744        // Tab byte arm-pinned separately from the space arm so a
10745        // future relaxation that admits one but not the other surfaces
10746        // here.
10747        let err = contrato_slot_err("check\tout");
10748        assert!(
10749            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10750                if slot == "check\tout" && reason.contains("whitespace")),
10751            "got {err:?}"
10752        );
10753    }
10754
10755    #[test]
10756    fn rejects_store_contrato_slot_with_control_char() {
10757        // SOH (0x01) — distinct from the whitespace arm. Redis admits
10758        // and corrupts on RESP protocol framing; DynamoDB rejects on
10759        // write.
10760        let err = contrato_slot_err("checkout/\x01order");
10761        assert!(
10762            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10763                if slot == "checkout/\x01order" && reason.contains("control character")),
10764            "got {err:?}"
10765        );
10766    }
10767
10768    #[test]
10769    fn rejects_store_contrato_slot_with_newline() {
10770        // Embedded newline — the canonical "the paste-from-binary slug
10771        // spans multiple lines" footgun. Distinct from the whitespace
10772        // arm because `\n` is a control character (0x0A).
10773        let err = contrato_slot_err("checkout\norder");
10774        assert!(
10775            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10776                if slot == "checkout\norder" && reason.contains("control character")),
10777            "got {err:?}"
10778        );
10779    }
10780
10781    #[test]
10782    fn rejects_store_contrato_slot_with_non_ascii() {
10783        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10784        // the slot from a doc with accented characters" footgun. Each
10785        // kv backend re-encodes non-ASCII differently (etcd preserves
10786        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10787        // rejects), so the typed slot's value set is the intersection-
10788        // floor every backend admits identically (printable ASCII).
10789        let err = contrato_slot_err("ch\u{e9}ckout/$order");
10790        assert!(
10791            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10792                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10793            "got {err:?}"
10794        );
10795    }
10796
10797    #[test]
10798    fn rejects_store_contrato_slot_too_long() {
10799        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10800        // legitimate-shape arms all pass (a single all-`a` token, no
10801        // separators); only the cap arm fires. Surfaces the paste-
10802        // from-binary / accidental-multi-line-blob landing footgun.
10803        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10804        // `rejects_http_contrato_endpoint_too_long` on the peer
10805        // payload axes.
10806        let big = "a".repeat(513);
10807        assert_eq!(big.len(), 513);
10808        let err = contrato_slot_err(&big);
10809        assert!(
10810            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10811                if slot == &big && reason.contains("max length of 512")),
10812            "got {err:?}"
10813        );
10814    }
10815
10816    #[test]
10817    fn store_contrato_slot_max_length_validates() {
10818        // 512-byte slot — exactly the cap. Boundary pin: drift in the
10819        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10820        // simultaneously, mirroring
10821        // `pubsub_contrato_subject_max_length_validates` and
10822        // `http_contrato_endpoint_max_length_validates` on the peer
10823        // payload axes.
10824        let big = "a".repeat(512);
10825        assert_eq!(big.len(), 512);
10826        let mut s = three_member_spec();
10827        s.contratos.push(WitContract {
10828            de: "payment".into(),
10829            para: "catalog".into(),
10830            wit: "wasi:keyvalue/store".into(),
10831            endpoint: None,
10832            subject: None,
10833            slot: Some(big),
10834        });
10835        s.validate().unwrap();
10836    }
10837
10838    #[test]
10839    fn store_contrato_slot_accepts_canonical_forms() {
10840        // Positive-set sweep: every canonical kv slot template the
10841        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10842        // (single-token identifiers, path-namespaced `$`-templates,
10843        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10844        // snake_case / kebab-case / MixedCase tokens, digit-bearing
10845        // tokens, percent-encoded fragments) must remain valid
10846        // contrato slots too. Drift between this list and the
10847        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10848        // surfaces at the shared predicate — one source of truth.
10849        // Uses a fresh `(payment, catalog)` edge so none of the swept
10850        // slots collide with the pre-existing entries in
10851        // `three_member_spec`.
10852        for slot in [
10853            "checkout",
10854            "checkout/$orderId",
10855            "users:{tenant}/{id}",
10856            "session.<sid>",
10857            "session.tokens.<sid>",
10858            "snake_case_key",
10859            "kebab-case-key",
10860            "MixedCase",
10861            "shard0",
10862            "v2/key",
10863            "users/caf%C3%A9",
10864        ] {
10865            let mut s = three_member_spec();
10866            s.contratos.push(WitContract {
10867                de: "payment".into(),
10868                para: "catalog".into(),
10869                wit: "wasi:keyvalue/store".into(),
10870                endpoint: None,
10871                subject: None,
10872                slot: Some(slot.into()),
10873            });
10874            s.validate()
10875                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10876        }
10877    }
10878
10879    #[test]
10880    fn contrato_slot_empty_takes_precedence_over_invalid() {
10881        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10882        // diagnostic on `""` and must lead — the value-shape gate is
10883        // only reached after the empty-check fires. Mirrors
10884        // `contrato_subject_empty_takes_precedence_over_invalid` and
10885        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10886        // the peer payload axes.
10887        let mut s = three_member_spec();
10888        s.contratos.push(WitContract {
10889            de: "payment".into(),
10890            para: "catalog".into(),
10891            wit: "wasi:keyvalue/store".into(),
10892            endpoint: None,
10893            subject: None,
10894            slot: Some(String::new()),
10895        });
10896        let err = s.validate().unwrap_err();
10897        assert!(
10898            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10899            "got {err:?}"
10900        );
10901    }
10902
10903    #[test]
10904    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10905        // Diagnostic-shape pin — the offending `:slot` + `:de` +
10906        // `:para` + a non-empty reason flow through verbatim so the
10907        // author can grep their caixa.lisp for the offending contrato
10908        // block and fix it in one edit. Same shape as
10909        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10910        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10911        // on the peer payload axes.
10912        let err = contrato_slot_err("check out/$order");
10913        match err {
10914            AplicacaoError::ContratoSlotInvalid {
10915                de,
10916                para,
10917                slot,
10918                reason,
10919            } => {
10920                assert_eq!(de, "payment");
10921                assert_eq!(para, "catalog");
10922                assert_eq!(slot, "check out/$order");
10923                assert!(!reason.is_empty(), "reason field must be non-empty");
10924            }
10925            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10926        }
10927    }
10928
10929    #[test]
10930    fn target_view_store_slot_passes_through_to_typed_view() {
10931        // The compounding theorem on the store axis: every
10932        // `WitTarget::Store { slot }` returned by `target()` carries a
10933        // kv-backend-accepted slot template. Renderers downstream of
10934        // `typed_view()` (the future per-Servico `:capabilities
10935        // wasi:keyvalue/store` axis emitter, the future `feira app
10936        // graph` view's slot labeller, the future kv-provider CR
10937        // materializer) can rely on this without re-checking — the
10938        // type system carries the proof. Mirrors
10939        // `target_view_pubsub_subject_passes_through_to_typed_view` on
10940        // the peer payload axis.
10941        let store = WitContract {
10942            de: "a".into(),
10943            para: "b".into(),
10944            wit: "wasi:keyvalue/store".into(),
10945            endpoint: None,
10946            subject: None,
10947            slot: Some("checkout/$orderId".into()),
10948        };
10949        match store.target().unwrap() {
10950            WitTarget::Store { slot } => {
10951                assert_eq!(slot, "checkout/$orderId");
10952            }
10953            other => panic!("expected Store, got {other:?}"),
10954        }
10955    }
10956
10957    #[test]
10958    fn rejects_self_loop_in_synchronous_contratos() {
10959        // A synchronous self-edge (`cart → cart` over HTTP) is now
10960        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10961        // "this edge is degenerate" diagnostic — rather than incidentally
10962        // by the cycle detector framing it as a `["cart", "cart"]`
10963        // multi-node deadlock.
10964        let mut s = three_member_spec();
10965        s.contratos.push(contract_http("cart", "cart", "/loop"));
10966        let err = s.validate().unwrap_err();
10967        match err {
10968            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10969                assert_eq!(caixa, "cart");
10970                assert_eq!(wit, "wasi:http/proxy");
10971            }
10972            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10973        }
10974    }
10975
10976    #[test]
10977    fn rejects_self_loop_in_pubsub_contratos() {
10978        // The cycle detector excludes pub-sub edges (acyclic by
10979        // construction), so before the explicit gate a `nats:pub-sub`
10980        // self-edge silently validated and rendered a self-allow CNP.
10981        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10982        let mut s = three_member_spec();
10983        s.contratos.push(WitContract {
10984            de: "payment".into(),
10985            para: "payment".into(),
10986            wit: "nats:pub-sub".into(),
10987            endpoint: None,
10988            subject: Some("rio.events.payment".into()),
10989            slot: None,
10990        });
10991        let err = s.validate().unwrap_err();
10992        match err {
10993            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10994                assert_eq!(caixa, "payment");
10995                assert_eq!(wit, "nats:pub-sub");
10996            }
10997            other => panic!("expected ContratoSelfLoop, got {other:?}"),
10998        }
10999    }
11000
11001    #[test]
11002    fn self_loop_fires_before_payload_shape_check() {
11003        // The structural "this edge can't exist" error precedes the
11004        // narrower payload-shape diagnostics: a self-edge carrying an
11005        // otherwise-malformed endpoint still reports ContratoSelfLoop,
11006        // not ContratoEndpointInvalid.
11007        let mut s = three_member_spec();
11008        s.contratos.push(WitContract {
11009            de: "cart".into(),
11010            para: "cart".into(),
11011            wit: "wasi:http/proxy".into(),
11012            endpoint: Some("not-absolute".into()),
11013            subject: None,
11014            slot: None,
11015        });
11016        match s.validate().unwrap_err() {
11017            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
11018            other => panic!("expected ContratoSelfLoop, got {other:?}"),
11019        }
11020    }
11021
11022    #[test]
11023    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
11024        // A self-edge naming a non-member reports the more fundamental
11025        // ContratoMemberMissing first (the member doesn't exist), so the
11026        // self-loop gate is reached only once both endpoints resolve.
11027        let mut s = three_member_spec();
11028        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
11029        match s.validate().unwrap_err() {
11030            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
11031            other => panic!("expected ContratoMemberMissing, got {other:?}"),
11032        }
11033    }
11034
11035    #[test]
11036    fn rejects_two_node_synchronous_cycle() {
11037        let mut s = three_member_spec();
11038        // existing edges: cart → catalog, cart → payment
11039        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
11040        s.contratos
11041            .push(contract_http("catalog", "cart", "/refresh"));
11042        let err = s.validate().unwrap_err();
11043        match err {
11044            AplicacaoError::ContratoCycle { cycle } => {
11045                // Cycle traversal should mention both endpoints, with
11046                // the back-edge target appearing as both first and last
11047                // element to close the loop.
11048                assert!(cycle.len() >= 3);
11049                assert_eq!(cycle.first(), cycle.last());
11050                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11051                assert!(body.contains("cart"));
11052                assert!(body.contains("catalog"));
11053            }
11054            other => panic!("expected ContratoCycle, got {other:?}"),
11055        }
11056    }
11057
11058    #[test]
11059    fn rejects_three_node_synchronous_cycle() {
11060        let mut s = three_member_spec();
11061        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
11062        s.contratos = vec![
11063            contract_http("catalog", "cart", "/x"),
11064            contract_http("cart", "payment", "/y"),
11065            contract_http("payment", "catalog", "/z"),
11066        ];
11067        let err = s.validate().unwrap_err();
11068        match err {
11069            AplicacaoError::ContratoCycle { cycle } => {
11070                assert_eq!(cycle.first(), cycle.last());
11071                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11072                assert_eq!(body.len(), 3);
11073                assert!(body.contains("cart"));
11074                assert!(body.contains("catalog"));
11075                assert!(body.contains("payment"));
11076            }
11077            other => panic!("expected ContratoCycle, got {other:?}"),
11078        }
11079    }
11080
11081    #[test]
11082    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
11083        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
11084        // "acyclic by construction" — so a cycle whose closing edge
11085        // is pub-sub should NOT raise ContratoCycle.
11086        let mut s = three_member_spec();
11087        s.contratos = vec![
11088            contract_http("catalog", "cart", "/x"),
11089            contract_http("cart", "payment", "/y"),
11090            // Closing edge is pub-sub — async; not a sync deadlock.
11091            WitContract {
11092                de: "payment".into(),
11093                para: "catalog".into(),
11094                wit: "nats:pub-sub".into(),
11095                endpoint: None,
11096                subject: Some("checkout.events.charge.completed".into()),
11097                slot: None,
11098            },
11099        ];
11100        s.validate().expect("pub-sub edge breaks the sync cycle");
11101    }
11102
11103    #[test]
11104    fn store_edge_counts_as_synchronous_for_cycle_detection() {
11105        // wasi:keyvalue/store is request/response; a cycle through one
11106        // *is* a sync deadlock, just like HTTP.
11107        let mut s = three_member_spec();
11108        s.contratos = vec![
11109            contract_http("catalog", "cart", "/x"),
11110            WitContract {
11111                de: "cart".into(),
11112                para: "catalog".into(),
11113                wit: "wasi:keyvalue/store".into(),
11114                endpoint: None,
11115                subject: None,
11116                slot: Some("session/$id".into()),
11117            },
11118        ];
11119        let err = s.validate().unwrap_err();
11120        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11121    }
11122
11123    #[test]
11124    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
11125        // Capability-only edges (unknown WIT shape, no payload) default
11126        // to synchronous — safer; authors with truly async capability
11127        // semantics can model them as pub-sub explicitly.
11128        let mut s = three_member_spec();
11129        s.contratos = vec![
11130            contract_http("catalog", "cart", "/x"),
11131            WitContract {
11132                de: "cart".into(),
11133                para: "catalog".into(),
11134                wit: "custom:exchange".into(),
11135                endpoint: None,
11136                subject: None,
11137                slot: None,
11138            },
11139        ];
11140        let err = s.validate().unwrap_err();
11141        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11142    }
11143
11144    #[test]
11145    fn long_acyclic_chain_validates() {
11146        // A long sync chain (no back-edges) must validate even when
11147        // every node is reachable from the first.
11148        let mut s = three_member_spec();
11149        s.membros = vec![
11150            membro("a", "^0.1"),
11151            membro("b", "^0.1"),
11152            membro("c", "^0.1"),
11153            membro("d", "^0.1"),
11154            membro("e", "^0.1"),
11155        ];
11156        s.contratos = vec![
11157            contract_http("a", "b", "/1"),
11158            contract_http("b", "c", "/2"),
11159            contract_http("c", "d", "/3"),
11160            contract_http("d", "e", "/4"),
11161        ];
11162        s.entrada.as_mut().unwrap().para = "a".into();
11163        s.validate().unwrap();
11164    }
11165
11166    #[test]
11167    fn diamond_acyclic_validates() {
11168        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
11169        let mut s = three_member_spec();
11170        s.membros = vec![
11171            membro("a", "^0.1"),
11172            membro("b", "^0.1"),
11173            membro("c", "^0.1"),
11174            membro("d", "^0.1"),
11175        ];
11176        s.contratos = vec![
11177            contract_http("a", "b", "/1"),
11178            contract_http("a", "c", "/2"),
11179            contract_http("b", "d", "/3"),
11180            contract_http("c", "d", "/4"),
11181        ];
11182        s.entrada.as_mut().unwrap().para = "a".into();
11183        s.validate().unwrap();
11184    }
11185
11186    // ── duplicate-`:contratos` build-error gate ──────────────────────────
11187
11188    #[test]
11189    fn rejects_duplicate_http_contrato() {
11190        // Fail-before-pass-after pin: the fixture's `cart → catalog`
11191        // HTTP edge appears once. Push an identical entry — same
11192        // (de, para, wit, endpoint) — and validate() must reject it.
11193        // Until this gate landed the typed surface accepted the
11194        // duplicate silently and caixa-mesh's `cilium_network_policies`
11195        // emitted two ``CiliumNetworkPolicy`` objects with identical
11196        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
11197        // admission rejects on `kubectl apply` far from the source.
11198        let mut s = three_member_spec();
11199        s.contratos
11200            .push(contract_http("cart", "catalog", "/products/:id"));
11201        let err = s.validate().unwrap_err();
11202        assert!(
11203            matches!(
11204                err,
11205                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11206                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
11207            ),
11208            "got {err:?}"
11209        );
11210    }
11211
11212    #[test]
11213    fn rejects_duplicate_pubsub_contrato() {
11214        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
11215        // edges with identical (de, para, subject) are degenerate;
11216        // pin that the typed surface refuses both at validate time.
11217        let mut s = three_member_spec();
11218        let pubsub = WitContract {
11219            de: "payment".into(),
11220            para: "cart".into(),
11221            wit: "nats:pub-sub".into(),
11222            endpoint: None,
11223            subject: Some("checkout.events.charge.failed".into()),
11224            slot: None,
11225        };
11226        s.contratos.push(pubsub.clone());
11227        s.contratos.push(pubsub);
11228        let err = s.validate().unwrap_err();
11229        assert!(
11230            matches!(
11231                err,
11232                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11233                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
11234            ),
11235            "got {err:?}"
11236        );
11237    }
11238
11239    #[test]
11240    fn rejects_duplicate_store_contrato() {
11241        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
11242        // edges with identical (de, para, slot) collapse to one mesh-
11243        // policy edge; pin the build error.
11244        let mut s = three_member_spec();
11245        let store = WitContract {
11246            de: "cart".into(),
11247            para: "payment".into(),
11248            wit: "wasi:keyvalue/store".into(),
11249            endpoint: None,
11250            subject: None,
11251            slot: Some("checkout/$orderId".into()),
11252        };
11253        // Drop the conflicting HTTP `cart → payment` edge from the
11254        // fixture so the duplicate-store pair is the only one
11255        // distinguishable on this pair.
11256        s.contratos
11257            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11258        s.contratos.push(store.clone());
11259        s.contratos.push(store);
11260        let err = s.validate().unwrap_err();
11261        assert!(
11262            matches!(
11263                err,
11264                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11265                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
11266            ),
11267            "got {err:?}"
11268        );
11269    }
11270
11271    #[test]
11272    fn rejects_duplicate_capability_contrato() {
11273        // Same gate on the pure-capability axis (no payload selector).
11274        // Two contracts with identical (de, para, wit) and no
11275        // endpoint/subject/slot are duplicate edges; pin so a future
11276        // `target_label` change can't accidentally collapse the
11277        // capability arm into a None-shaped key that compares equal
11278        // to a populated one.
11279        let mut s = three_member_spec();
11280        let capability = WitContract {
11281            de: "cart".into(),
11282            para: "catalog".into(),
11283            wit: "pleme:cap/audit".into(),
11284            endpoint: None,
11285            subject: None,
11286            slot: None,
11287        };
11288        s.contratos.push(capability.clone());
11289        s.contratos.push(capability);
11290        let err = s.validate().unwrap_err();
11291        match err {
11292            AplicacaoError::ContratoDuplicate {
11293                de,
11294                para,
11295                wit,
11296                target,
11297            } => {
11298                assert_eq!(de, "cart");
11299                assert_eq!(para, "catalog");
11300                assert_eq!(wit, "pleme:cap/audit");
11301                assert!(
11302                    target.contains("capability"),
11303                    "capability-edge duplicate diagnostic must surface the \
11304                     no-payload shape (got target = {target:?})"
11305                );
11306            }
11307            other => panic!("expected ContratoDuplicate, got {other:?}"),
11308        }
11309    }
11310
11311    #[test]
11312    fn accepts_distinct_http_paths_between_same_pair() {
11313        // Negative pin: two HTTP contracts cart → catalog at distinct
11314        // endpoints (`/products/:id` and `/search`) are *not*
11315        // duplicates — they're distinct typed edges differing on the
11316        // payload axis. The duplicate-gate must not over-match here,
11317        // since the cart-calls-catalog-on-multiple-paths shape is the
11318        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
11319        // example: cart calls catalog at /products/:id, payment at
11320        // /charge — same shape extends to two paths on one para).
11321        let mut s = three_member_spec();
11322        s.contratos
11323            .push(contract_http("cart", "catalog", "/search"));
11324        s.validate()
11325            .expect("distinct endpoints between same (de, para) must validate");
11326    }
11327
11328    #[test]
11329    fn accepts_same_endpoint_on_different_pairs() {
11330        // Negative pin: the same `/charge` endpoint reused on two
11331        // different (de, para) pairs is two distinct edges, not a
11332        // duplicate. Pinning this shape so the gate's identity key
11333        // includes both `de` and `para` (not just `(wit, endpoint)`).
11334        let mut s = three_member_spec();
11335        s.contratos
11336            .push(contract_http("payment", "catalog", "/charge"));
11337        s.validate()
11338            .expect("same endpoint reused on distinct (de, para) must validate");
11339    }
11340
11341    #[test]
11342    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
11343        // Pin the diagnostic shape: the duplicate-edge error names
11344        // *which* target field carried the conflict, so the author
11345        // doesn't have to re-grep the source caixa.lisp to find it.
11346        // Same self-locating diagnostic discipline as
11347        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11348        let mut s = three_member_spec();
11349        s.contratos
11350            .push(contract_http("cart", "catalog", "/products/:id"));
11351        let err = s.validate().unwrap_err();
11352        let msg = format!("{err}");
11353        assert!(
11354            msg.contains("\"/products/:id\""),
11355            "duplicate-contrato diagnostic must name the offending \
11356             :endpoint payload (got: {msg:?})"
11357        );
11358        assert!(
11359            msg.contains("cart") && msg.contains("catalog"),
11360            "diagnostic must name both endpoints of the duplicate edge \
11361             (got: {msg:?})"
11362        );
11363    }
11364
11365    #[test]
11366    fn duplicate_contrato_gate_runs_after_membership_check() {
11367        // Order pin: a duplicate contract whose `:de` is *also* not in
11368        // `:membros` surfaces the membership error first — the
11369        // missing-member diagnostic is more locating than the
11370        // duplicate-edge one (the author has to fix the membership
11371        // before the duplicate is meaningful). Same ordering
11372        // discipline as `membros_validation_runs_before_contratos_membership_check`.
11373        let mut s = three_member_spec();
11374        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11375        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11376        let err = s.validate().unwrap_err();
11377        assert!(
11378            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11379            "membership-missing must fire before duplicate-edge (got {err:?})"
11380        );
11381    }
11382
11383    #[test]
11384    fn duplicate_contrato_gate_runs_after_target_shape_check() {
11385        // Order pin: a contract with a malformed target (e.g. an HTTP
11386        // wit world with an empty :endpoint) surfaces the target-shape
11387        // error first, not the duplicate one. Even when two such
11388        // malformed entries are identical, the per-contract `target()`
11389        // check fires inside the loop *before* the duplicate-key
11390        // insert, so the diagnostic remains the most-locating one.
11391        let mut s = three_member_spec();
11392        let malformed = WitContract {
11393            de: "cart".into(),
11394            para: "catalog".into(),
11395            wit: "wasi:http/proxy".into(),
11396            endpoint: Some(String::new()),
11397            subject: None,
11398            slot: None,
11399        };
11400        s.contratos.push(malformed.clone());
11401        s.contratos.push(malformed);
11402        let err = s.validate().unwrap_err();
11403        assert!(
11404            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11405            "endpoint-empty must fire before duplicate-edge (got {err:?})"
11406        );
11407    }
11408
11409    #[test]
11410    fn wit_target_label_pins_per_variant_format() {
11411        // Label format is the single source of truth every duplicate-
11412        // `:contratos` diagnostic + every future `feira app graph`
11413        // consumer routes through. Pin the shape per variant so a
11414        // future edit to `WitTarget::label` (e.g. a JSON emitter that
11415        // strips the leading `:`, or a rename from `endpoint` →
11416        // `path`) surfaces as a red-red test rather than as a silent
11417        // downstream diagnostic drift. Together with the exhaustive
11418        // `match` on `WitTarget` inside `label()`, adding a future
11419        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
11420        // peer, per-edge WIT registry variants) is a compile error at
11421        // the label site — not a fall-through into the `Capability`
11422        // "no payload" default the prior raw-field-probe helper
11423        // silently landed on.
11424        assert_eq!(
11425            WitTarget::Http {
11426                endpoint: "/charge",
11427            }
11428            .label(),
11429            "\
11430:endpoint \"/charge\""
11431        );
11432        assert_eq!(
11433            WitTarget::PubSub {
11434                subject: "events.checkout.paid",
11435            }
11436            .label(),
11437            "\
11438:subject \"events.checkout.paid\""
11439        );
11440        assert_eq!(
11441            WitTarget::Store {
11442                slot: "checkout/$order",
11443            }
11444            .label(),
11445            "\
11446:slot \"checkout/$order\""
11447        );
11448        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
11449        // Capability-arm label routes through the lifted
11450        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
11451        // declaration per arm, next to the variant" discipline the
11452        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
11453        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11454        // consts already carry extends to the payload-less arm; the
11455        // byte-string equality pin below plus this label-routes-
11456        // through-the-const pin make a future rebrand on either the
11457        // const declaration or the `label()` template a build error
11458        // here rather than a downstream consumer surprise.
11459        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
11460        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
11461    }
11462
11463    #[test]
11464    fn wit_target_display_routes_through_label_helper() {
11465        // Fail-before-pass-after pin on the fourth (and only remaining)
11466        // typed-shape-discriminator axis to converge onto the
11467        // three-path-convergence discipline the sibling M3
11468        // [`PlacementStrategy`] (0a2f653) and M2
11469        // [`crate::supervisor::RestartStrategy`] /
11470        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
11471        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
11472        // through [`WitTarget::label`], so every consumer reaching for
11473        // `format!("{v}")` on a typed payload target lands on the same
11474        // stable author-facing byte-string [`WitTarget::label`] returns
11475        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
11476        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
11477        // `:contratos` gate seeds via [`WitTarget::label`] at
11478        // aplicacao.rs:5491 already threads through.
11479        //
11480        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11481        // through to the `Debug` derive's structural output
11482        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11483        // rather than the [`WitTarget::label`] helper's stable byte-
11484        // string (`:endpoint "/charge"` — the author-facing `:contratos`
11485        // keyword form). Every future consumer that reaches for
11486        // `format!("{target}")` — the canonical shape every user-facing
11487        // pretty-print site on the sibling typed-enum axes
11488        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11489        // [`crate::supervisor::RestartPolicy`]) already uses — would
11490        // silently land under a different byte-string than the
11491        // [`WitTarget::label`] callers that the duplicate-`:contratos`
11492        // diagnostic already threads through, with the mismatch
11493        // surfacing as a downstream diagnostic / graph / audit line
11494        // reading one spelling while the substrate's own gate emitted
11495        // another.
11496        //
11497        // Pin the routing here so a future
11498        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11499        // that hand-rolls the per-arm formatting instead of delegating
11500        // to [`WitTarget::label`] fails at caixa-core build time.
11501        for variant in [
11502            WitTarget::Http {
11503                endpoint: "/charge",
11504            },
11505            WitTarget::PubSub {
11506                subject: "events.checkout.paid",
11507            },
11508            WitTarget::Store {
11509                slot: "checkout/$order",
11510            },
11511            WitTarget::Capability,
11512        ] {
11513            assert_eq!(
11514                variant.to_string(),
11515                variant.label(),
11516                "WitTarget::{variant:?} Display must route through \
11517                 WitTarget::label (single source of truth: the lifted \
11518                 payload_pair 4-arm dispatch the label helper already \
11519                 threads through)"
11520            );
11521        }
11522    }
11523
11524    #[test]
11525    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11526        // Consumer-side pin on the three-path convergence:
11527        // [`std::fmt::Display`] agrees byte-for-byte with the
11528        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11529        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11530        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11531        // Pre-lift the two paths were structurally independent — the
11532        // substrate-side gate reached for `target_view.label()` while a
11533        // future downstream diagnostic / graph / audit line reaching
11534        // for `format!("{target}")` would silently land on the `Debug`
11535        // derive's structural output. Pin the two paths byte-for-byte
11536        // here so any future variant addition (M4 `Rest`/`Grpc` split
11537        // of [`WitTarget::Http`], `Queue`-shaped peer of
11538        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11539        // match error at [`WitTarget::payload_pair`] rather than a
11540        // silent per-consumer dispatch miss.
11541        for variant in [
11542            WitTarget::Http {
11543                endpoint: "/charge",
11544            },
11545            WitTarget::PubSub {
11546                subject: "events.checkout.paid",
11547            },
11548            WitTarget::Store {
11549                slot: "checkout/$order",
11550            },
11551            WitTarget::Capability,
11552        ] {
11553            assert_eq!(
11554                format!("{variant}"),
11555                variant.label(),
11556                "WitTarget::{variant:?} Display byte-string must match \
11557                 the AplicacaoError::ContratoDuplicate `target:` carrier \
11558                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11559                 seeds via WitTarget::label — three-path convergence: \
11560                 Display + label + payload_pair all resolve to the same \
11561                 per-arm byte-string"
11562            );
11563        }
11564    }
11565
11566    #[test]
11567    fn wit_target_payload_pair_pins_per_variant() {
11568        // Pin the per-arm `(field-name, payload)` pair single-sourced
11569        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11570        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11571        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11572        // and [`WitTarget::field_name`] (returns the first component)
11573        // route through. Until this lift landed [`WitTarget::label`]
11574        // dispatched on the same three arms with a per-arm
11575        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11576        // paired [`WitTarget::HTTP_FIELD_NAME`] /
11577        // [`WitTarget::PUBSUB_FIELD_NAME`] /
11578        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11579        // canonical "same shape, written N times" duplication
11580        // THEORY.md §I.3.5 promotes to a build-time concern. A future
11581        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11582        // [`WitTarget::Http`], `Queue`-shaped peer of
11583        // [`WitTarget::Store`]) is one match-arm edit at
11584        // [`WitTarget::payload_pair`], visible here as a compile-time
11585        // exhaustiveness error on both this pin and the label-format
11586        // pin above.
11587        assert_eq!(
11588            WitTarget::Http {
11589                endpoint: "/charge"
11590            }
11591            .payload_pair(),
11592            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11593        );
11594        assert_eq!(
11595            WitTarget::PubSub {
11596                subject: "events.x",
11597            }
11598            .payload_pair(),
11599            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11600        );
11601        assert_eq!(
11602            WitTarget::Store {
11603                slot: "checkout/$order",
11604            }
11605            .payload_pair(),
11606            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11607        );
11608        assert_eq!(WitTarget::Capability.payload_pair(), None);
11609    }
11610
11611    #[test]
11612    fn wit_target_field_name_pins_per_variant() {
11613        // Pin the per-arm author-facing `:contratos` payload field
11614        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11615        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11616        // + returned by [`WitTarget::field_name`]. Every downstream
11617        // consumer (the [`WitContract::target`] gate's `expected:`
11618        // scalar, the [`WitTarget::label`] template's keyword prefix,
11619        // the `feira app graph` verb's `endpoint=…` prefix) routes
11620        // through the same three peer consts, so a rename on the
11621        // author-surface `(defcaixa … :contratos ((:de … :para …
11622        // :wit … :endpoint …)))` field lands in exactly one place.
11623        assert_eq!(
11624            WitTarget::Http {
11625                endpoint: "/charge"
11626            }
11627            .field_name(),
11628            Some(WitTarget::HTTP_FIELD_NAME),
11629        );
11630        assert_eq!(
11631            WitTarget::PubSub {
11632                subject: "events.x",
11633            }
11634            .field_name(),
11635            Some(WitTarget::PUBSUB_FIELD_NAME),
11636        );
11637        assert_eq!(
11638            WitTarget::Store {
11639                slot: "checkout/$order",
11640            }
11641            .field_name(),
11642            Some(WitTarget::STORE_FIELD_NAME),
11643        );
11644        // Capability arm carries no payload field — the diagnostic
11645        // never reports `expected: "capability"` because the gate's
11646        // Capability arm accepts no payload at all (it fires the
11647        // "expected: none" WrongTarget error instead), so the field-
11648        // name method returns None here rather than a placeholder.
11649        assert_eq!(WitTarget::Capability.field_name(), None);
11650
11651        // Peer const scalar values pinned so a rename on either side
11652        // (author-surface field name in the `(defcaixa …)` DSL, or
11653        // the diagnostic's `expected:` scalar) can't drift without
11654        // failing here first.
11655        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11656        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11657        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11658    }
11659
11660    #[test]
11661    fn wit_target_payload_pins_per_variant() {
11662        // Pin the per-arm payload scalar single-sourced onto the
11663        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
11664        // [`WitTarget::payload`] — the peer per-half projection to
11665        // [`WitTarget::field_name`] on the paired sub-selector axis. The
11666        // three payload-carrying arms round-trip their author-declared
11667        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
11668        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
11669        // the payload-less [`WitTarget::Capability`] arm returns `None`.
11670        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
11671        // (c6ec2af) pin on the Component-0 projection axis, extended
11672        // onto the Component-1 projection axis so both per-half readers
11673        // on the paired dispatch carry their own byte-shape pin.
11674        assert_eq!(
11675            WitTarget::Http {
11676                endpoint: "/charge",
11677            }
11678            .payload(),
11679            Some("/charge"),
11680        );
11681        assert_eq!(
11682            WitTarget::PubSub {
11683                subject: "events.x",
11684            }
11685            .payload(),
11686            Some("events.x"),
11687        );
11688        assert_eq!(
11689            WitTarget::Store {
11690                slot: "checkout/$order",
11691            }
11692            .payload(),
11693            Some("checkout/$order"),
11694        );
11695        assert_eq!(WitTarget::Capability.payload(), None);
11696    }
11697
11698    #[test]
11699    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
11700        // Per-variant equivalence pin: for every arm of [`WitTarget`],
11701        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
11702        // byte-for-byte. Guards the drift surface where a future refactor
11703        // that split one accessor off the shared match onto its own
11704        // dispatch — a well-meaning "inline the pair back into per-half
11705        // fields for one crate-internal caller who only wanted one half"
11706        // or a scratch `impl` shadowing the derived projection — would
11707        // silently desynchronize [`WitTarget::payload`] from the
11708        // authoritative [`WitTarget::payload_pair`] dispatch, and every
11709        // downstream consumer that thinks "the payload half of the pair"
11710        // would drift from the diagnostic / graph consumers reading the
11711        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
11712        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
11713        // per-half projection pin (`gitrefspec_ref_pair_projects_
11714        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
11715        // FluxCD source-controller `spec.ref.<field>` axis — same "one
11716        // paired dispatch, both per-half projections agree byte-for-
11717        // byte" discipline extended onto the M3 `:contratos` payload-
11718        // arm surface.
11719        for variant in [
11720            WitTarget::Http {
11721                endpoint: "/charge",
11722            },
11723            WitTarget::PubSub {
11724                subject: "events.checkout.paid",
11725            },
11726            WitTarget::Store {
11727                slot: "checkout/$order",
11728            },
11729            WitTarget::Capability,
11730        ] {
11731            let via_projection = variant.payload();
11732            let via_pair = variant.payload_pair().map(|(_, p)| p);
11733            assert_eq!(
11734                via_projection, via_pair,
11735                "WitTarget::{variant:?} payload() must equal \
11736                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
11737                 regression that splits the two per-half projections off \
11738                 their shared match would silently desynchronize the \
11739                 payload accessor from the paired dispatch every \
11740                 diagnostic / graph consumer reads through",
11741            );
11742        }
11743    }
11744
11745    #[test]
11746    fn wit_target_http_endpoint_pins_per_variant() {
11747        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
11748        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
11749        // substrate-primitive per-arm post-projection accessor every
11750        // L7-HTTP-facing consumer routes through, sibling to the peer
11751        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
11752        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
11753        // arm round-trips its author-declared endpoint verbatim as
11754        // `Some("/charge")`; the three sibling arms
11755        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
11756        // [`WitTarget::Capability`]) each return `None` because they
11757        // carry no HTTP endpoint by definition. Same fail-before-pass-
11758        // after per-variant discipline as the sibling
11759        // `wit_target_payload_pins_per_variant` (5d6dc92) /
11760        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
11761        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
11762        // the peer pan-arm / per-half projection axes — extended onto
11763        // the per-arm HTTP-shape post-projection axis so a future
11764        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
11765        // [`WitTarget::Http`], a `Queue`-shaped peer of
11766        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
11767        // error on the sibling [`WitTarget::http_endpoint`] match arms
11768        // whose payload the L7-HTTP-shape accept-set is meant to bound.
11769        assert_eq!(
11770            WitTarget::Http {
11771                endpoint: "/charge",
11772            }
11773            .http_endpoint(),
11774            Some("/charge"),
11775        );
11776        assert_eq!(
11777            WitTarget::PubSub {
11778                subject: "events.checkout.paid",
11779            }
11780            .http_endpoint(),
11781            None,
11782        );
11783        assert_eq!(
11784            WitTarget::Store {
11785                slot: "checkout/$order",
11786            }
11787            .http_endpoint(),
11788            None,
11789        );
11790        assert_eq!(WitTarget::Capability.http_endpoint(), None);
11791    }
11792
11793    #[test]
11794    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
11795        // Per-variant coherence pin: for every arm of [`WitTarget`],
11796        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
11797        // arm (both project the same author-declared request-path
11798        // scalar), and returns `None` on every sibling arm regardless of
11799        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
11800        // Store carry their own payload the pan-arm accessor surfaces,
11801        // but that payload is not an HTTP endpoint — the per-arm
11802        // accessor must not leak it through the HTTP-shape channel).
11803        // Guards the drift surface where a future refactor that
11804        // conflated the per-arm HTTP projection with the pan-arm
11805        // [`WitTarget::payload`] projection — a well-meaning "one
11806        // accessor for the L7 branch, one for the graph" collapse that
11807        // routes both through the same 4-arm dispatch — would silently
11808        // widen the L7-HTTP-shape accept-set onto pub-sub / store
11809        // payloads at the caixa-mesh L7 emit branch, admitting a
11810        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
11811        // rule with the operator-side apply-time symptom (Cilium's
11812        // eBPF data-plane rejects every ingress edge whose L7 filter
11813        // doesn't match the wire-format HTTP request line) far from
11814        // the source refactor. Sibling to the peer
11815        // `wit_target_payload_matches_payload_pair_second_component_
11816        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
11817        // extended onto the per-arm HTTP specialization axis so both
11818        // the pan-arm and the per-arm projections carry their own
11819        // byte-shape coherence witness against the substrate's typed
11820        // arm-family accept-set.
11821        for variant in [
11822            WitTarget::Http {
11823                endpoint: "/charge",
11824            },
11825            WitTarget::PubSub {
11826                subject: "events.checkout.paid",
11827            },
11828            WitTarget::Store {
11829                slot: "checkout/$order",
11830            },
11831            WitTarget::Capability,
11832        ] {
11833            let per_arm = variant.http_endpoint();
11834            let pan_arm = variant.payload();
11835            if variant.is_http() {
11836                assert_eq!(
11837                    per_arm, pan_arm,
11838                    "WitTarget::{variant:?} http_endpoint() must equal \
11839                     payload() on the Http arm — a per-arm-vs-pan-arm \
11840                     split would silently drift the L7 emit branch's \
11841                     path-scalar source from the graph verb's payload \
11842                     scalar source",
11843                );
11844            } else {
11845                assert_eq!(
11846                    per_arm, None,
11847                    "WitTarget::{variant:?} http_endpoint() must return \
11848                     None on non-Http arms — a leak that surfaced a \
11849                     pub-sub :subject or a key/value :slot through the \
11850                     HTTP-endpoint accessor would silently widen the \
11851                     Cilium L7 HTTP `path:` rule accept-set onto \
11852                     protocol shapes Cilium's eBPF data-plane can't \
11853                     introspect",
11854                );
11855            }
11856        }
11857    }
11858
11859    #[test]
11860    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
11861        // Per-variant coherence pin: for every arm of [`WitTarget`],
11862        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
11863        // drift surface where a future extension of the
11864        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
11865        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
11866        // accessor to cover both peers) landed without a paired
11867        // extension of the [`gen_platform::IsVariant`]-derived
11868        // `is_http()` predicate's accept-set, or vice versa — a
11869        // regression that split the "which arms count as HTTP-shaped
11870        // for L7-path emission?" answer between two dispatch surfaces
11871        // the substrate ships. Sibling to the peer
11872        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
11873        // on the paired dispatch axis — extended onto the per-arm
11874        // predicate-vs-accessor coherence axis so the gen-platform
11875        // IsVariant predicate and the substrate-lifted per-arm
11876        // accessor carry one shared answer to "is this the HTTP arm?".
11877        for variant in [
11878            WitTarget::Http {
11879                endpoint: "/charge",
11880            },
11881            WitTarget::PubSub {
11882                subject: "events.checkout.paid",
11883            },
11884            WitTarget::Store {
11885                slot: "checkout/$order",
11886            },
11887            WitTarget::Capability,
11888        ] {
11889            assert_eq!(
11890                variant.http_endpoint().is_some(),
11891                variant.is_http(),
11892                "WitTarget::{variant:?} http_endpoint().is_some() must \
11893                 equal is_http() — a drift would split the L7 emit \
11894                 branch's arm-set gate from the substrate-derived \
11895                 shape-discrimination predicate on the same axis",
11896            );
11897        }
11898    }
11899
11900    #[test]
11901    fn wit_target_field_names_are_pairwise_distinct() {
11902        // Distinctness pin: if any two of the three payload-field-name
11903        // scalars ever collapse (e.g. an accidental `endpoint` copy-
11904        // paste over the `subject` const), the [`WitContract::target`]
11905        // gate's diagnostic would point authors at the wrong field —
11906        // an "expected `:endpoint`" error on a pub-sub edge would
11907        // silently misroute the fix. Same cross-axis-distinctness
11908        // discipline as the peer M3 `:placement :estrategia` variant-
11909        // discriminator scalar-value pins (cc8f749) applied to the
11910        // payload-field-name axis.
11911        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11912        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11913        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11914    }
11915
11916    #[test]
11917    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
11918        // Fail-before-pass-after pin: the graph-verb payload column's
11919        // per-arm `{field}={payload}` byte-string is derived through the
11920        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
11921        // payload-carrying arms, not through a hand-rolled per-arm match
11922        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
11923        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11924        // inline. A future variant addition — the M4-and-later per-edge
11925        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
11926        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
11927        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
11928        // and both [`WitTarget::label`] (duplicate-`:contratos`
11929        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
11930        // payload column) pick up the new arm from the same dispatch.
11931        // Prior to this lift the graph verb open-coded the 4-arm match
11932        // in caixa-feira, so a variant addition would have to be threaded
11933        // through both projections in lockstep or the graph verb would
11934        // silently drop the new arm to `(capability-only)`.
11935        for variant in [
11936            WitTarget::Http {
11937                endpoint: "/charge",
11938            },
11939            WitTarget::PubSub {
11940                subject: "events.checkout.paid",
11941            },
11942            WitTarget::Store {
11943                slot: "checkout/$order",
11944            },
11945        ] {
11946            let (field, payload) = variant
11947                .payload_pair()
11948                .expect("payload arm must expose (field, payload)");
11949            assert_eq!(
11950                variant.graph_label(),
11951                format!("{field}={payload}"),
11952                "WitTarget::{variant:?} graph_label must route the \
11953                 `{{field}}={{payload}}` template through payload_pair — \
11954                 a regression to a hand-rolled per-arm match at the graph \
11955                 verb would silently disagree with a future variant \
11956                 addition landed only at payload_pair"
11957            );
11958        }
11959    }
11960
11961    #[test]
11962    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
11963        // Fail-before-pass-after pin on the payload-less arm: the graph
11964        // verb's `(capability-only)` byte-string routes through the
11965        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
11966        // [`WitTarget::Capability`] arm, not through an inline
11967        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
11968        // per-`:contratos` payload column. Peer of the sibling
11969        // [`wit_target_label_pins_per_variant_format`] Capability-arm
11970        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
11971        // extended here onto the third payload-less-arm consumer axis
11972        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
11973        // axis and the wrong-target diagnostic axis).
11974        assert_eq!(
11975            WitTarget::Capability.graph_label(),
11976            WitTarget::CAPABILITY_GRAPH_LABEL,
11977        );
11978        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
11979    }
11980
11981    #[test]
11982    fn wit_target_capability_graph_label_distinct_from_capability_label() {
11983        // Cross-consumer-axis distinctness pin: the graph-verb
11984        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
11985        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
11986        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
11987        // payload)`) surface the payload-less arm on two distinct
11988        // consumer axes; a collapse (an accidental rebrand that lands
11989        // one spelling on both consts, a copy-paste that unifies them
11990        // "for consistency") would silently merge the two byte-strings
11991        // and lose the vocabulary distinction the graph verb's
11992        // compact-column form and the diagnostic's descriptive-clause
11993        // form each carry on purpose. Peer of the sibling 4-way
11994        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
11995        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
11996        // extended here onto the cross-consumer-axis distinctness of the
11997        // two payload-less-arm consts.
11998        assert_ne!(
11999            WitTarget::CAPABILITY_GRAPH_LABEL,
12000            WitTarget::CAPABILITY_LABEL,
12001            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
12002             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
12003             diagnostic) must remain distinct — a collapse would silently \
12004             merge two consumer axes onto one spelling"
12005        );
12006    }
12007
12008    #[test]
12009    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
12010        // 4-way distinctness pin extending the sibling
12011        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
12012        // (which covers only the HTTP / PubSub / Store payload arms)
12013        // onto the fourth scalar the shared
12014        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
12015        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
12016        // (`"none"`), the payload-less Capability-arm rejection scalar.
12017        //
12018        // All four [`WitTarget::HTTP_FIELD_NAME`] /
12019        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12020        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
12021        // dispatch surface [`WitContract::target`] writes onto the
12022        // `ContratoWrongTarget::expected` field — the same `&'static
12023        // str` axis authors read as "this WIT world's shape admits
12024        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
12025        // downstream consumers rely on: an `expected: "endpoint"`
12026        // diagnostic on a Capability-shaped edge tells the author to
12027        // add a `:endpoint "…"` slot to a WIT world that admits none,
12028        // silently misrouting the fix. Until this pin landed the three
12029        // payload-arm consts were distinctness-guarded by the sibling
12030        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
12031        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
12032        // author-facing vocabulary shift from `"none"` to `"endpoint"`
12033        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
12034        // into per-shape peers) would have silently landed one
12035        // Capability-arm rejection on a payload-arm's `expected:` byte-
12036        // string and desynchronized the diagnostic from the author's
12037        // typed shape.
12038        //
12039        // Same 4-way pairwise-distinctness pin discipline as the peer
12040        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
12041        // (cc8f749) applies on the sibling M3 closed-set typed-enum
12042        // scalar-value dispatch axis; extends the pin trajectory the
12043        // sibling `wit_target_field_names_are_pairwise_distinct`
12044        // 3-way pin opened to cover the last unguarded corner on the
12045        // `ContratoWrongTarget::expected` scalar-value axis.
12046        //
12047        // Fail-before-pass-after locally verified by mutating
12048        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
12049        // — this pin fires as expected; restoring passes.
12050        let all = [
12051            WitTarget::HTTP_FIELD_NAME,
12052            WitTarget::PUBSUB_FIELD_NAME,
12053            WitTarget::STORE_FIELD_NAME,
12054            WitTarget::CAPABILITY_EXPECTED,
12055        ];
12056        for (i, a) in all.iter().enumerate() {
12057            for (j, b) in all.iter().enumerate() {
12058                if i != j {
12059                    assert_ne!(
12060                        a, b,
12061                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
12062                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
12063                         pairwise distinct — got duplicate {a:?} at indices \
12064                         {i} and {j}; all four scalars thread through the \
12065                         shared `AplicacaoError::ContratoWrongTarget::expected` \
12066                         &'static str axis, so a collapse silently misdirects \
12067                         the diagnostic on which typed shape the WIT world admits",
12068                    );
12069                }
12070            }
12071        }
12072    }
12073
12074    #[test]
12075    fn wit_target_is_variant_predicates_partition_the_arm_set() {
12076        // Fail-before-pass-after pin on the
12077        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
12078        // each of the four variants exactly one of the generated
12079        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
12080        // predicates returns `true` and the other three return
12081        // `false`. Prior to this derive the only production
12082        // arm-discriminator on [`WitTarget`] — the sync-cycle
12083        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
12084        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
12085        // the variant that expressed no compile-time link back to
12086        // the closed-set typed dispatch a future fifth
12087        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
12088        // split of [`WitTarget::PubSub`] into shape-specific peers,
12089        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
12090        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
12091        // to thread through in lockstep or the DFS exclusion would
12092        // silently disagree with the peer diagnostic templates on
12093        // which arms carry sync-versus-async semantics. Peer of the
12094        // sibling [`crate::CaixaKind`] (f5bba80),
12095        // [`PlacementStrategy`] (766ec63),
12096        // [`crate::supervisor::RestartStrategy`],
12097        // [`crate::supervisor::RestartPolicy`], and
12098        // [`crate::upgrade::UpgradeInstruction`] (915a934)
12099        // `IsVariant` derives on the sibling closed-set typed-enum
12100        // discriminator axes — extends the same one-typed-dispatch-
12101        // per-variant discipline onto the last unlifted closed-set
12102        // typed-enum discriminator on the caixa surface (the M3
12103        // mesh-slot per-`:contratos` target-arm axis), closing the
12104        // arm-discriminator convergence trajectory across every
12105        // closed-set typed enum in caixa-core.
12106        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
12107            (
12108                WitTarget::Http { endpoint: "/x" },
12109                [true, false, false, false],
12110            ),
12111            (
12112                WitTarget::PubSub {
12113                    subject: "events.x",
12114                },
12115                [false, true, false, false],
12116            ),
12117            (
12118                WitTarget::Store { slot: "kv/x" },
12119                [false, false, true, false],
12120            ),
12121            (WitTarget::Capability, [false, false, false, true]),
12122        ];
12123        for (variant, expected) in rows {
12124            let observed = [
12125                variant.is_http(),
12126                variant.is_pubsub(),
12127                variant.is_store(),
12128                variant.is_capability(),
12129            ];
12130            assert_eq!(
12131                observed, expected,
12132                "WitTarget::{variant:?} is_* predicates must partition \
12133                 the arm set (http, pubsub, store, capability); got {observed:?}"
12134            );
12135        }
12136    }
12137
12138    #[test]
12139    fn wit_target_is_variant_predicates_are_const_fn() {
12140        // The [`gen_platform::IsVariant`] derive emits `const fn`
12141        // predicates on the peer [`crate::CaixaKind`] +
12142        // [`crate::upgrade::UpgradeInstruction`] +
12143        // [`crate::supervisor::RestartStrategy`] +
12144        // [`crate::supervisor::RestartPolicy`] +
12145        // [`PlacementStrategy`] closed-set typed enums — pin the
12146        // same posture on [`WitTarget`] so a future accidental
12147        // downgrade to non-`const` (an added runtime helper reachable
12148        // only from a non-`const` context, a manual hand-rolled
12149        // `impl` that shadows the derive-generated method) trips at
12150        // caixa-core build time rather than surfacing as a downstream
12151        // `const`-context regression far from the derive declaration.
12152        //
12153        // Unlike the peer unit-variant enums (`CaixaKind` /
12154        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
12155        // whose `const` constructors need no arguments, the three
12156        // payload-carrying [`WitTarget`] arms are const-constructed
12157        // through `&'static str` payloads — the same `'static`
12158        // lifetime the closed-set typed enum's four-arm partition
12159        // pin above already threads through.
12160        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
12161        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
12162        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
12163        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
12164        const IS_HTTP: bool = HTTP.is_http();
12165        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
12166        const IS_STORE: bool = STORE.is_store();
12167        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
12168        assert!(IS_HTTP);
12169        assert!(IS_PUBSUB);
12170        assert!(IS_STORE);
12171        assert!(IS_CAPABILITY);
12172    }
12173
12174    #[test]
12175    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
12176        // Consumer-side pin on the sole production converge site:
12177        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
12178        // edges from the synchronous-subgraph DFS via the lifted
12179        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
12180        // predicate (rebound from the prior raw
12181        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
12182        // variant). Byte-equivalent today (`is_pubsub` is the
12183        // derive-generated `matches!(self, Self::PubSub { .. })` by
12184        // construction, the `#[is_variant(name = "pubsub")]` override
12185        // aliasing the auto-derived `is_pub_sub` back to the sibling
12186        // [`WitContract::is_pubsub`] name); pin the behavior so a
12187        // future accidental drift (a rebind onto a peer arm
12188        // predicate, a manual hand-rolled `impl` that shadows the
12189        // derive-generated method with different semantics, a peer
12190        // arm rename that shifts which variant carries sync-versus-
12191        // async semantics) trips at caixa-core test time rather than
12192        // at some downstream operator's runtime dispatch far from the
12193        // rebind commit.
12194        //
12195        // The fixture constructs a two-Servico Aplicacao with one
12196        // pub-sub edge that would close a sync-cycle if the DFS did
12197        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
12198        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
12199        // edge, which is not a cycle. A regression in the converge
12200        // (a rebind that reads the pub-sub arm as sync) would report
12201        // `AplicacaoError::ContratoCycle`.
12202        let s = AplicacaoSpec {
12203            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
12204            contratos: vec![
12205                // Pub-sub edge: DFS must skip via is_pubsub().
12206                WitContract {
12207                    de: "a".into(),
12208                    para: "b".into(),
12209                    wit: "nats:pub-sub".into(),
12210                    endpoint: None,
12211                    subject: Some("events.x".into()),
12212                    slot: None,
12213                },
12214                // HTTP edge: DFS must include.
12215                WitContract {
12216                    de: "b".into(),
12217                    para: "a".into(),
12218                    wit: "wasi:http/proxy".into(),
12219                    endpoint: Some("/x".into()),
12220                    subject: None,
12221                    slot: None,
12222                },
12223            ],
12224            politicas: MeshPolicy::default(),
12225            placement: Placement {
12226                estrategia: PlacementStrategy::Replicated,
12227                clusters: vec!["rio".into()],
12228                affinity: None,
12229                shard_key: None,
12230            },
12231            entrada: None,
12232        };
12233        s.validate()
12234            .expect("pub-sub edge must be excluded from sync-cycle DFS");
12235    }
12236
12237    #[test]
12238    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
12239        // Consumer-side pin: the same three peer consts thread through
12240        // both the [`WitTarget::label`] template (leading-`:` keyword
12241        // prefix in the duplicate-`:contratos` diagnostic) and the
12242        // [`WitContract::target`] gate's [`AplicacaoError::
12243        // ContratoMissingTarget`] `expected:` scalar (the field the
12244        // author needs to add). Pin both routes at once so a future
12245        // refactor can't accidentally split them onto separate string
12246        // literals — the "one place, everywhere reaches for it"
12247        // invariant the peer const set carries.
12248        let http_label = WitTarget::Http { endpoint: "/x" }.label();
12249        assert!(
12250            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
12251            "label must lead with :{} keyword (got {http_label:?})",
12252            WitTarget::HTTP_FIELD_NAME,
12253        );
12254
12255        let mut s = three_member_spec();
12256        s.contratos.push(WitContract {
12257            de: "cart".into(),
12258            para: "catalog".into(),
12259            wit: "kafka:topic".into(),
12260            endpoint: None,
12261            subject: None,
12262            slot: None,
12263        });
12264        match s.validate().unwrap_err() {
12265            AplicacaoError::ContratoMissingTarget { expected, .. } => {
12266                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
12267            }
12268            other => panic!("expected ContratoMissingTarget, got {other:?}"),
12269        }
12270    }
12271
12272    #[test]
12273    fn duplicate_pubsub_diagnostic_names_offending_subject() {
12274        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
12275        // on the pub-sub target axis: the duplicate-edge diagnostic
12276        // must name the `:subject` payload verbatim (not just the
12277        // `(de, para, wit)` triple). Prior to lifting the label onto
12278        // [`WitTarget::label`] the diagnostic derived the label from
12279        // raw [`WitContract`] `Option<String>` probes — a future
12280        // `WitTarget` variant addition (M4 per-edge WIT registry)
12281        // would silently fall through to the `Capability` "no
12282        // payload" default without a compiler warning. Pinning the
12283        // pub-sub arm's format closes the second of three
12284        // payload-carrying `WitTarget` arms this diagnostic threads
12285        // through.
12286        let mut s = three_member_spec();
12287        let pubsub = WitContract {
12288            de: "payment".into(),
12289            para: "cart".into(),
12290            wit: "nats:pub-sub".into(),
12291            endpoint: None,
12292            subject: Some("events.checkout.paid".into()),
12293            slot: None,
12294        };
12295        s.contratos.push(pubsub.clone());
12296        s.contratos.push(pubsub);
12297        let err = s.validate().unwrap_err();
12298        let msg = format!("{err}");
12299        assert!(
12300            msg.contains(":subject \"events.checkout.paid\""),
12301            "duplicate-pubsub diagnostic must name the offending \
12302             :subject payload (got: {msg:?})"
12303        );
12304    }
12305
12306    #[test]
12307    fn duplicate_store_diagnostic_names_offending_slot() {
12308        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
12309        // key-value target axis: the diagnostic must name the `:slot`
12310        // payload verbatim. Third of three payload-carrying
12311        // `WitTarget` arms this diagnostic threads through, closing
12312        // the per-arm label pin trilogy (`Http` — 6841,
12313        // `PubSub` + `Store` — this test + peer above).
12314        let mut s = three_member_spec();
12315        let store = WitContract {
12316            de: "cart".into(),
12317            para: "payment".into(),
12318            wit: "wasi:keyvalue/store".into(),
12319            endpoint: None,
12320            subject: None,
12321            slot: Some("checkout/$orderId".into()),
12322        };
12323        s.contratos
12324            .retain(|c| !(c.de == "cart" && c.para == "payment"));
12325        s.contratos.push(store.clone());
12326        s.contratos.push(store);
12327        let err = s.validate().unwrap_err();
12328        let msg = format!("{err}");
12329        assert!(
12330            msg.contains(":slot \"checkout/$orderId\""),
12331            "duplicate-store diagnostic must name the offending :slot \
12332             payload (got: {msg:?})"
12333        );
12334    }
12335
12336    #[test]
12337    fn rejects_entrada_path_without_leading_slash() {
12338        let mut s = three_member_spec();
12339        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
12340        let err = s.validate().unwrap_err();
12341        assert!(
12342            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
12343            "got {err:?}"
12344        );
12345    }
12346
12347    #[test]
12348    fn rejects_empty_entrada_path() {
12349        let mut s = three_member_spec();
12350        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
12351        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
12352    }
12353
12354    #[test]
12355    fn rejects_duplicate_entrada_paths() {
12356        let mut s = three_member_spec();
12357        s.entrada.as_mut().unwrap().paths = vec![
12358            "/api/cart".into(),
12359            "/api/products".into(),
12360            "/api/cart".into(),
12361        ];
12362        let err = s.validate().unwrap_err();
12363        assert!(
12364            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
12365            "got {err:?}"
12366        );
12367    }
12368
12369    #[test]
12370    fn rejects_zero_entrada_port() {
12371        let mut s = three_member_spec();
12372        s.entrada.as_mut().unwrap().port = 0;
12373        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
12374    }
12375
12376    // ── :entrada :paths value-shape gate ─────────────────────────────
12377    //
12378    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
12379    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
12380    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
12381    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
12382    // time now becomes a caixa-build-time `EntradaPathInvalid` with
12383    // the offending `:paths` entry named verbatim.
12384
12385    #[test]
12386    fn rejects_entrada_path_with_query() {
12387        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
12388        // silently passed validate and the Gateway API webhook
12389        // rejected it at apply time with no source citation.
12390        let mut s = three_member_spec();
12391        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
12392        let err = s.validate().unwrap_err();
12393        assert!(
12394            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12395                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
12396            "got {err:?}"
12397        );
12398    }
12399
12400    #[test]
12401    fn rejects_entrada_path_with_fragment() {
12402        let mut s = three_member_spec();
12403        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
12404        let err = s.validate().unwrap_err();
12405        assert!(
12406            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12407                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
12408            "got {err:?}"
12409        );
12410    }
12411
12412    #[test]
12413    fn rejects_entrada_path_with_space() {
12414        let mut s = three_member_spec();
12415        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
12416        let err = s.validate().unwrap_err();
12417        assert!(
12418            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12419                if path == "/api/my cart" && reason.contains("whitespace")),
12420            "got {err:?}"
12421        );
12422    }
12423
12424    #[test]
12425    fn rejects_entrada_path_with_tab() {
12426        let mut s = three_member_spec();
12427        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
12428        let err = s.validate().unwrap_err();
12429        assert!(
12430            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12431                if path == "/api/\tcart" && reason.contains("whitespace")),
12432            "got {err:?}"
12433        );
12434    }
12435
12436    #[test]
12437    fn rejects_entrada_path_with_control_char() {
12438        // 0x01 (SOH) — a non-whitespace control char surfaces the
12439        // distinct "control character" reason arm, separate from
12440        // the whitespace arm. Pinned so a future refactor that
12441        // collapses the two arms can't accidentally drop the more
12442        // self-locating diagnostic.
12443        let mut s = three_member_spec();
12444        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
12445        let err = s.validate().unwrap_err();
12446        assert!(
12447            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12448                if path == "/api/\x01cart" && reason.contains("control character")),
12449            "got {err:?}"
12450        );
12451    }
12452
12453    #[test]
12454    fn rejects_entrada_path_with_non_ascii() {
12455        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
12456        // unreserved-set rule rejects. The Gateway API webhook
12457        // rejects literal non-ASCII bytes; percent-encoding is the
12458        // only way to author non-ASCII in a path.
12459        let mut s = three_member_spec();
12460        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
12461        let err = s.validate().unwrap_err();
12462        assert!(
12463            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12464                if path == "/api/café" && reason.contains("non-ASCII")),
12465            "got {err:?}"
12466        );
12467    }
12468
12469    #[test]
12470    fn rejects_entrada_path_with_consecutive_slashes() {
12471        let mut s = three_member_spec();
12472        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
12473        let err = s.validate().unwrap_err();
12474        assert!(
12475            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12476                if path == "/api//cart" && reason.contains("consecutive `/`")),
12477            "got {err:?}"
12478        );
12479    }
12480
12481    #[test]
12482    fn rejects_entrada_path_with_dot_segment() {
12483        let mut s = three_member_spec();
12484        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
12485        let err = s.validate().unwrap_err();
12486        assert!(
12487            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12488                if path == "/api/./cart" && reason.contains("`.` segment")),
12489            "got {err:?}"
12490        );
12491    }
12492
12493    #[test]
12494    fn rejects_entrada_path_with_trailing_dot_segment() {
12495        // The bare `/.` and the trailing `/foo/.` are both rejected
12496        // by the Gateway API webhook; pinned separately so a future
12497        // narrowing that catches only the inner form surfaces here.
12498        let mut s = three_member_spec();
12499        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
12500        let err = s.validate().unwrap_err();
12501        assert!(
12502            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12503                if path == "/api/." && reason.contains("`.` segment")),
12504            "got {err:?}"
12505        );
12506    }
12507
12508    #[test]
12509    fn rejects_entrada_path_with_parent_segment() {
12510        let mut s = three_member_spec();
12511        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
12512        let err = s.validate().unwrap_err();
12513        assert!(
12514            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12515                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
12516            "got {err:?}"
12517        );
12518    }
12519
12520    #[test]
12521    fn rejects_entrada_path_with_trailing_parent_segment() {
12522        // Trailing `/..` — symmetric arm of the parent-segment rule,
12523        // pinned separately so a future relaxation that only checks
12524        // the inner form (`/../`) surfaces here.
12525        let mut s = three_member_spec();
12526        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
12527        let err = s.validate().unwrap_err();
12528        assert!(
12529            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12530                if path == "/api/.." && reason.contains("`..` parent-segment")),
12531            "got {err:?}"
12532        );
12533    }
12534
12535    #[test]
12536    fn rejects_entrada_path_too_long() {
12537        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
12538        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
12539        // ASCII-alphanumeric body so only the length rule fires.
12540        let mut s = three_member_spec();
12541        let big = format!("/api/{}", "a".repeat(1020));
12542        assert_eq!(big.len(), 1025);
12543        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
12544        let err = s.validate().unwrap_err();
12545        assert!(
12546            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12547                if path == &big && reason.contains("max length of 1024")),
12548            "got {err:?}"
12549        );
12550    }
12551
12552    #[test]
12553    fn entrada_path_max_length_validates() {
12554        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
12555        // maxLength cap. Boundary pin: drift in the cap surfaces here
12556        // and at `rejects_entrada_path_too_long` simultaneously.
12557        let mut s = three_member_spec();
12558        let big = format!("/api/{}", "a".repeat(1019));
12559        assert_eq!(big.len(), 1024);
12560        s.entrada.as_mut().unwrap().paths = vec![big];
12561        s.validate().unwrap();
12562    }
12563
12564    #[test]
12565    fn entrada_accepts_canonical_paths() {
12566        // Positive-control sweep — every form the Gateway API
12567        // apiserver accepts must round-trip through validate. Covers
12568        // the root catch-all, plain paths, dot-prefixed segments
12569        // (hidden-file-style, distinct from `.` and `..` segments
12570        // which are rejected), digit-bearing segments, the canonical
12571        // route-template `:param` form (`:` is RFC 3986 reserved-set
12572        // valid in paths), trailing-slash form, percent-encoded
12573        // segments, and an interior `..` *substring* (`/foo..bar` is
12574        // not the `..` segment and is allowed).
12575        for path in [
12576            "/",
12577            "/api/cart",
12578            "/healthz",
12579            "/api/.config",
12580            "/v1/products",
12581            "/products/:id",
12582            "/api/cart/",
12583            "/api/caf%C3%A9",
12584            "/foo..bar",
12585            "/...",
12586        ] {
12587            let mut s = three_member_spec();
12588            s.entrada.as_mut().unwrap().paths = vec![path.into()];
12589            s.validate()
12590                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
12591        }
12592    }
12593
12594    #[test]
12595    fn entrada_path_empty_takes_precedence_over_invalid() {
12596        // Ordering pin: `EntradaPathEmpty` is the more self-locating
12597        // diagnostic on `""` and must lead — `validate_entrada_path`
12598        // is only reached after the empty-check fires at the call
12599        // site. (The predicate itself defends against direct
12600        // invocation by returning the same error on `""`.)
12601        let mut s = three_member_spec();
12602        s.entrada.as_mut().unwrap().paths = vec!["".into()];
12603        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
12604    }
12605
12606    #[test]
12607    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
12608        // Ordering pin: a path without a leading `/` surfaces the
12609        // narrower `EntradaPathNotAbsolute` diagnostic first; the
12610        // value-shape gate is only consulted on paths that already
12611        // satisfy the absolute-prefix invariant.
12612        let mut s = three_member_spec();
12613        // `bad path` would fire the whitespace rule under the
12614        // value-shape gate, but missing-leading-`/` is the more
12615        // self-locating diagnostic.
12616        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
12617        let err = s.validate().unwrap_err();
12618        assert!(
12619            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
12620            "got {err:?}"
12621        );
12622    }
12623
12624    #[test]
12625    fn entrada_path_invalid_fires_before_duplicate_check() {
12626        // Ordering pin: a malformed path on the *first* entry of a
12627        // would-be duplicate pair fires the value-shape gate before
12628        // the duplicate gate, mirroring the
12629        // `placement_cluster_invalid_fires_before_duplicate_check`
12630        // (6cbb900) pattern on the peer axis.
12631        let mut s = three_member_spec();
12632        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
12633        let err = s.validate().unwrap_err();
12634        assert!(
12635            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
12636            "got {err:?}"
12637        );
12638    }
12639
12640    #[test]
12641    fn entrada_path_diagnostic_carries_offending_path() {
12642        // Diagnostic-shape pin — the offending path + a non-empty
12643        // reason flow through verbatim so the author can grep their
12644        // caixa.lisp for `:paths` and fix it in one edit. Same shape
12645        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
12646        let mut s = three_member_spec();
12647        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
12648        let err = s.validate().unwrap_err();
12649        match err {
12650            AplicacaoError::EntradaPathInvalid { path, reason } => {
12651                assert_eq!(path, "/api?q=1");
12652                assert!(!reason.is_empty(), "reason field must be non-empty");
12653            }
12654            other => panic!("expected EntradaPathInvalid, got {other:?}"),
12655        }
12656    }
12657
12658    #[test]
12659    fn rejects_entrada_path_with_curly_brace_template_form() {
12660        // Per-axis pin on the shared `is_gateway_api_http_path`
12661        // reserved-byte arm: the canonical "I wrote an OpenAPI
12662        // path-template `{id}` instead of the Gateway API `:id` form"
12663        // footgun the K8s apiserver would otherwise catch at admission
12664        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
12665        // landing site, far from the caixa.lisp. Surfaces as
12666        // `EntradaPathInvalid` carrying the offending path verbatim
12667        // plus the canonical `%7B`/`%7D` percent-encoding remediation
12668        // — the substrate-side `gateway_api_http_path_rejects_every_
12669        // reserved_printable_ascii_byte` predicate-level sweep pins the
12670        // full eleven-byte set; this per-axis pin confirms the
12671        // diagnostic flows through to the `EntradaPathInvalid` variant.
12672        let mut s = three_member_spec();
12673        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
12674        let err = s.validate().unwrap_err();
12675        assert!(
12676            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12677                if path == "/api/cart/{id}"
12678                    && reason.contains("reserved character")
12679                    && reason.contains("'{'")
12680                    && reason.contains("%7B")),
12681            "got {err:?}"
12682        );
12683    }
12684
12685    #[test]
12686    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
12687        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
12688        // template_form` on the sibling `:contratos :endpoint` axis.
12689        // Same shared `is_gateway_api_http_path` reserved-byte arm
12690        // fires through `ContratoEndpointInvalid`, with the offending
12691        // endpoint + `:de` + `:para` + reason flowing through verbatim.
12692        // Pins that the lifted predicate's tightening lands on both
12693        // caller axes simultaneously — one source of truth for the
12694        // Gateway API HTTPPathMatch.value accepted set.
12695        let err = contrato_endpoint_err("/api/cart/{id}");
12696        assert!(
12697            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12698                if endpoint == "/api/cart/{id}"
12699                    && reason.contains("reserved character")
12700                    && reason.contains("'{'")
12701                    && reason.contains("%7B")),
12702            "got {err:?}"
12703        );
12704    }
12705
12706    // ── :entrada :host value-shape gate ──────────────────────────────
12707    //
12708    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
12709    // the sibling `:host` axis. Every authoring footgun the K8s
12710    // Gateway API v1 apiserver would catch at admission time becomes
12711    // a caixa-build-time `EntradaHostInvalid` with the offending
12712    // `:host` named verbatim. Same diagnostic shape as
12713    // `MembroVersaoInvalid` (9888b13).
12714
12715    #[test]
12716    fn rejects_entrada_host_with_scheme() {
12717        // Fail-before-pass-after pin — pre-gate codebases silently
12718        // accepted `https://…` and the apiserver rejected it at apply
12719        // time with no source citation.
12720        let mut s = three_member_spec();
12721        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
12722        let err = s.validate().unwrap_err();
12723        assert!(
12724            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12725                if host == "https://checkout.quero.cloud"),
12726            "got {err:?}"
12727        );
12728    }
12729
12730    #[test]
12731    fn rejects_entrada_host_with_port() {
12732        // The `:8080` port suffix is the canonical "I forgot the port
12733        // belongs in `:entrada :port`" footgun. The top-level `:` arm
12734        // (introduced after the per-label loop-only impl silently
12735        // surfaced a deep "label \"cloud:8080\" contains invalid
12736        // character ':'" leak) names the canonical fix verbatim — the
12737        // `:entrada :port` slot.
12738        let mut s = three_member_spec();
12739        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12740        let err = s.validate().unwrap_err();
12741        assert!(
12742            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12743                if host == "checkout.quero.cloud:8080"
12744                && reason.contains(":entrada :port")),
12745            "got {err:?}"
12746        );
12747    }
12748
12749    #[test]
12750    fn rejects_entrada_host_with_trailing_colon() {
12751        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
12752        // edit) — the per-label loop would land it as a deep
12753        // "label \"com:\" must start and end with an alphanumeric"
12754        // / "contains invalid character ':'" leak. The top-level
12755        // `:` arm pre-empts with the canonical `:port` slot
12756        // diagnostic.
12757        let mut s = three_member_spec();
12758        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
12759        let err = s.validate().unwrap_err();
12760        assert!(
12761            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12762                if host == "checkout.quero.cloud:"
12763                && reason.contains(":entrada :port")),
12764            "got {err:?}"
12765        );
12766    }
12767
12768    #[test]
12769    fn rejects_entrada_host_unbracketed_ipv6_literal() {
12770        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
12771        // literals across the board (peer with `rejects_entrada_host_
12772        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
12773        // Before this top-level `:` arm landed the per-label loop
12774        // surfaced a single-label byte-class diagnostic that named the
12775        // `:` byte but not the IP-literal prohibition. The top-level
12776        // `:` arm names both the `:port` slot and the IP-literal
12777        // prohibition verbatim, so an author whose `:host "2001:..."`
12778        // value lands here gets a self-locating fix either way.
12779        let mut s = three_member_spec();
12780        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
12781        let err = s.validate().unwrap_err();
12782        assert!(
12783            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12784                if host == "2001:db8::1"
12785                && reason.contains("IPv6")),
12786            "got {err:?}"
12787        );
12788    }
12789
12790    #[test]
12791    fn rejects_entrada_host_wildcard_with_port() {
12792        // Wildcard host with port suffix — the `*.` strip and the
12793        // per-label loop on `["foo", "quero", "cloud:8080"]` would
12794        // surface the deep byte-class leak. The top-level `:` arm sits
12795        // upstream of the `*.` strip, so it names the canonical `:port`
12796        // fix verbatim regardless of whether the host is wildcard-led.
12797        let mut s = three_member_spec();
12798        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
12799        let err = s.validate().unwrap_err();
12800        assert!(
12801            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12802                if host == "*.quero.cloud:8080"
12803                && reason.contains(":entrada :port")),
12804            "got {err:?}"
12805        );
12806    }
12807
12808    #[test]
12809    fn rejects_entrada_host_with_path() {
12810        let mut s = three_member_spec();
12811        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
12812        let err = s.validate().unwrap_err();
12813        assert!(
12814            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12815                if host == "checkout.quero.cloud/api"),
12816            "got {err:?}"
12817        );
12818    }
12819
12820    #[test]
12821    fn rejects_entrada_host_with_uppercase() {
12822        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12823        // rejected, not silently lower-cased.
12824        let mut s = three_member_spec();
12825        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12826        let err = s.validate().unwrap_err();
12827        assert!(
12828            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12829                if reason.contains("uppercase")),
12830            "got {err:?}"
12831        );
12832    }
12833
12834    #[test]
12835    fn rejects_entrada_host_with_underscore() {
12836        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12837        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12838        let mut s = three_member_spec();
12839        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12840        let err = s.validate().unwrap_err();
12841        assert!(
12842            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12843                if reason.contains('_')),
12844            "got {err:?}"
12845        );
12846    }
12847
12848    #[test]
12849    fn rejects_entrada_host_ipv4_literal() {
12850        // Gateway API v1 explicitly forbids IP literals as Hostnames.
12851        let mut s = three_member_spec();
12852        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12853        let err = s.validate().unwrap_err();
12854        assert!(
12855            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12856                if reason.contains("IPv4")),
12857            "got {err:?}"
12858        );
12859    }
12860
12861    #[test]
12862    fn rejects_entrada_host_with_trailing_dot() {
12863        // The Gateway API regex anchors at end-of-string with no
12864        // trailing `.` allowance — the FQDN root-dot form is rejected.
12865        let mut s = three_member_spec();
12866        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12867        let err = s.validate().unwrap_err();
12868        assert!(
12869            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12870                if host == "checkout.quero.cloud."),
12871            "got {err:?}"
12872        );
12873    }
12874
12875    #[test]
12876    fn rejects_entrada_host_with_leading_dot() {
12877        let mut s = three_member_spec();
12878        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12879        let err = s.validate().unwrap_err();
12880        assert!(
12881            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12882                if reason.contains("empty label")),
12883            "got {err:?}"
12884        );
12885    }
12886
12887    #[test]
12888    fn rejects_entrada_host_with_consecutive_dots() {
12889        let mut s = three_member_spec();
12890        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12891        let err = s.validate().unwrap_err();
12892        assert!(
12893            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12894                if reason.contains("empty label")),
12895            "got {err:?}"
12896        );
12897    }
12898
12899    #[test]
12900    fn rejects_entrada_host_with_leading_hyphen_label() {
12901        let mut s = three_member_spec();
12902        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
12903        let err = s.validate().unwrap_err();
12904        assert!(
12905            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12906                if reason.contains("alphanumeric")),
12907            "got {err:?}"
12908        );
12909    }
12910
12911    #[test]
12912    fn rejects_entrada_host_with_trailing_hyphen_label() {
12913        let mut s = three_member_spec();
12914        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12915        let err = s.validate().unwrap_err();
12916        assert!(
12917            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12918                if reason.contains("alphanumeric")),
12919            "got {err:?}"
12920        );
12921    }
12922
12923    #[test]
12924    fn rejects_entrada_host_with_inner_wildcard() {
12925        // Gateway API allows `*` only as the first label (`*.foo`);
12926        // any inner or trailing `*` is rejected.
12927        let mut s = three_member_spec();
12928        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12929        let err = s.validate().unwrap_err();
12930        assert!(
12931            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12932                if reason.contains("wildcard")),
12933            "got {err:?}"
12934        );
12935    }
12936
12937    #[test]
12938    fn rejects_entrada_host_bare_wildcard() {
12939        // `*.` with no domain is meaningless; Gateway API rejects it.
12940        let mut s = three_member_spec();
12941        s.entrada.as_mut().unwrap().host = "*.".into();
12942        let err = s.validate().unwrap_err();
12943        assert!(
12944            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12945                if reason.contains("wildcard")),
12946            "got {err:?}"
12947        );
12948    }
12949
12950    #[test]
12951    fn rejects_entrada_host_with_whitespace() {
12952        let mut s = three_member_spec();
12953        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12954        let err = s.validate().unwrap_err();
12955        assert!(
12956            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12957                if reason.contains("whitespace")),
12958            "got {err:?}"
12959        );
12960    }
12961
12962    #[test]
12963    fn rejects_entrada_host_space_names_offending_byte() {
12964        // Embedded space in the `:entrada :host` axis surfaces the
12965        // byte-naming diagnostic through the lifted
12966        // `find_ascii_whitespace_byte` predicate. Peer with the
12967        // sibling `parse_rejects_leading_whitespace` pins on
12968        // `supervisor::duration_codec` (a7ae622) — same "the
12969        // diagnostic carries the offending byte's `0x{b:02x}` shape"
12970        // discipline extended from the shared duration codec to the
12971        // Gateway API v1 Hostname axis.
12972        let mut s = three_member_spec();
12973        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12974        let err = s.validate().unwrap_err();
12975        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12976            panic!("expected EntradaHostInvalid, got {err:?}");
12977        };
12978        assert!(
12979            reason.contains("ASCII whitespace byte"),
12980            "expected byte-naming diagnostic, got {reason:?}"
12981        );
12982        assert!(
12983            reason.contains("0x20"),
12984            "expected offending space byte 0x20, got {reason:?}"
12985        );
12986    }
12987
12988    #[test]
12989    fn rejects_entrada_host_tab_names_offending_byte() {
12990        // Embedded tab byte in the `:entrada :host` axis — the
12991        // canonical paste-from-YAML-block-scalar / paste-from-
12992        // indented-doc footgun. Pins that the lifted predicate covers
12993        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12994        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12995        // not just the leading-space case the pre-lift `.bytes().any`
12996        // arm's opaque "must not contain whitespace" reason already
12997        // covered. Peer with `parse_rejects_tab_byte` on
12998        // `supervisor::duration_codec` (a7ae622).
12999        let mut s = three_member_spec();
13000        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
13001        let err = s.validate().unwrap_err();
13002        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13003            panic!("expected EntradaHostInvalid, got {err:?}");
13004        };
13005        assert!(
13006            reason.contains("ASCII whitespace byte"),
13007            "expected byte-naming diagnostic, got {reason:?}"
13008        );
13009        assert!(
13010            reason.contains("0x09"),
13011            "expected offending tab byte 0x09, got {reason:?}"
13012        );
13013    }
13014
13015    #[test]
13016    fn rejects_entrada_host_lf_names_offending_byte() {
13017        // Embedded LF byte in the `:entrada :host` axis — the
13018        // canonical paste-from-shell-heredoc / paste-from-multiline-
13019        // doc footgun the caixa-mesh YAML emitter would silently
13020        // reinterpret at the Gateway API v1 HTTPRoute admission
13021        // layer (an embedded LF byte in a YAML plain scalar either
13022        // truncates the value at the emitter or crashes the parser
13023        // on the k8s-apiserver side). Pins the third representative
13024        // of the full ASCII-whitespace set through the shared
13025        // predicate.
13026        let mut s = three_member_spec();
13027        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
13028        let err = s.validate().unwrap_err();
13029        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13030            panic!("expected EntradaHostInvalid, got {err:?}");
13031        };
13032        assert!(
13033            reason.contains("ASCII whitespace byte"),
13034            "expected byte-naming diagnostic, got {reason:?}"
13035        );
13036        assert!(
13037            reason.contains("0x0a"),
13038            "expected offending LF byte 0x0a, got {reason:?}"
13039        );
13040    }
13041
13042    #[test]
13043    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
13044        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
13045        // axis — the canonical paste-from-typography /
13046        // paste-from-word-processor footgun. Before the non-ASCII
13047        // Unicode `White_Space` scan lifted through the shared
13048        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
13049        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
13050        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
13051        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
13052        // with the far-from-source `label "…" must start and end
13053        // with an alphanumeric` diagnostic — burying the
13054        // paste-from-typography origin under a label-shape leak.
13055        // Peer with the sibling non-ASCII-whitespace pins at
13056        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
13057        // — 1b75b38), `limits::parse_duration`,
13058        // `limits::parse_millicores`, and the shared duration codec
13059        // — same "the diagnostic carries the offending Unicode
13060        // codepoint's `U+XXXX` shape" discipline extended from every
13061        // typed-magnitude codec to the Gateway API v1 Hostname axis.
13062        let mut s = three_member_spec();
13063        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
13064        let err = s.validate().unwrap_err();
13065        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13066            panic!("expected EntradaHostInvalid, got {err:?}");
13067        };
13068        assert!(
13069            reason.contains("non-ASCII Unicode whitespace character"),
13070            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
13071        );
13072        assert!(
13073            reason.contains("U+00A0"),
13074            "expected offending NBSP codepoint U+00A0, got {reason:?}"
13075        );
13076    }
13077
13078    #[test]
13079    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
13080        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
13081        // `:entrada :host` axis — the canonical paste-from-web-doc /
13082        // paste-from-published-HTML footgun. `char::is_whitespace`
13083        // returns true for `U+2028` per the Unicode `White_Space`
13084        // property, so `str::trim` at any downstream site would
13085        // silently strip it — same drift class as NBSP but on a
13086        // different codepoint region. Pins the second representative
13087        // (non-Latin-1 `char::is_whitespace` member) through the
13088        // shared predicate. Peer with
13089        // `parse_byte_size_rejects_internal_line_separator` on
13090        // `limits::parse_byte_size` (1b75b38).
13091        let mut s = three_member_spec();
13092        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
13093        let err = s.validate().unwrap_err();
13094        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13095            panic!("expected EntradaHostInvalid, got {err:?}");
13096        };
13097        assert!(
13098            reason.contains("non-ASCII Unicode whitespace character"),
13099            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
13100        );
13101        assert!(
13102            reason.contains("U+2028"),
13103            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
13104        );
13105    }
13106
13107    #[test]
13108    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
13109        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
13110        // labels in the `:entrada :host` axis — the canonical
13111        // paste-from-CJK-typography footgun (CJK IMEs default to
13112        // full-width whitespace when the space bar is pressed in
13113        // Japanese / Chinese input modes). Pins the third
13114        // representative of the non-ASCII Unicode `White_Space` set
13115        // through the shared predicate: the CJK block, distinct from
13116        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
13117        // SEPARATOR `U+2028` — covering the same axis breadth the
13118        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
13119        // (1b75b38) pins on `limits::parse_byte_size`.
13120        let mut s = three_member_spec();
13121        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
13122        let err = s.validate().unwrap_err();
13123        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13124            panic!("expected EntradaHostInvalid, got {err:?}");
13125        };
13126        assert!(
13127            reason.contains("non-ASCII Unicode whitespace character"),
13128            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
13129        );
13130        assert!(
13131            reason.contains("U+3000"),
13132            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
13133        );
13134    }
13135
13136    #[test]
13137    fn rejects_entrada_host_too_long() {
13138        // Total length cap = 253; build a 254-byte host out of two
13139        // 63-byte labels + one 62-byte label + dots.
13140        let mut s = three_member_spec();
13141        let big = format!(
13142            "{}.{}.{}.{}",
13143            "a".repeat(63),
13144            "b".repeat(63),
13145            "c".repeat(63),
13146            "d".repeat(254 - 63 * 3 - 3)
13147        );
13148        assert_eq!(big.len(), 254);
13149        s.entrada.as_mut().unwrap().host = big;
13150        let err = s.validate().unwrap_err();
13151        assert!(
13152            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13153                if reason.contains("max length of 253")),
13154            "got {err:?}"
13155        );
13156    }
13157
13158    #[test]
13159    fn rejects_entrada_host_label_too_long() {
13160        let mut s = three_member_spec();
13161        // 64-byte label — one over the per-label cap.
13162        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
13163        let err = s.validate().unwrap_err();
13164        assert!(
13165            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13166                if reason.contains("label max length of 63")),
13167            "got {err:?}"
13168        );
13169    }
13170
13171    #[test]
13172    fn entrada_host_diagnostic_carries_offending_host() {
13173        // Diagnostic-shape pin — the offending host + a non-empty
13174        // reason flow through verbatim so the author can grep their
13175        // caixa.lisp for `:host "<host>"` and fix it in one edit.
13176        let mut s = three_member_spec();
13177        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
13178        let err = s.validate().unwrap_err();
13179        match err {
13180            AplicacaoError::EntradaHostInvalid { host, reason } => {
13181                assert_eq!(host, "checkout.quero.cloud:8080");
13182                assert!(!reason.is_empty(), "reason field must be non-empty");
13183            }
13184            other => panic!("expected EntradaHostInvalid, got {other:?}"),
13185        }
13186    }
13187
13188    #[test]
13189    fn entrada_host_empty_takes_precedence_over_invalid() {
13190        // Ordering pin: `EmptyEntradaHost` is the more self-locating
13191        // diagnostic on `""` and must lead — `validate_entrada_host`
13192        // is only reached after the empty-check fires at the call
13193        // site. (The predicate itself defends against direct
13194        // invocation by returning the same error on `""`.)
13195        let mut s = three_member_spec();
13196        s.entrada.as_mut().unwrap().host = String::new();
13197        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
13198    }
13199
13200    #[test]
13201    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
13202        // Ordering pin: a missing :para member is the more
13203        // self-locating diagnostic and fires before the host gate.
13204        let mut s = three_member_spec();
13205        let e = s.entrada.as_mut().unwrap();
13206        e.para = "ghost".into();
13207        e.host = "BAD HOST".into();
13208        let err = s.validate().unwrap_err();
13209        assert!(
13210            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
13211            "got {err:?}"
13212        );
13213    }
13214
13215    #[test]
13216    fn entrada_host_invalid_fires_before_port_zero() {
13217        // Ordering pin: the host gate fires before the port gate so
13218        // a malformed host is named even when the port is also wrong.
13219        let mut s = three_member_spec();
13220        let e = s.entrada.as_mut().unwrap();
13221        e.host = "Checkout.quero.cloud".into();
13222        e.port = 0;
13223        let err = s.validate().unwrap_err();
13224        assert!(
13225            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13226                if host == "Checkout.quero.cloud"),
13227            "got {err:?}"
13228        );
13229    }
13230
13231    #[test]
13232    fn entrada_accepts_canonical_hosts() {
13233        // Positive-control sweep — every form the Gateway API
13234        // apiserver accepts must round-trip through validate. Covers
13235        // a plain DNS subdomain, a leading wildcard, a single-label
13236        // host (cluster-internal), a max-length-edge label, a
13237        // hyphen-bearing label, and a Punycode IDN label.
13238        for host in [
13239            "checkout.quero.cloud",
13240            "*.quero.cloud",
13241            "checkout",
13242            // 63-byte label — exactly the per-label cap.
13243            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
13244            "foo-bar.quero.cloud",
13245            // Punycode IDN — valid because the author pre-encoded.
13246            "xn--bcher-kva.example.com",
13247        ] {
13248            let mut s = three_member_spec();
13249            s.entrada.as_mut().unwrap().host = host.into();
13250            s.validate()
13251                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
13252        }
13253    }
13254
13255    #[test]
13256    fn entrada_host_max_length_validates() {
13257        // 253-byte host is the cap exactly — must validate. Build a
13258        // 253-byte host out of three 63-byte labels + one 61-byte
13259        // label + 3 dots = 252 bytes, then pad one byte to 253.
13260        let mut s = three_member_spec();
13261        let host = format!(
13262            "{}.{}.{}.{}",
13263            "a".repeat(63),
13264            "b".repeat(63),
13265            "c".repeat(63),
13266            "d".repeat(253 - 63 * 3 - 3)
13267        );
13268        assert_eq!(host.len(), 253);
13269        s.entrada.as_mut().unwrap().host = host;
13270        s.validate().unwrap();
13271    }
13272
13273    #[test]
13274    fn entrada_host_total_length_cap_threads_lifted_render_const() {
13275        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
13276        // total-length gate now reads the K8s Gateway API v1 Hostname
13277        // `maxLength: 253` cap from the lifted
13278        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
13279        // of truth — the same constant every future Gateway-API-Hostname
13280        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
13281        // materializer's per-host validator, the future per-`Certificate`
13282        // SAN emitter for cert-manager, the multi-`:entrada`
13283        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
13284        // from. Before the lift, the aplicacao-side reader consumed a
13285        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
13286        // 253-byte value as the peer render-side canonical bounds
13287        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
13288        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
13289        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
13290        // module boundary — a future 253-byte drift on either side would
13291        // silently split into two axes' worth of admission-schema mismatch
13292        // without a build-time signal. Pin the cap through a fresh 254-
13293        // byte host that hits the total-length arm, then read the reason
13294        // for the exact byte count the shared constant carries: any future
13295        // regression on the lift (a private alias reintroduced, a hard-
13296        // coded literal at the arm, a mismatch between the aplicacao-side
13297        // and render-side canonicals) surfaces as this pin's diagnostic
13298        // failing to match, not as a per-cluster admission rejection far
13299        // from the caixa.lisp source line.
13300        let mut s = three_member_spec();
13301        let over_cap = format!(
13302            "{}.{}.{}.{}",
13303            "a".repeat(63),
13304            "b".repeat(63),
13305            "c".repeat(63),
13306            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
13307        );
13308        assert_eq!(
13309            over_cap.len(),
13310            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
13311        );
13312        s.entrada.as_mut().unwrap().host = over_cap;
13313        let err = s.validate().unwrap_err();
13314        match err {
13315            AplicacaoError::EntradaHostInvalid { reason, .. } => {
13316                let needle = format!(
13317                    "max length of {} bytes",
13318                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
13319                );
13320                assert!(
13321                    reason.contains(&needle),
13322                    "diagnostic must name the lifted \
13323                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
13324                );
13325            }
13326            other => panic!("expected EntradaHostInvalid, got {other:?}"),
13327        }
13328    }
13329
13330    #[test]
13331    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
13332        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
13333        // on the per-label-cap axis. Before the lift, the aplicacao-side
13334        // per-label arm consumed a private const alias
13335        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
13336        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
13337        // split from it at the module boundary — every `.`-separated
13338        // label in a Gateway API v1 Hostname is a DNS-1123 label under
13339        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
13340        // so the private alias's 63 and the canonical const's 63 were
13341        // pinning the same underlying rule twice. Pin the cap through a
13342        // 64-byte label that hits the per-label arm, then read the reason
13343        // for the exact byte count the shared constant carries: any
13344        // future drift on either side (a private alias reintroduced, a
13345        // hard-coded literal at the arm, a mismatch between the two
13346        // 63-byte pins) surfaces at this pin's diagnostic rather than at
13347        // a per-cluster admission rejection whose "field is invalid"
13348        // opacity misframes the root cause.
13349        let mut s = three_member_spec();
13350        let over_cap_label = format!(
13351            "{}.quero.cloud",
13352            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
13353        );
13354        s.entrada.as_mut().unwrap().host = over_cap_label;
13355        let err = s.validate().unwrap_err();
13356        match err {
13357            AplicacaoError::EntradaHostInvalid { reason, .. } => {
13358                let needle = format!(
13359                    "label max length of {} bytes",
13360                    crate::render::DNS_1123_LABEL_MAX_LEN,
13361                );
13362                assert!(
13363                    reason.contains(&needle),
13364                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
13365                     cap verbatim on the per-label arm, got: {reason:?}",
13366                );
13367            }
13368            other => panic!("expected EntradaHostInvalid, got {other:?}"),
13369        }
13370    }
13371
13372    #[test]
13373    fn entrada_with_empty_paths_validates() {
13374        // Empty `:paths` is the documented "match every path" form;
13375        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
13376        let mut s = three_member_spec();
13377        s.entrada.as_mut().unwrap().paths = vec![];
13378        s.validate().unwrap();
13379    }
13380
13381    #[test]
13382    fn entrada_root_path_validates() {
13383        // The author-supplied bare-root `:entrada :paths` entry is the
13384        // same byte-shape the peer emit-side catch-all constant
13385        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
13386        // the author's `:paths` list is empty — sweeping the test-side
13387        // probe literal onto the lifted const closes the two-axis pin
13388        // (author-side admit + emit-side canonical fallback) around
13389        // one `&'static str`, so a future rebrand of the catch-all
13390        // reaches both consumers by construction. Peer to
13391        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
13392        // on the canonical-literal pin surface.
13393        let mut s = three_member_spec();
13394        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
13395        s.validate().unwrap();
13396    }
13397
13398    #[test]
13399    fn placement_strategy_variants_round_trip() {
13400        for s in [
13401            PlacementStrategy::SingleNode,
13402            PlacementStrategy::Replicated,
13403            PlacementStrategy::Sharded,
13404        ] {
13405            let p = Placement {
13406                estrategia: s,
13407                clusters: vec!["rio".into()],
13408                affinity: None,
13409                shard_key: if s.is_sharded() {
13410                    Some("$key".into())
13411                } else {
13412                    None
13413                },
13414            };
13415            let json = serde_json::to_string(&p).unwrap();
13416            let back: Placement = serde_json::from_str(&json).unwrap();
13417            assert_eq!(back, p);
13418        }
13419    }
13420
13421    #[test]
13422    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
13423        // The fail-before-pass-after pin: pre-lift there was no
13424        // single-source binding between the [`PlacementStrategy`]
13425        // variant name the `Serialize` derive emits and the byte-
13426        // string every downstream cluster-side dispatcher (the
13427        // `lareira-fleet-programs` aggregator's per-entry strategy
13428        // branch, the future `app-operator` reconciler, the M3
13429        // Adaptive compression pass's per-strategy weighting) probes
13430        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
13431        // future `#[serde(rename_all = "kebab-case")]` attribute on
13432        // the enum — or a variant rename in the source — would
13433        // silently rebrand the emitted scalar under one spelling
13434        // while every downstream dispatcher still probed the other,
13435        // with the failure surfacing at the aggregator's dispatch
13436        // step or the operator's reconcile posture (workloads coming
13437        // up under the `default()` `Replicated` arm rather than the
13438        // typed slot's declared strategy) far from the source
13439        // rebrand commit and with no field naming the drift. Pinning
13440        // the two paths (the `Serialize` derive's serialized string
13441        // AND the [`PlacementStrategy::as_str`] helper) to the same
13442        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
13443        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
13444        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
13445        // makes any future drift on either endpoint fail here at
13446        // caixa-core build time.
13447        for (variant, expected) in [
13448            (
13449                PlacementStrategy::SingleNode,
13450                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13451            ),
13452            (
13453                PlacementStrategy::Replicated,
13454                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13455            ),
13456            (
13457                PlacementStrategy::Sharded,
13458                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13459            ),
13460        ] {
13461            let json = serde_json::to_string(&variant).unwrap();
13462            assert_eq!(
13463                json,
13464                format!("\"{expected}\""),
13465                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
13466            );
13467            assert_eq!(
13468                variant.as_str(),
13469                expected,
13470                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
13471                 M3_PLACEMENT_ESTRATEGIA_* constant"
13472            );
13473        }
13474    }
13475
13476    #[test]
13477    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
13478        // Cross-arm drift-detection pin on the M3
13479        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
13480        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
13481        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
13482        // scalar-value pentad: a future collapse of two canonical
13483        // variant byte-strings onto the same value (an accidental
13484        // copy-paste flip of
13485        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
13486        // read `"SingleNode"`, a per-arm rebrand that lands one const
13487        // without touching its paired peer) would silently reroute
13488        // every downstream operator's per-strategy dispatch onto the
13489        // sibling arm's reconcile branch and pass every
13490        // propagation-probe test that expected only the stale arm's
13491        // value — a `Replicated`-declared Aplicacao would come up
13492        // under the `SingleNode` primary-and-standby reconcile
13493        // posture, so every-cluster active-active workload would
13494        // silently collapse onto one-cluster-runs-at-a-time takeover
13495        // semantics against its declared strategy, with no field
13496        // naming the strategy-value drift root cause. Peer of the
13497        // sibling
13498        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
13499        // (09ffb2d) /
13500        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
13501        // (ccdf955) /
13502        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
13503        // (d739850) distinctness pins on the sibling OTP-shape /
13504        // caixa-kind closed-set typed-enum discriminator axes — the
13505        // fourth (and structurally the M3 mesh-primitive-defining)
13506        // closed-set typed-enum axis to converge on the same
13507        // "pairwise-distinct-by-construction" discipline.
13508        //
13509        // Fail-before-pass-after locally verified by mutating
13510        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
13511        // also read `"SingleNode"` — this pin fires as expected;
13512        // restoring passes.
13513        let all = [
13514            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13515            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13516            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13517        ];
13518        for (i, a) in all.iter().enumerate() {
13519            for (j, b) in all.iter().enumerate() {
13520                if i != j {
13521                    assert_ne!(
13522                        a, b,
13523                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
13524                         distinct — got duplicate {a:?} at indices {i} and {j}",
13525                    );
13526                }
13527            }
13528        }
13529    }
13530
13531    #[test]
13532    fn placement_strategy_display_routes_through_as_str_helper() {
13533        // The fail-before-pass-after pin: pre-lift the sibling
13534        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
13535        // / [`crate::supervisor::RestartPolicy`] both carried a stable
13536        // [`std::fmt::Display`] surface via their
13537        // `#[discriminant(also_display)]` gen-platform derive, but
13538        // [`PlacementStrategy`] did not — every consumer reaching for
13539        // a strategy byte-string past the wire format had to pick
13540        // between three paths ([`PlacementStrategy::as_str`], the
13541        // `Serialize` derive's serialized string, or `format!("{v:?}")`
13542        // on the `Debug` derive), any two of which a future variant
13543        // rename or `#[serde(rename_all = "kebab-case")]` attribute
13544        // would silently desynchronize. Wiring [`std::fmt::Display`]
13545        // through [`PlacementStrategy::as_str`] closes the third path:
13546        // every `format!("{v}")` call reaches the same lifted
13547        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13548        // and the [`PlacementStrategy::as_str`] helper already route
13549        // through, so a future variant rename lands at exactly one
13550        // place. Pin the routing here so a future
13551        // `impl std::fmt::Display for PlacementStrategy` reimplementation
13552        // that hand-rolls the arms instead of delegating to
13553        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
13554        for variant in [
13555            PlacementStrategy::SingleNode,
13556            PlacementStrategy::Replicated,
13557            PlacementStrategy::Sharded,
13558        ] {
13559            assert_eq!(
13560                variant.to_string(),
13561                variant.as_str(),
13562                "PlacementStrategy::{variant:?} Display must route through \
13563                 PlacementStrategy::as_str (single source of truth: the lifted \
13564                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
13565            );
13566        }
13567    }
13568
13569    #[test]
13570    fn placement_strategy_display_matches_serialized_wire_byte_string() {
13571        // The fail-before-pass-after pin on the second half of the
13572        // three-path convergence: `Display` (user-facing text) agrees
13573        // byte-for-byte with the `Serialize` derive's wire format
13574        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
13575        // scalar) on every variant. Pre-lift the two paths were
13576        // structurally independent — a future
13577        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
13578        // would silently rebrand the emitted wire scalar
13579        // (`single-node`, `replicated`, `sharded`) while every consumer
13580        // that pretty-prints the strategy (the M3 diagnostic templates,
13581        // the future `feira app graph` per-Aplicacao strategy line,
13582        // the future M4 CR materializer's admission-webhook rejection
13583        // body) would still emit the TitleCase form the `as_str` /
13584        // `Display` route returns, with the mismatch surfacing at
13585        // consumer parse time / operator dispatch time far from the
13586        // source rebrand commit. Pin the two paths byte-for-byte here
13587        // so any future serde-attribute or variant-rename drift is a
13588        // caixa-core-build-time test failure at this call, not a
13589        // silent per-consumer dispatch miss.
13590        for variant in [
13591            PlacementStrategy::SingleNode,
13592            PlacementStrategy::Replicated,
13593            PlacementStrategy::Sharded,
13594        ] {
13595            let wire = serde_json::to_string(&variant).unwrap();
13596            // Strip the outer `"…"` the JSON string form carries — the
13597            // wire scalar the K8s / YAML apiserver consumes is the
13598            // enclosed byte-string, not the quote wrapper.
13599            let unquoted = wire
13600                .strip_prefix('"')
13601                .and_then(|s| s.strip_suffix('"'))
13602                .expect("serialized PlacementStrategy is a JSON string");
13603            assert_eq!(
13604                variant.to_string(),
13605                unquoted,
13606                "PlacementStrategy::{variant:?} Display byte-string must match the \
13607                 Serialize derive's wire byte-string (three-path convergence: \
13608                 Display + as_str + Serialize all resolve to the same \
13609                 M3_PLACEMENT_ESTRATEGIA_* const)"
13610            );
13611        }
13612    }
13613
13614    #[test]
13615    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
13616        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
13617        // derive on [`PlacementStrategy`]: for each of the three variants
13618        // exactly one of the generated `is_single_node` / `is_replicated`
13619        // / `is_sharded` predicates returns `true` and the other two
13620        // return `false`. Prior to this derive the three per-arm
13621        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
13622        // (the `placement_strategy_variants_round_trip` fixture, the
13623        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
13624        // fixture, and the
13625        // `validate_placement_reads_through_lifted_estrategia_accessor`
13626        // fixture) each open-coded a per-arm PartialEq compare against
13627        // the enum variant — three sites that expressed no compile-time
13628        // link back to the closed-set typed dispatch a future fourth
13629        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
13630        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
13631        // would have to thread through in lockstep or one fixture would
13632        // silently disagree with the others on which arms consume the
13633        // `:shard-key` axis. Peer of the sibling
13634        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
13635        // / [`crate::supervisor::RestartPolicy`] /
13636        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
13637        // the sibling closed-set typed-enum discriminator axes — extends
13638        // the same one-typed-dispatch-per-variant discipline onto the
13639        // fifth (and only remaining) closed-set typed-enum discriminator
13640        // on the caixa surface, closing the axis on the M3 mesh-slot
13641        // family.
13642        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
13643            (PlacementStrategy::SingleNode, [true, false, false]),
13644            (PlacementStrategy::Replicated, [false, true, false]),
13645            (PlacementStrategy::Sharded, [false, false, true]),
13646        ];
13647        for (variant, expected) in rows {
13648            let observed = [
13649                variant.is_single_node(),
13650                variant.is_replicated(),
13651                variant.is_sharded(),
13652            ];
13653            assert_eq!(
13654                observed, expected,
13655                "PlacementStrategy::{variant:?} is_* predicates must partition \
13656                 the arm set (single_node, replicated, sharded); got {observed:?}"
13657            );
13658        }
13659    }
13660
13661    #[test]
13662    fn placement_strategy_is_variant_predicates_are_const_fn() {
13663        // The [`gen_platform::IsVariant`] derive emits `const fn`
13664        // predicates on the peer [`crate::CaixaKind`] +
13665        // [`crate::upgrade::UpgradeInstruction`] +
13666        // [`crate::supervisor::RestartStrategy`] +
13667        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
13668        // pin the same posture on [`PlacementStrategy`] so a future
13669        // accidental downgrade to non-`const` (an added runtime helper
13670        // reachable only from a non-`const` context, a manual hand-rolled
13671        // `impl` that shadows the derive-generated method) trips at
13672        // caixa-core build time rather than surfacing as a downstream
13673        // `const`-context regression far from the derive declaration.
13674        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
13675        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
13676        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
13677        assert!(IS_SINGLE_NODE);
13678        assert!(IS_REPLICATED);
13679        assert!(IS_SHARDED);
13680    }
13681
13682    #[test]
13683    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
13684        // Pin the M3 diagnostic template routes through the typed
13685        // [`PlacementStrategy`] Display byte-string (rebound from the
13686        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
13687        // routes emitted identical bytes (the `Debug` derive on a
13688        // unit variant emits the variant name verbatim, exactly what
13689        // `as_str` returns), but the two paths were structurally
13690        // independent — a future `#[serde(rename_all = "…")]`
13691        // attribute or variant rename would coordinate the wire /
13692        // `Display` / `as_str` triple through the lifted const but
13693        // leave the `Debug` route on the compiler-derived variant name,
13694        // silently desynchronizing the diagnostic byte-string from the
13695        // wire byte-string. Rebinding the template onto `Display`
13696        // ties the diagnostic to the same lifted
13697        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13698        // emits — drift becomes structurally impossible. Pin the
13699        // byte-string here so a future edit that reverts the template
13700        // to `{estrategia:?}` is caught at caixa-core test time, not
13701        // at consumer dispatch time.
13702        for (variant, expected_scalar) in [
13703            (
13704                PlacementStrategy::SingleNode,
13705                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13706            ),
13707            (
13708                PlacementStrategy::Replicated,
13709                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13710            ),
13711            (
13712                PlacementStrategy::Sharded,
13713                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13714            ),
13715        ] {
13716            let err = AplicacaoError::PlacementWithoutClusters {
13717                estrategia: variant,
13718            };
13719            let msg = err.to_string();
13720            assert!(
13721                msg.starts_with(&format!(":placement {expected_scalar} requires")),
13722                "PlacementWithoutClusters diagnostic for {variant:?} must open \
13723                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13724            );
13725        }
13726    }
13727
13728    #[test]
13729    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
13730        // Peer of
13731        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
13732        // on the second M3 diagnostic that carries the typed
13733        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
13734        // diagnostics now route the strategy scalar through the same
13735        // [`std::fmt::Display`] surface, tying the diagnostic
13736        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
13737        // const set the wire format also emits. The two non-Sharded
13738        // arms are exercised here (the diagnostic exists to flag a
13739        // `:shard-key` slot the current strategy will never consume);
13740        // the peer `Sharded` arm never reaches this diagnostic (the
13741        // `Sharded` strategy consumes `:shard-key` — the
13742        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
13743        // slot instead).
13744        for (variant, expected_scalar) in [
13745            (
13746                PlacementStrategy::SingleNode,
13747                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13748            ),
13749            (
13750                PlacementStrategy::Replicated,
13751                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13752            ),
13753        ] {
13754            let err = AplicacaoError::ShardKeyOnNonSharded {
13755                estrategia: variant,
13756                shard_key: "$tenantId".into(),
13757            };
13758            let msg = err.to_string();
13759            assert!(
13760                msg.starts_with(&format!(":placement {expected_scalar} carries")),
13761                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
13762                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13763            );
13764        }
13765    }
13766
13767    #[test]
13768    fn placement_strategy_all_enumerates_every_variant_once() {
13769        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
13770        // exhaustive-iteration surface: every variant appears exactly
13771        // once, and the slice length matches the arm count of the
13772        // closed set. Every consumer that walks the accepted-strategy
13773        // set (a future `feira app placement --list` CLI-side surfacing,
13774        // a future M4 admission-webhook's rejection body naming the
13775        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
13776        // reverse-projection consumers that iterate the accept-set for
13777        // a "did you mean" hint) reads through this slice, so a future
13778        // variant addition (an `Anycast` mesh-anycast arm the
13779        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
13780        // grows the enum but forgets to grow [`Self::ALL`] silently
13781        // truncates every downstream consumer's accept-set at the same
13782        // pre-addition boundary — this pin fails at caixa-core build
13783        // time on the pairwise-distinct + arm-count invariants.
13784        //
13785        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
13786        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
13787        // pins on the peer closed-set typed-enum axes.
13788        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
13789        assert_eq!(
13790            all.len(),
13791            3,
13792            "PlacementStrategy::ALL must enumerate every variant of the \
13793             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
13794        );
13795        for (i, a) in all.iter().enumerate() {
13796            for (j, b) in all.iter().enumerate() {
13797                if i != j {
13798                    assert_ne!(
13799                        a, b,
13800                        "PlacementStrategy::ALL must carry every variant exactly \
13801                         once — got duplicate {a:?} at indices {i} and {j}"
13802                    );
13803                }
13804            }
13805        }
13806        for variant in [
13807            PlacementStrategy::SingleNode,
13808            PlacementStrategy::Replicated,
13809            PlacementStrategy::Sharded,
13810        ] {
13811            assert!(
13812                all.contains(&variant),
13813                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
13814                 addition that grows the enum but forgets to grow the ALL slice \
13815                 silently truncates every downstream consumer's accept-set at the \
13816                 pre-addition boundary"
13817            );
13818        }
13819    }
13820
13821    #[test]
13822    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
13823        // Fail-before-pass-after pin on the forward accept-set of the
13824        // [`PlacementStrategy::from_wire`] reverse projection: every
13825        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
13826        // constant the [`PlacementStrategy::as_str`] emitter walks
13827        // parses back to its paired variant. Any future arm addition
13828        // that grows the emitter's `as_str` match but forgets to grow
13829        // the parser's `from_str` match silently splits the two halves
13830        // of the round-trip — the wire byte-string one non-serde
13831        // consumer parses from the one the emitter wrote — with the
13832        // failure surfacing at parse time far from the rebrand commit.
13833        // Pinning the three-arm accept-set here catches the drift at
13834        // caixa-core build time.
13835        //
13836        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
13837        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
13838        // closed-set typed-enum `str → Self` axes.
13839        for (wire, expected) in [
13840            (
13841                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13842                PlacementStrategy::SingleNode,
13843            ),
13844            (
13845                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13846                PlacementStrategy::Replicated,
13847            ),
13848            (
13849                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13850                PlacementStrategy::Sharded,
13851            ),
13852        ] {
13853            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
13854                panic!(
13855                    "PlacementStrategy::from_wire({wire:?}) must accept every \
13856                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
13857                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
13858                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
13859                )
13860            });
13861            assert_eq!(
13862                parsed, expected,
13863                "PlacementStrategy::from_wire({wire:?}) must return \
13864                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
13865            );
13866        }
13867    }
13868
13869    #[test]
13870    fn placement_strategy_from_wire_round_trips_through_as_str() {
13871        // Fail-before-pass-after pin on the closed round-trip between
13872        // the forward [`PlacementStrategy::as_str`] emitter and the
13873        // reverse [`PlacementStrategy::from_wire`] parser: for every
13874        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
13875        // output must return exactly the same variant. Any per-arm
13876        // divergence — a future arm added to `as_str` but not
13877        // `from_str`, an accidental copy-paste flip in one but not the
13878        // other — silently splits the emit and parse halves and the
13879        // failure surfaces at consumer parse time far from the drift
13880        // site. The `ALL`-iterating shape means a future variant
13881        // addition picks up the coverage by construction.
13882        //
13883        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
13884        // [`crate::CaixaKind::from_wire`] and the
13885        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
13886        // sibling round-trip pin on [`RateLimitUnit`].
13887        for &variant in PlacementStrategy::ALL {
13888            let wire = variant.as_str();
13889            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
13890                panic!(
13891                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
13892                     must be Some({variant:?}) — the two halves of the round-trip \
13893                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
13894                     got None on wire byte-string {wire:?}"
13895                )
13896            });
13897            assert_eq!(
13898                parsed, variant,
13899                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
13900                 must round-trip to the same variant; got {parsed:?}"
13901            );
13902        }
13903    }
13904
13905    #[test]
13906    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
13907        // Fail-before-pass-after pin on the closed-set refusal
13908        // discipline of [`PlacementStrategy::from_wire`]: every
13909        // byte-string outside the three-arm accept-set returns `None`
13910        // rather than silently collapsing onto the [`Default`]
13911        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
13912        // exercised here sweeps the load-bearing drift shapes: the
13913        // empty string (a stripped serde-attribute drift), an all-
13914        // whitespace string (the canonical text-editor accidental
13915        // padding shape), the lowercased kebab-case forms a future
13916        // `#[serde(rename_all = "kebab-case")]` attribute would emit
13917        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
13918        // coincidentally match the accepted canonical scalars, so only
13919        // `"single-node"` fires as a refusal, but pinning the case-
13920        // sensitivity of the accepted arms via the peer [`SingleNode`]
13921        // assertion in the round-trip pin makes the discipline
13922        // structurally clear), the lowercased single-word forms
13923        // (`"singlenode"`), the padded canonical scalar
13924        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
13925        // (`"Sharded\n"`), and a pointer-different `&'static str` that
13926        // happens to alias a canonical byte-string by content but not
13927        // by identity (validated implicitly by the emitter's routing
13928        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
13929        // identity a paired [`crate::assert_str_reexport_identity`] pin
13930        // in caixa-core's per-const declaration surface would catch).
13931        //
13932        // Peer of the sibling
13933        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
13934        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
13935        for bad in [
13936            "",
13937            " ",
13938            "\n",
13939            "\t",
13940            "single-node",
13941            "singlenode",
13942            "SingleNodes",
13943            "single_node",
13944            "single node",
13945            "SINGLENODE",
13946            "SingleNode ",
13947            " SingleNode",
13948            " Sharded ",
13949            "Sharded\n",
13950            "replicated ",
13951            "sharded",
13952            "REPLICATED",
13953            "Anycast",
13954            "Global",
13955            "?",
13956        ] {
13957            assert!(
13958                PlacementStrategy::from_wire(bad).is_none(),
13959                "PlacementStrategy::from_wire({bad:?}) must return None — the \
13960                 parser's accept-set is exactly the three PlacementStrategy::as_str \
13961                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
13962                 is outside that closed set"
13963            );
13964        }
13965    }
13966
13967    #[test]
13968    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
13969        // Fail-before-pass-after pin on the third path of the four-path
13970        // convergence: `from_str` (the reverse projection) inverts the
13971        // `Serialize` derive's wire byte-string on every variant.
13972        // Together with the pre-existing three-path convergence
13973        // (`Display` + `as_str` + `Serialize` all resolve to the same
13974        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
13975        // the peer
13976        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
13977        // this closes the round-trip: the wire byte-string the
13978        // `Serialize` derive emits parses back to the same variant
13979        // through `from_str`, so any future serde-attribute or variant-
13980        // rename drift on the emit half now surfaces as a matched drift
13981        // on the parse half at caixa-core build time — the two halves
13982        // migrate as a unit through the lifted consts on any future
13983        // rename, and the round-trip cannot silently split.
13984        //
13985        // Peer of the sibling
13986        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
13987        // wire-format pin — extends the three-path convergence
13988        // (`Display` + `as_str` + `Serialize`) onto the fourth path
13989        // (`from_str`), closing the `str ↔ Self` round-trip on the
13990        // M3 `:placement :estrategia` closed-set axis.
13991        for &variant in PlacementStrategy::ALL {
13992            let wire = serde_json::to_string(&variant).unwrap();
13993            let unquoted = wire
13994                .strip_prefix('"')
13995                .and_then(|s| s.strip_suffix('"'))
13996                .expect("serialized PlacementStrategy is a JSON string");
13997            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
13998                panic!(
13999                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
14000                     Serialize derive's wire byte-string for \
14001                     PlacementStrategy::{variant:?} — the four-path convergence \
14002                     (Display + as_str + Serialize + from_str) resolves through \
14003                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
14004                )
14005            });
14006            assert_eq!(
14007                parsed, variant,
14008                "PlacementStrategy::from_wire of the Serialize derive's wire \
14009                 byte-string for PlacementStrategy::{variant:?} must round-trip \
14010                 to the same variant; got {parsed:?}"
14011            );
14012        }
14013    }
14014
14015    #[test]
14016    fn rejects_zero_policy_timeout() {
14017        let mut s = three_member_spec();
14018        s.politicas.timeout = Some(Duration::ZERO);
14019        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
14020    }
14021
14022    #[test]
14023    fn rejects_zero_policy_retries() {
14024        let mut s = three_member_spec();
14025        s.politicas.retries = Some(0);
14026        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
14027    }
14028
14029    #[test]
14030    fn rejects_policy_retries_above_cap() {
14031        // The fail-before-pass-after pin: `Some(11)` is structurally
14032        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
14033        // passed validate on every pre-gate codebase because the
14034        // typed slot's only check was the zero-floor arm. The
14035        // thundering-herd amplification vector only surfaced at the
14036        // runtime substrate (Envoy / Cilium L7 retry overlay)
14037        // far from the source caixa.lisp with no field naming the
14038        // offending policy.
14039        let mut s = three_member_spec();
14040        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
14041        assert_eq!(
14042            s.validate().unwrap_err(),
14043            AplicacaoError::PolicyRetriesExceedsCap {
14044                retries: POLICY_RETRIES_MAX + 1
14045            }
14046        );
14047    }
14048
14049    #[test]
14050    fn rejects_policy_retries_far_above_cap() {
14051        // The `u32::MAX` worst case — the four-billion-retry policy
14052        // a typo (`(:retries 4294967295)`) or struct-literal
14053        // copy-paste lands in the slot. Pin the cap arm's coverage
14054        // explicitly across the full `u32` overflow so a future
14055        // relaxation that drops the upper bound surfaces here.
14056        let mut s = three_member_spec();
14057        s.politicas.retries = Some(u32::MAX);
14058        assert_eq!(
14059            s.validate().unwrap_err(),
14060            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
14061        );
14062    }
14063
14064    #[test]
14065    fn accepts_policy_retries_at_cap() {
14066        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
14067        // must validate. The cap is inclusive on the top edge,
14068        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
14069        // discipline on the sibling [`crate::LimitsSpec::memory`]
14070        // axis. Pin the boundary explicitly so a future off-by-one
14071        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
14072        // surfaces here as a test failure rather than a silent
14073        // contract narrowing.
14074        let mut s = three_member_spec();
14075        s.politicas.retries = Some(POLICY_RETRIES_MAX);
14076        s.validate()
14077            .expect("retries == POLICY_RETRIES_MAX must validate");
14078    }
14079
14080    #[test]
14081    fn accepts_policy_retries_typical_values() {
14082        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
14083        // every value in the validated set must pass. The
14084        // Envoy / Istio production-playbook recommendation band
14085        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
14086        // (`maxRetries ≤ 10`) both lie within this set.
14087        for r in 1..=POLICY_RETRIES_MAX {
14088            let mut s = three_member_spec();
14089            s.politicas.retries = Some(r);
14090            s.validate()
14091                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
14092        }
14093    }
14094
14095    #[test]
14096    fn policy_retries_zero_takes_precedence_over_cap() {
14097        // The cross-arm ordering pin: `Some(0)` is structurally
14098        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
14099        // (cap), but the zero-floor diagnostic is the more
14100        // self-locating one (it directly names the omit-axis
14101        // remediation), so the validate gate must fire on zero
14102        // first. Pin the order so a future refactor that reorders
14103        // the arms surfaces here as a test failure rather than a
14104        // silent diagnostic regression. Same shape every other
14105        // zero-then-shape ordering on this surface uses
14106        // ([`AplicacaoError::PolicyTimeoutZero`] then
14107        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
14108        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
14109        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
14110        let mut s = three_member_spec();
14111        s.politicas.retries = Some(0);
14112        assert_eq!(
14113            s.validate().unwrap_err(),
14114            AplicacaoError::PolicyRetriesZero,
14115            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
14116        );
14117    }
14118
14119    #[test]
14120    fn policy_retries_cap_diagnostic_carries_offending_value() {
14121        // The diagnostic-shape pin: the offending `u32` is carried
14122        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
14123        // variant so the surfaced error message names the value the
14124        // author wrote (`":politicas :retries (47) exceeds the
14125        // mesh-policy ceiling …"`), not just the cap. Same
14126        // self-locating diagnostic shape every other typed-cap arm
14127        // on this surface carries
14128        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
14129        // offending byte count verbatim).
14130        let mut s = three_member_spec();
14131        s.politicas.retries = Some(47);
14132        let err = s.validate().unwrap_err();
14133        assert!(
14134            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
14135            "got {err:?}"
14136        );
14137        let msg = err.to_string();
14138        assert!(
14139            msg.contains("47"),
14140            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
14141        );
14142    }
14143
14144    #[test]
14145    fn policy_retries_cap_is_aws_app_mesh_aligned() {
14146        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
14147        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
14148        // schema cap — the only upstream mesh-policy schema that
14149        // documents an explicit hard cap. Pinning the literal value
14150        // here surfaces a future drift (a relaxation to 20, a
14151        // tightening to 5) as a deliberate test edit, not a silent
14152        // contract narrowing.
14153        assert_eq!(POLICY_RETRIES_MAX, 10);
14154    }
14155
14156    #[test]
14157    fn rejects_circuit_breaker_zero_max_failures() {
14158        let mut s = three_member_spec();
14159        s.politicas.circuit_breaker = Some(CircuitBreaker {
14160            max_failures: 0,
14161            window: Duration::from_secs(60),
14162        });
14163        assert_eq!(
14164            s.validate().unwrap_err(),
14165            AplicacaoError::PolicyBreakerZeroFailures
14166        );
14167    }
14168
14169    #[test]
14170    fn rejects_circuit_breaker_max_failures_above_cap() {
14171        // The fail-before-pass-after pin: `1001` is structurally one
14172        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
14173        // silently passed validate on every pre-gate codebase
14174        // because the typed slot's only check was the zero-floor
14175        // arm. The breaker-no-op vector only surfaced at the runtime
14176        // substrate (Envoy / Cilium L7 outlier-detection overlay)
14177        // far from the source caixa.lisp with no field naming the
14178        // offending policy.
14179        let mut s = three_member_spec();
14180        s.politicas.circuit_breaker = Some(CircuitBreaker {
14181            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14182            window: Duration::from_secs(60),
14183        });
14184        assert_eq!(
14185            s.validate().unwrap_err(),
14186            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14187                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14188            }
14189        );
14190    }
14191
14192    #[test]
14193    fn rejects_circuit_breaker_max_failures_far_above_cap() {
14194        // The `u32::MAX` worst case — the four-billion-failure
14195        // threshold a typo (`(:max-failures 4294967295)`) or a
14196        // struct-literal copy-paste lands in the slot. Pin the cap
14197        // arm's coverage explicitly across the full `u32` overflow
14198        // so a future relaxation that drops the upper bound surfaces
14199        // here.
14200        let mut s = three_member_spec();
14201        s.politicas.circuit_breaker = Some(CircuitBreaker {
14202            max_failures: u32::MAX,
14203            window: Duration::from_secs(60),
14204        });
14205        assert_eq!(
14206            s.validate().unwrap_err(),
14207            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14208                max_failures: u32::MAX,
14209            }
14210        );
14211    }
14212
14213    #[test]
14214    fn accepts_circuit_breaker_max_failures_at_cap() {
14215        // The boundary value — exactly
14216        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
14217        // cap is inclusive on the top edge, matching the
14218        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
14219        // discipline on the sibling capped axes. Pin the boundary
14220        // explicitly so a future off-by-one tightening
14221        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
14222        // surfaces here as a test failure rather than a silent
14223        // contract narrowing.
14224        let mut s = three_member_spec();
14225        s.politicas.circuit_breaker = Some(CircuitBreaker {
14226            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
14227            window: Duration::from_secs(60),
14228        });
14229        s.validate()
14230            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
14231    }
14232
14233    #[test]
14234    fn accepts_circuit_breaker_max_failures_typical_values() {
14235        // The documented production-playbook band positive-control
14236        // sweep — every value Hystrix / Istio / Envoy / Polly /
14237        // Resilience4j recommend (5..=50) must pass, plus a sweep
14238        // through the hyperscale band (100, 500, 1000) the cap
14239        // accepts. Pin the inclusive validated set explicitly so a
14240        // future tightening of the ceiling surfaces here.
14241        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
14242            let mut s = three_member_spec();
14243            s.politicas.circuit_breaker = Some(CircuitBreaker {
14244                max_failures: n,
14245                window: Duration::from_secs(60),
14246            });
14247            s.validate()
14248                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
14249        }
14250    }
14251
14252    #[test]
14253    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
14254        // The cross-arm ordering pin: `0` is structurally outside
14255        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
14256        // (cap), but the zero-floor diagnostic is the more
14257        // self-locating one (it directly names the omit-axis
14258        // remediation), so the validate gate must fire on zero
14259        // first. Same shape every other zero-then-shape ordering on
14260        // this surface uses
14261        // ([`AplicacaoError::PolicyRetriesZero`] then
14262        // [`AplicacaoError::PolicyRetriesExceedsCap`];
14263        // [`AplicacaoError::PolicyTimeoutZero`] then
14264        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
14265        let mut s = three_member_spec();
14266        s.politicas.circuit_breaker = Some(CircuitBreaker {
14267            max_failures: 0,
14268            window: Duration::from_secs(60),
14269        });
14270        assert_eq!(
14271            s.validate().unwrap_err(),
14272            AplicacaoError::PolicyBreakerZeroFailures,
14273            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
14274        );
14275    }
14276
14277    #[test]
14278    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
14279        // The cross-arm ordering pin between the cap and the
14280        // sibling `:window` gates (zero-window, canonical-window).
14281        // A breaker carrying both an over-cap `max_failures` AND a
14282        // structurally invalid window (zero, sub-ms) must surface
14283        // the cap diagnostic first — the cap arm is wired
14284        // immediately after the zero-failure arm and strictly
14285        // before the window arms, so the offending value the
14286        // diagnostic names matches the order the author would
14287        // discover the gates by reading top-to-bottom through
14288        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
14289        // future refactor that reorders the arms surfaces here as a
14290        // test failure rather than a silent diagnostic regression.
14291        let mut s = three_member_spec();
14292        s.politicas.circuit_breaker = Some(CircuitBreaker {
14293            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14294            window: Duration::ZERO,
14295        });
14296        assert_eq!(
14297            s.validate().unwrap_err(),
14298            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14299                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
14300            },
14301            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
14302        );
14303    }
14304
14305    #[test]
14306    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
14307        // The diagnostic-shape pin: the offending `u32` is carried
14308        // verbatim into the
14309        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
14310        // variant so the surfaced error message names the value the
14311        // author wrote (`":politicas :circuit-breaker :max-failures
14312        // (50000) exceeds the mesh-policy ceiling …"`), not just
14313        // the cap. Same self-locating diagnostic shape every other
14314        // typed-cap arm on this surface carries
14315        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
14316        // offending retry count verbatim,
14317        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
14318        // offending byte count verbatim).
14319        let mut s = three_member_spec();
14320        s.politicas.circuit_breaker = Some(CircuitBreaker {
14321            max_failures: 50_000,
14322            window: Duration::from_secs(60),
14323        });
14324        let err = s.validate().unwrap_err();
14325        assert!(
14326            matches!(
14327                err,
14328                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
14329                    max_failures: 50_000
14330                }
14331            ),
14332            "got {err:?}"
14333        );
14334        let msg = err.to_string();
14335        assert!(
14336            msg.contains("50000"),
14337            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
14338        );
14339    }
14340
14341    #[test]
14342    fn policy_breaker_max_failures_cap_pins_canonical_value() {
14343        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
14344        // value at 1000 — an order of magnitude above every
14345        // documented production-playbook recommendation band
14346        // (Hystrix `requestVolumeThreshold` default 20, Istio
14347        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
14348        // `outlier_detection.consecutive_5xx` default 5, Polly /
14349        // Resilience4j typical 5..=50) and below the
14350        // clearly-pathological "effectively no protection" floor
14351        // (10_000, 100_000, u32::MAX). Pinning the literal value
14352        // here surfaces a future drift (a relaxation to 10_000, a
14353        // tightening to 100) as a deliberate test edit, not a
14354        // silent contract narrowing.
14355        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
14356    }
14357
14358    #[test]
14359    fn rejects_circuit_breaker_zero_window() {
14360        let mut s = three_member_spec();
14361        s.politicas.circuit_breaker = Some(CircuitBreaker {
14362            max_failures: 5,
14363            window: Duration::ZERO,
14364        });
14365        assert_eq!(
14366            s.validate().unwrap_err(),
14367            AplicacaoError::PolicyBreakerZeroWindow
14368        );
14369    }
14370
14371    #[test]
14372    fn rejects_zero_rate_limit() {
14373        let mut s = three_member_spec();
14374        s.politicas.rate_limit = Some(RateLimit {
14375            rate: 0,
14376            window: Duration::from_secs(1),
14377        });
14378        assert_eq!(
14379            s.validate().unwrap_err(),
14380            AplicacaoError::PolicyRateLimitZero
14381        );
14382    }
14383
14384    #[test]
14385    fn rejects_rate_limit_zero_window() {
14386        // `RateLimit { rate: 100, window: Duration::ZERO }` is
14387        // constructible programmatically (the typed `Duration` field
14388        // imposes no nonzero invariant) but renders through
14389        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
14390        // codec's `parse` rejects as `unknown rate-limit window unit
14391        // "0s"`. Until this validate-time gate landed the typed slot
14392        // accepted the value silently and the round-trip break only
14393        // surfaced at deserialize time (potentially in a downstream
14394        // consumer that never re-validates). Pin the rejection at
14395        // `AplicacaoSpec::validate` so the typed slot's valid set
14396        // matches the codec's round-trippable set structurally.
14397        let mut s = three_member_spec();
14398        s.politicas.rate_limit = Some(RateLimit {
14399            rate: 100,
14400            window: Duration::ZERO,
14401        });
14402        assert_eq!(
14403            s.validate().unwrap_err(),
14404            AplicacaoError::PolicyRateLimitWindowNotCanonical {
14405                window: Duration::ZERO
14406            }
14407        );
14408    }
14409
14410    #[test]
14411    fn rejects_rate_limit_arbitrary_seconds_window() {
14412        // 45 seconds is a valid `Duration` but not one of the three
14413        // canonical rate-limit windows the codec round-trips
14414        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
14415        // refuses on round-trip — same round-trip-break shape the
14416        // zero-window arm above pins, with a non-zero magnitude to
14417        // guard against a future "reject only zero" half-measure.
14418        let mut s = three_member_spec();
14419        let window = Duration::from_secs(45);
14420        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
14421        assert_eq!(
14422            s.validate().unwrap_err(),
14423            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
14424        );
14425    }
14426
14427    #[test]
14428    fn rejects_rate_limit_two_minute_window() {
14429        // 120 seconds = 2 minutes is a "looks-canonical" but
14430        // not-canonical window: it's a clean integer multiple of the
14431        // minute unit, but the codec only round-trips the
14432        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
14433        // A `Duration::from_secs(120)` window renders as `"100/120s"`
14434        // which the parser rejects. Pinning this case rules out a
14435        // future "accept any clean multiple of s/m/h" relaxation
14436        // that would silently break the codec contract.
14437        let mut s = three_member_spec();
14438        let window = Duration::from_secs(120);
14439        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
14440        assert_eq!(
14441            s.validate().unwrap_err(),
14442            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
14443        );
14444    }
14445
14446    #[test]
14447    fn rejects_rate_limit_subsecond_window() {
14448        // A sub-second window (e.g. 500ms) is a valid `Duration` but
14449        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
14450        // Pin the rejection so a future relaxation can't silently
14451        // admit fractional-second windows that the codec can't
14452        // round-trip.
14453        let mut s = three_member_spec();
14454        let window = Duration::from_millis(500);
14455        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
14456        assert_eq!(
14457            s.validate().unwrap_err(),
14458            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
14459        );
14460    }
14461
14462    #[test]
14463    fn rejects_policy_rate_limit_above_cap() {
14464        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
14465        // is structurally one past the cap and silently passed
14466        // validate on every pre-gate codebase because the typed slot's
14467        // only `rate` check was the zero-floor arm. The no-op-limiter
14468        // shape only surfaced at the runtime substrate (Envoy's
14469        // `local_rate_limit.token_bucket.max_tokens`, the future
14470        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
14471        // with no field naming the offending policy.
14472        let mut s = three_member_spec();
14473        s.politicas.rate_limit = Some(RateLimit {
14474            rate: POLICY_RATE_LIMIT_MAX + 1,
14475            window: Duration::from_secs(1),
14476        });
14477        assert_eq!(
14478            s.validate().unwrap_err(),
14479            AplicacaoError::PolicyRateLimitExceedsCap {
14480                rate: POLICY_RATE_LIMIT_MAX + 1
14481            }
14482        );
14483    }
14484
14485    #[test]
14486    fn rejects_policy_rate_limit_far_above_cap() {
14487        // The `u32::MAX` worst case — the four-billion-token rate-limit
14488        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
14489        // copy-paste lands in the slot. Pin the cap arm's coverage
14490        // explicitly across the full `u32` overflow so a future
14491        // relaxation that drops the upper bound surfaces here. Peer to
14492        // `rejects_policy_retries_far_above_cap` on the sibling
14493        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
14494        // on the sibling `:max-failures` axis.
14495        let mut s = three_member_spec();
14496        s.politicas.rate_limit = Some(RateLimit {
14497            rate: u32::MAX,
14498            window: Duration::from_secs(1),
14499        });
14500        assert_eq!(
14501            s.validate().unwrap_err(),
14502            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
14503        );
14504    }
14505
14506    #[test]
14507    fn accepts_policy_rate_limit_at_cap() {
14508        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
14509        // must validate. The cap is inclusive on the top edge, matching
14510        // every other typed upper bound in this crate
14511        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
14512        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
14513        // across all three canonical windows so a future off-by-one
14514        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
14515        // window-conditional cap surfaces here as a test failure rather
14516        // than a silent contract narrowing.
14517        for secs in [1u64, 60, 3600] {
14518            let mut s = three_member_spec();
14519            s.politicas.rate_limit = Some(RateLimit {
14520                rate: POLICY_RATE_LIMIT_MAX,
14521                window: Duration::from_secs(secs),
14522            });
14523            s.validate().unwrap_or_else(|e| {
14524                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
14525            });
14526        }
14527    }
14528
14529    #[test]
14530    fn accepts_policy_rate_limit_typical_values() {
14531        // The documented production-playbook recommendation band —
14532        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
14533        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
14534        // Enterprise ~1M per-hour. Every value in the validated set
14535        // must pass; pin the band explicitly so a future tightening
14536        // surfaces here.
14537        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
14538            for secs in [1u64, 60, 3600] {
14539                let mut s = three_member_spec();
14540                s.politicas.rate_limit = Some(RateLimit {
14541                    rate,
14542                    window: Duration::from_secs(secs),
14543                });
14544                s.validate().unwrap_or_else(|e| {
14545                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
14546                });
14547            }
14548        }
14549    }
14550
14551    #[test]
14552    fn policy_rate_limit_zero_takes_precedence_over_cap() {
14553        // The cross-arm ordering pin: `rate == 0` is structurally
14554        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
14555        // (cap), but the zero-floor diagnostic is the more
14556        // self-locating one (it directly names the omit-axis
14557        // remediation). Pin the order so a future refactor that
14558        // reorders the arms surfaces here as a test failure rather
14559        // than a silent diagnostic regression. Same shape every other
14560        // zero-then-cap ordering on this surface uses
14561        // ([`AplicacaoError::PolicyRetriesZero`] then
14562        // [`AplicacaoError::PolicyRetriesExceedsCap`];
14563        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14564        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14565        let mut s = three_member_spec();
14566        s.politicas.rate_limit = Some(RateLimit {
14567            rate: 0,
14568            window: Duration::from_secs(1),
14569        });
14570        assert_eq!(
14571            s.validate().unwrap_err(),
14572            AplicacaoError::PolicyRateLimitZero,
14573            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
14574        );
14575    }
14576
14577    #[test]
14578    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
14579        // Two-axis-bad pin: rate above cap *and* window non-canonical.
14580        // The validate gate must fire on the rate cap first — the
14581        // amplification-shape (no-op limiter) diagnostic is the more
14582        // fundamental one; the window-canonical diagnostic is the
14583        // narrower codec-round-trip shape. Pin the ordering so a future
14584        // refactor that reorders the rate-then-window check arms
14585        // surfaces here as a test failure rather than a silent
14586        // diagnostic regression.
14587        let mut s = three_member_spec();
14588        s.politicas.rate_limit = Some(RateLimit {
14589            rate: POLICY_RATE_LIMIT_MAX + 1,
14590            window: Duration::from_secs(45),
14591        });
14592        assert_eq!(
14593            s.validate().unwrap_err(),
14594            AplicacaoError::PolicyRateLimitExceedsCap {
14595                rate: POLICY_RATE_LIMIT_MAX + 1
14596            },
14597            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
14598        );
14599    }
14600
14601    #[test]
14602    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
14603        // The diagnostic-shape pin: the offending `u32` is carried
14604        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
14605        // variant so the surfaced error message names the value the
14606        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
14607        // the mesh-policy ceiling …"`), not just the cap. Same
14608        // self-locating diagnostic shape every other typed-cap arm on
14609        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
14610        // carries the offending retries count verbatim,
14611        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
14612        // the offending failure count verbatim).
14613        let mut s = three_member_spec();
14614        s.politicas.rate_limit = Some(RateLimit {
14615            rate: 5_000_000,
14616            window: Duration::from_secs(1),
14617        });
14618        let err = s.validate().unwrap_err();
14619        assert!(
14620            matches!(
14621                err,
14622                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
14623            ),
14624            "got {err:?}"
14625        );
14626        let msg = err.to_string();
14627        assert!(
14628            msg.contains("5000000"),
14629            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
14630        );
14631    }
14632
14633    #[test]
14634    fn policy_rate_limit_cap_pins_canonical_value() {
14635        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
14636        // 1_000_000 — two-to-three orders of magnitude above every
14637        // documented production-playbook recommendation band (Envoy /
14638        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
14639        // Gateway 10_000..=100_000 per-minute) and below the
14640        // clearly-pathological "paste-from-binary blob" floor
14641        // (100_000_000, u32::MAX). Pinning the literal value here
14642        // surfaces a future drift (a relaxation to 10_000_000, a
14643        // tightening to 100_000) as a deliberate test edit, not a
14644        // silent contract narrowing.
14645        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
14646    }
14647
14648    #[test]
14649    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
14650        // Both axes are invalid here: rate == 0 *and* window is
14651        // non-canonical. The validate gate must fire on rate first
14652        // (matching the existing `rejects_zero_rate_limit` ordering),
14653        // so the existing diagnostic continues to lead with the
14654        // simpler "zero rate" framing. Pinning the order of checks
14655        // so a future refactor that reorders the arms surfaces here
14656        // as a test failure rather than a silent diagnostic
14657        // regression.
14658        let mut s = three_member_spec();
14659        s.politicas.rate_limit = Some(RateLimit {
14660            rate: 0,
14661            window: Duration::from_secs(45),
14662        });
14663        assert_eq!(
14664            s.validate().unwrap_err(),
14665            AplicacaoError::PolicyRateLimitZero
14666        );
14667    }
14668
14669    #[test]
14670    fn rate_limit_canonical_windows_validate() {
14671        // The three canonical windows the codec round-trips
14672        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
14673        // unchanged. Pin the full canonical set as a positive case
14674        // (the existing `rate_limit_round_trip_seconds` /
14675        // `rate_limit_round_trip_minutes` tests pin the
14676        // serialize-then-deserialize property at the codec layer; this
14677        // test pins the validate-side complement so a future tightening
14678        // of the canonical set — e.g. dropping `:hour` — surfaces here
14679        // as a test failure rather than a silent contract narrowing).
14680        for secs in [1u64, 60, 3600] {
14681            let mut s = three_member_spec();
14682            s.politicas.rate_limit = Some(RateLimit {
14683                rate: 100,
14684                window: Duration::from_secs(secs),
14685            });
14686            s.validate().expect("canonical window must validate");
14687        }
14688    }
14689
14690    #[test]
14691    fn rate_limit_validated_value_round_trips_through_codec() {
14692        // The structural property the validate gate enforces:
14693        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
14694        // losslessly through the `rate_limit_codec` (serialize → string
14695        // → deserialize → equal value). Pin this end-to-end so a future
14696        // change to either side (the validate gate's accepted window
14697        // set, the codec's parse/render unit set) that breaks the
14698        // alignment surfaces here. The previous-state shape (typed
14699        // slot accepts arbitrary `Duration`, codec only round-trips
14700        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
14701        // window — the validate gate now forecloses that.
14702        for secs in [1u64, 60, 3600] {
14703            let mut s = three_member_spec();
14704            s.politicas.rate_limit = Some(RateLimit {
14705                rate: 250,
14706                window: Duration::from_secs(secs),
14707            });
14708            s.validate().unwrap();
14709            let json = serde_json::to_string(&s.politicas).unwrap();
14710            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14711            assert_eq!(
14712                back.rate_limit, s.politicas.rate_limit,
14713                "every validated :rate-limit must round-trip losslessly through the codec"
14714            );
14715        }
14716    }
14717
14718    #[test]
14719    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
14720        // The hour-window canonical form (`"<n>/h"`) was missing from
14721        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
14722        // pair. Now that the validate gate pins 3600s as part of the
14723        // canonical set, pin its serialize-side render shape too so
14724        // the third leg of the s/m/h tripod is explicitly tested.
14725        let policy = MeshPolicy {
14726            rate_limit: Some(RateLimit {
14727                rate: 10000,
14728                window: Duration::from_secs(3600),
14729            }),
14730            ..Default::default()
14731        };
14732        let json = serde_json::to_string(&policy).unwrap();
14733        assert!(
14734            json.contains("\"10000/h\""),
14735            "hour-window canonical form must render with `h` suffix (got: {json})"
14736        );
14737        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14738        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
14739    }
14740
14741    #[test]
14742    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
14743        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
14744        // typed accessor's accepted-window set against the codec's
14745        // accepted set explicitly. A future addition to the codec
14746        // (e.g. accepting `:day`/`:week` as authoring units) must be
14747        // accompanied by a parallel addition here, and a regression
14748        // that drops one of the three canonical units from either
14749        // side surfaces as a test failure. The accessor is the
14750        // single source of truth for the canonical-window set —
14751        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
14752        // gate and [`rate_limit_codec::render`]'s canonical arm both
14753        // read through it — this test enshrines that its
14754        // `Duration → Option<RateLimitUnit>` projection matches the
14755        // codec's parse / render arms' accepted-window set exactly.
14756        //
14757        // Predecessor: this pin previously read the module-private
14758        // free helper `is_canonical_rate_limit_window` — a delegate
14759        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
14760        // — but the helper had no production consumers left after the
14761        // validate-gate migration onto [`RateLimit::canonical_unit`]
14762        // and was deleted; the closed-set arm-window bijection now
14763        // lives on exactly one typed dispatch on the substrate
14764        // primitive.
14765        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
14766            RateLimit { rate: 1, window }.canonical_unit()
14767        };
14768        assert!(canonical_unit(Duration::from_secs(1)).is_some());
14769        assert!(canonical_unit(Duration::from_secs(60)).is_some());
14770        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
14771        // Non-canonical windows the accessor rejects.
14772        assert!(canonical_unit(Duration::ZERO).is_none());
14773        assert!(canonical_unit(Duration::from_secs(2)).is_none());
14774        assert!(canonical_unit(Duration::from_secs(30)).is_none());
14775        assert!(canonical_unit(Duration::from_secs(120)).is_none());
14776        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
14777        // Sub-second windows: even `Duration::from_millis(1000)` is
14778        // exactly 1s and accepted; `Duration::from_millis(500)` is
14779        // sub-second and rejected.
14780        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
14781        assert!(canonical_unit(Duration::from_millis(500)).is_none());
14782        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
14783    }
14784
14785    #[test]
14786    fn rate_limit_unit_table_projections_are_mutual_inverses() {
14787        // Bidirection pin against the closed-set typed enum
14788        // [`RateLimitUnit`] arm-table (the canonical
14789        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
14790        // of the rate-limit unit surface reads from). The two
14791        // projection directions [`RateLimitUnit::from_suffix`] /
14792        // [`RateLimitUnit::window`] (str → Duration, exposed as one
14793        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
14794        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
14795        // (Duration → str, exposed as one typed dispatch through
14796        // [`RateLimit::canonical_unit`] composed with
14797        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
14798        // codec's parse arm ([`rate_limit_codec::parse`] via
14799        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
14800        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
14801        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
14802        // via [`RateLimit::canonical_unit`]) all key off. A future
14803        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
14804        // sub-second window) is one variant + one arm per method on the
14805        // closed-set enum; the compiler-enforced exhaustiveness on
14806        // every consumer's `match self` arms picks it up by
14807        // construction. This pin enshrines that both projection
14808        // directions agree on every canonical arm row and neither
14809        // leaks a spurious entry the other doesn't recognize.
14810        //
14811        // Predecessor: this test previously read the two vestigial
14812        // module-private free helpers `rate_limit_window_unit` and
14813        // `rate_limit_window_from_unit` on the `Duration → &str` and
14814        // `&str → Duration` axes; the former was deleted after its
14815        // sole production consumer ([`rate_limit_codec::render`])
14816        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
14817        // the latter is folded here into the substrate primitive
14818        // [`RateLimitUnit::window_from_suffix`] so both projection
14819        // directions live on the closed-set enum's arm-table.
14820        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
14821            let window = super::RateLimitUnit::window_from_suffix(unit)
14822                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
14823            assert_eq!(
14824                window,
14825                Duration::from_secs(secs),
14826                "unit {unit:?} must resolve to {secs}s"
14827            );
14828            let projected_suffix = RateLimit { rate: 1, window }
14829                .canonical_unit()
14830                .map(super::RateLimitUnit::as_suffix);
14831            assert_eq!(
14832                projected_suffix,
14833                Some(unit),
14834                "Duration({secs}s) must render as {unit:?} \
14835                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
14836            );
14837        }
14838        // Non-table units yield None on the `unit → Duration`
14839        // projection — a future `"d"` addition to the table would
14840        // flip this arm; today it pins the current three-row table's
14841        // rejection semantics.
14842        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
14843        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
14844        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
14845        // Non-table Durations yield None on the `Duration → unit`
14846        // projection — pins that the two projections agree on the
14847        // "not in the table" semantic too, so a drift where the
14848        // parse-side accepts a value the render-side can't emit is
14849        // a build error at the two-arm pair, not a silent codec
14850        // round-trip break.
14851        let projected_suffix = |window: Duration| -> Option<&'static str> {
14852            RateLimit { rate: 1, window }
14853                .canonical_unit()
14854                .map(super::RateLimitUnit::as_suffix)
14855        };
14856        assert!(projected_suffix(Duration::from_secs(2)).is_none());
14857        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
14858        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
14859    }
14860
14861    #[test]
14862    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
14863        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
14864        // substrate-primitive `&str → Duration` associated method the
14865        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
14866        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
14867        // to the same [`Duration`] the two-step composition
14868        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
14869        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
14870        // `"MIN"`) must project to [`None`] on both paths. A future
14871        // implementation of `window_from_suffix` that took a shortcut
14872        // through a per-suffix `match` table (bypassing the arm-table's
14873        // `Self::from_suffix` scan and the arm-table's `Self::window`
14874        // dispatch) would silently split the accept-set — the parse
14875        // arm would accept a suffix the enum's arm-table doesn't know,
14876        // or reject a suffix the enum's arm-table does; this pin
14877        // surfaces that drift at caixa-core build time rather than at a
14878        // downstream serde round-trip audit on a live `MeshPolicy`.
14879        //
14880        // Same byte-parity discipline the sibling
14881        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
14882        // pin carries on the peer `Duration → RateLimitUnit` axis via
14883        // [`RateLimit::canonical_unit`], and the peer
14884        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14885        // carries on the bidirectional arm-table axis — extended here
14886        // onto the fifth (and last unlifted) projection axis on the
14887        // closed-set enum's arm-table.
14888        let composition = |suffix: &str| -> Option<Duration> {
14889            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
14890        };
14891        for suffix in ["s", "m", "h"] {
14892            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14893            let via_composition = composition(suffix);
14894            assert_eq!(
14895                via_method, via_composition,
14896                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14897                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
14898                 method must delegate to the arm-table's two typed dispatches, \
14899                 not shortcut through a per-suffix match table"
14900            );
14901            assert!(
14902                via_method.is_some(),
14903                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
14904                 RateLimitUnit::window_from_suffix"
14905            );
14906        }
14907        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
14908            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14909            let via_composition = composition(suffix);
14910            assert_eq!(
14911                via_method, via_composition,
14912                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14913                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
14914                 axis too"
14915            );
14916            assert!(
14917                via_method.is_none(),
14918                "non-arm suffix {suffix:?} must project to None via \
14919                 RateLimitUnit::window_from_suffix — a future extension that \
14920                 accepted this suffix without a corresponding arm on the enum \
14921                 would split the codec's parse-accepted set from the enum's \
14922                 arm-table"
14923            );
14924        }
14925        // And the codec's parse arm now reads through this method: a
14926        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
14927        // the same `Duration` the method returns for its unit, closing
14928        // the two-consumer drift surface (the codec's parse arm and the
14929        // enum's arm-table) with one typed dispatch on the substrate
14930        // primitive.
14931        for suffix in ["s", "m", "h"] {
14932            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
14933            let mp: MeshPolicy = serde_json::from_str(&wire)
14934                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
14935            let parsed = mp.rate_limit().expect("rate_limit payload present");
14936            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
14937                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
14938            assert_eq!(
14939                parsed.window(),
14940                via_method,
14941                "codec parse arm on {wire:?} must resolve the window through \
14942                 RateLimitUnit::window_from_suffix, not a divergent path"
14943            );
14944        }
14945    }
14946
14947    #[test]
14948    fn rate_limit_unit_all_enumerates_every_arm_once() {
14949        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
14950        // enumerate every arm of the closed-set enum exactly once, in
14951        // the canonical shortest-to-longest window order (Second before
14952        // Minute before Hour) — the same order the sibling
14953        // [`crate::supervisor::RestartStrategy`] /
14954        // [`crate::supervisor::RestartPolicy`] /
14955        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
14956        // typed enums carry (the arm declared first is the arm listed
14957        // first). A future variant addition that extends the enum
14958        // without appending to [`RateLimitUnit::ALL`] leaves the
14959        // exhaustive iteration surface silently short one arm — the
14960        // codec's parse arm would then reject the new suffix even
14961        // though the enum knows it. This pin closes the drift.
14962        assert_eq!(
14963            super::RateLimitUnit::ALL,
14964            &[
14965                super::RateLimitUnit::Second,
14966                super::RateLimitUnit::Minute,
14967                super::RateLimitUnit::Hour,
14968            ],
14969            "RateLimitUnit::ALL must enumerate every arm exactly once, \
14970             in canonical shortest-to-longest window order"
14971        );
14972    }
14973
14974    #[test]
14975    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
14976        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
14977        // every arm's [`RateLimitUnit::as_suffix`] output must parse
14978        // back through [`RateLimitUnit::from_suffix`] to the same
14979        // variant. A future arm addition that lands `as_suffix` but
14980        // forgets `from_suffix` (`from_suffix` iterates
14981        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
14982        // is the load-bearing carrier of the round-trip; the sibling
14983        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
14984        // the `ALL` half) trips here at caixa-core build time rather
14985        // than surfacing as a codec round-trip miss (a `render` emit
14986        // that lands a suffix the paired `parse` cannot decode).
14987        for unit in super::RateLimitUnit::ALL {
14988            let suffix = unit.as_suffix();
14989            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
14990                panic!(
14991                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
14992                     RateLimitUnit::as_suffix output — got None for {unit:?}"
14993                )
14994            });
14995            assert_eq!(
14996                parsed, *unit,
14997                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
14998                 must return RateLimitUnit::{unit:?}"
14999            );
15000        }
15001    }
15002
15003    #[test]
15004    fn rate_limit_unit_from_window_and_window_round_trip() {
15005        // Total round-trip pin on the `(from_window, window)` pair:
15006        // every arm's [`RateLimitUnit::window`] output must parse back
15007        // through [`RateLimitUnit::from_window`] to the same variant.
15008        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
15009        // on the peer `Duration` axis — the two round-trip pins
15010        // together enshrine that both projections of the typed
15011        // canonical-unit bijection are total on the arm-set.
15012        for unit in super::RateLimitUnit::ALL {
15013            let window = unit.window();
15014            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
15015                panic!(
15016                    "RateLimitUnit::from_window({window:?}) must accept every \
15017                     RateLimitUnit::window output — got None for {unit:?}"
15018                )
15019            });
15020            assert_eq!(
15021                parsed, *unit,
15022                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
15023                 must return RateLimitUnit::{unit:?}"
15024            );
15025        }
15026    }
15027
15028    #[test]
15029    fn rate_limit_unit_projections_are_pairwise_distinct() {
15030        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
15031        // [`RateLimitUnit::window`] outputs must be pairwise distinct
15032        // across every arm — an accidental copy-paste flip that
15033        // reroutes one arm's suffix or window to also match another
15034        // silently collapses two arms onto one, so
15035        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
15036        // (both using `find` on `Self::ALL`) would return whichever
15037        // arm the linear scan lands on first — a match-arm-ordering-
15038        // dependent outcome the closed-set typed-enum shape is meant
15039        // to rule out structurally. Peer of the sibling
15040        // `caixa_kind_wire_consts_are_pairwise_distinct` /
15041        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
15042        // other closed-set typed-enum discriminator axes.
15043        let all = super::RateLimitUnit::ALL;
15044        for (i, a) in all.iter().enumerate() {
15045            for (j, b) in all.iter().enumerate() {
15046                if i != j {
15047                    assert_ne!(
15048                        a.as_suffix(),
15049                        b.as_suffix(),
15050                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
15051                         must be distinct — a collision silently collapses two \
15052                         arms onto one under from_suffix's linear scan"
15053                    );
15054                    assert_ne!(
15055                        a.window(),
15056                        b.window(),
15057                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
15058                         must be distinct — a collision silently collapses two \
15059                         arms onto one under from_window's linear scan"
15060                    );
15061                }
15062            }
15063        }
15064    }
15065
15066    #[test]
15067    fn rate_limit_unit_display_routes_through_as_suffix() {
15068        // Route pin: [`std::fmt::Display`] must byte-equal
15069        // [`RateLimitUnit::as_suffix`] on every arm — the single
15070        // source of truth for the canonical suffix. A future
15071        // reimplementation that hand-rolls the arms instead of
15072        // delegating to [`RateLimitUnit::as_suffix`] would silently
15073        // desynchronize `format!("{u}")` from the codec's parse arm
15074        // (which uses `as_suffix` to compare suffixes). Peer of the
15075        // sibling `caixa_kind_display_routes_through_as_str_helper` /
15076        // `placement_strategy_display_routes_through_as_str_helper`
15077        // pins on the peer closed-set typed-enum Display axes.
15078        for unit in super::RateLimitUnit::ALL {
15079            assert_eq!(
15080                unit.to_string(),
15081                unit.as_suffix(),
15082                "RateLimitUnit::{unit:?} Display must route through \
15083                 as_suffix (single source of truth: the canonical suffix \
15084                 the codec parses and renders)"
15085            );
15086        }
15087    }
15088
15089    #[test]
15090    fn rate_limit_unit_from_window_rejects_non_canonical() {
15091        // Rejection pin on the parser's accept-set: any Duration
15092        // outside the three-arm [`RateLimitUnit::window`] output set
15093        // (sub-second residue, or a second-magnitude outside `{1, 60,
15094        // 3600}`) must return `None`. A future accidental widening of
15095        // the accept-set (rounding down sub-second residue to the
15096        // nearest arm, admitting `Duration::from_secs(30)` as a
15097        // half-minute unit) would silently drift the parser's accept-
15098        // set from the emitter's — a validated slot with a
15099        // non-canonical window would then round-trip through the
15100        // codec to a canonical form the author never wrote.
15101        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
15102        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
15103        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
15104        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
15105        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
15106        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
15107        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
15108    }
15109
15110    #[test]
15111    fn rate_limit_unit_from_suffix_rejects_unknown() {
15112        // Rejection pin on the suffix parser's accept-set: any string
15113        // outside the three-arm [`RateLimitUnit::as_suffix`] output
15114        // set must return `None`. Peer of the sibling
15115        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
15116        // the [`crate::CaixaKind`] `from_wire` accept-set.
15117        for bad in [
15118            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
15119            " s",
15120        ] {
15121            assert!(
15122                super::RateLimitUnit::from_suffix(bad).is_none(),
15123                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
15124                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
15125                 outputs"
15126            );
15127        }
15128    }
15129
15130    #[test]
15131    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
15132        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
15133        // every canonical `:window` magnitude the validate gate
15134        // accepts must map to the paired [`RateLimitUnit`] arm through
15135        // this accessor. A future validate-gate rebrand that widened
15136        // the accepted-window set without extending [`RateLimitUnit`]
15137        // would silently split the accessor's `Some`-return set from
15138        // the validate gate's accept-set — a slot that satisfies
15139        // validate would land at the accessor with `None`, so a
15140        // consumer past validate that pattern-matches on the returned
15141        // `Some` would silently miss the newly-accepted magnitude.
15142        for (window_secs, expected) in [
15143            (1u64, super::RateLimitUnit::Second),
15144            (60, super::RateLimitUnit::Minute),
15145            (3600, super::RateLimitUnit::Hour),
15146        ] {
15147            let rl = RateLimit {
15148                rate: 100,
15149                window: Duration::from_secs(window_secs),
15150            };
15151            assert_eq!(
15152                rl.canonical_unit(),
15153                Some(expected),
15154                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
15155                 must return Some({expected:?})"
15156            );
15157        }
15158        // Non-canonical windows the validate gate rejects also return
15159        // None here — the accessor is the typed-enum projection of
15160        // the sibling `is_canonical_rate_limit_window` predicate.
15161        let bad = RateLimit {
15162            rate: 100,
15163            window: Duration::from_secs(30),
15164        };
15165        assert!(
15166            bad.canonical_unit().is_none(),
15167            "RateLimit with a non-canonical window must return None from \
15168             canonical_unit — the validate gate rejects the same set"
15169        );
15170    }
15171
15172    #[test]
15173    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
15174        // Fail-before-pass-after byte-parity pin: for every canonical
15175        // window the [`rate_limit_codec::render`] arm's emitted string
15176        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
15177        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
15178        // the vestigial free helper [`rate_limit_window_unit`] (a
15179        // `find_map`-walked `Duration → &'static str` delegate) onto the
15180        // substrate primitive [`RateLimit::canonical_unit`] typed method
15181        // (a closed-set `match self.window` arm on
15182        // [`RateLimitUnit::from_window`], projected through
15183        // [`RateLimitUnit::as_suffix`] via the enum's
15184        // [`std::fmt::Display`] impl). A future re-routing of the render
15185        // arm through a differently-computed unit projection would break
15186        // this pin at build time rather than as a silent per-consumer
15187        // codec round-trip drift far from the substrate primitive edit.
15188        //
15189        // Sibling to the peer
15190        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
15191        // on the free-helper axis: that pin locks the two projections
15192        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
15193        // on the closed-set arm table; this pin locks the codec's render
15194        // arm reads through the typed accessor rather than the free
15195        // helper. Two production consumers of the canonical-unit axis
15196        // now key off one typed dispatch on the substrate primitive.
15197        for (window_secs, unit) in [
15198            (1u64, super::RateLimitUnit::Second),
15199            (60, super::RateLimitUnit::Minute),
15200            (3600, super::RateLimitUnit::Hour),
15201        ] {
15202            let rl = RateLimit {
15203                rate: 42,
15204                window: Duration::from_secs(window_secs),
15205            };
15206            let policy = MeshPolicy {
15207                rate_limit: Some(rl),
15208                ..Default::default()
15209            };
15210            let json = serde_json::to_string(&policy).unwrap();
15211            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
15212            assert!(
15213                json.contains(&expected),
15214                "rate_limit_codec::render must emit {expected} (via \
15215                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
15216                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
15217            );
15218            // And the accessor route resolves to the same typed unit
15219            // the render arm's Display formatting is asked to produce —
15220            // so a future edit that split the two paths (one through
15221            // the accessor, one through a re-introduced free helper)
15222            // trips this pin.
15223            assert_eq!(
15224                rl.canonical_unit(),
15225                Some(unit),
15226                "RateLimit::canonical_unit must return Some({unit:?}) for a \
15227                 {window_secs}s window; the codec render arm reads the same \
15228                 typed unit through this accessor"
15229            );
15230        }
15231    }
15232
15233    #[test]
15234    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
15235        // Fail-before-pass-after byte-parity pin on the validate gate's
15236        // canonical-window shape probe: every non-canonical `:window`
15237        // the free-helper predicate [`is_canonical_rate_limit_window`]
15238        // rejects is also rejected by the substrate primitive
15239        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
15240        // gate now reads through, and vice versa on the accepted set
15241        // (the three canonical windows). Locks the migration from the
15242        // free helper onto the substrate primitive: a future re-routing
15243        // of one of the two paths through a differently-computed unit
15244        // projection would silently split the codec's accepted set from
15245        // the validate gate's accepted set — a two-consumer drift the
15246        // codec-round-trip pin
15247        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
15248        // above closes on the render arm and this pin closes on the
15249        // validate arm.
15250        for canonical_window_secs in [1u64, 60, 3600] {
15251            let mut s = three_member_spec();
15252            let rl = RateLimit {
15253                rate: 100,
15254                window: Duration::from_secs(canonical_window_secs),
15255            };
15256            s.politicas.rate_limit = Some(rl);
15257            assert!(
15258                s.validate().is_ok(),
15259                "canonical {canonical_window_secs}s window must pass \
15260                 validate_politicas — the validate gate now reads \
15261                 RateLimit::canonical_unit().is_none() and the accessor \
15262                 returns Some on every canonical arm"
15263            );
15264            assert!(
15265                rl.canonical_unit().is_some(),
15266                "canonical {canonical_window_secs}s window must resolve to \
15267                 Some on RateLimit::canonical_unit — the validate gate reads \
15268                 this accessor directly"
15269            );
15270        }
15271        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
15272            let mut s = three_member_spec();
15273            let rl = RateLimit {
15274                rate: 100,
15275                window: Duration::from_secs(non_canonical_window_secs),
15276            };
15277            s.politicas.rate_limit = Some(rl);
15278            assert_eq!(
15279                s.validate().unwrap_err(),
15280                AplicacaoError::PolicyRateLimitWindowNotCanonical {
15281                    window: rl.window(),
15282                },
15283                "non-canonical {non_canonical_window_secs}s window must be \
15284                 rejected by validate_politicas — the validate gate now \
15285                 keys off RateLimit::canonical_unit().is_none()"
15286            );
15287            assert!(
15288                rl.canonical_unit().is_none(),
15289                "non-canonical {non_canonical_window_secs}s window must \
15290                 resolve to None on RateLimit::canonical_unit — the two \
15291                 paths (the free helper the validate gate previously read \
15292                 and the substrate primitive the validate gate now reads) \
15293                 must agree on the same rejected set"
15294            );
15295        }
15296        // And the substrate-primitive [`RateLimit::canonical_unit`]
15297        // accessor's accepted-window set matches the codec's parse arm's
15298        // accepted-suffix set on every canonical / non-canonical shape,
15299        // so a future silent drift between the codec's accepted set and
15300        // the validate gate's accepted set is a build error at test time
15301        // (both consumers key off the same closed-set enum's `match self`
15302        // arms). The predecessor free helper `is_canonical_rate_limit_window`
15303        // — a delegate that composed [`RateLimitUnit::from_window`] with
15304        // `.is_some()` — was deleted after this migration; the
15305        // canonical-window set now lives on exactly one typed dispatch
15306        // on the substrate primitive.
15307        for (secs, expected) in [
15308            (1u64, true),
15309            (60, true),
15310            (3600, true),
15311            (2, false),
15312            (30, false),
15313            (86_400, false),
15314        ] {
15315            let window = Duration::from_secs(secs);
15316            let rl = RateLimit { rate: 1, window };
15317            assert_eq!(
15318                rl.canonical_unit().is_some(),
15319                expected,
15320                "RateLimit::canonical_unit().is_some() must agree with the \
15321                 codec-accepted canonical-window set on {secs}s"
15322            );
15323            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
15324                1 => "s",
15325                60 => "m",
15326                3600 => "h",
15327                _ => return,
15328            })
15329            .is_some_and(|d| d == window);
15330            if expected {
15331                assert!(
15332                    suffix_from_axis,
15333                    "the codec's `&str → Duration` axis \
15334                     ({secs}s) must round-trip to the same Duration the \
15335                     substrate primitive's accessor returns Some on"
15336                );
15337            }
15338        }
15339    }
15340
15341    #[test]
15342    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
15343        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15344        // derive: for each of the three variants, exactly one of the
15345        // generated `is_second` / `is_minute` / `is_hour` predicates
15346        // returns `true` and the other two return `false`. Peer of
15347        // the sibling
15348        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
15349        // sibling `IsVariant`-derived closed-set typed-enum pins.
15350        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
15351            (super::RateLimitUnit::Second, [true, false, false]),
15352            (super::RateLimitUnit::Minute, [false, true, false]),
15353            (super::RateLimitUnit::Hour, [false, false, true]),
15354        ];
15355        for (variant, expected) in rows {
15356            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
15357            assert_eq!(
15358                observed, expected,
15359                "RateLimitUnit::{variant:?} is_* predicates must partition \
15360                 the arm set (second, minute, hour); got {observed:?}"
15361            );
15362        }
15363    }
15364
15365    #[test]
15366    fn rejects_policy_timeout_sub_millisecond() {
15367        // A purely sub-millisecond `Duration` (`from_micros(500)` =
15368        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
15369        // arm passes — but `as_millis() == 0`, so the shared codec's
15370        // `render` arm returns the literal `"0s"`, which the
15371        // codec's `parse` arm then deserializes as `Duration::ZERO`
15372        // and the `PolicyTimeoutZero` zero-floor gate would reject
15373        // on re-validate. Pin the rejection at the typed slot's
15374        // canonical-floor gate so the round-trip break surfaces at
15375        // validate time, naming the offending `Duration`, rather
15376        // than at the next serialize → deserialize round-trip far
15377        // from the source `caixa.lisp`.
15378        let mut s = three_member_spec();
15379        let timeout = Duration::from_micros(500);
15380        s.politicas.timeout = Some(timeout);
15381        assert_eq!(
15382            s.validate().unwrap_err(),
15383            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
15384        );
15385    }
15386
15387    #[test]
15388    fn rejects_policy_timeout_non_integer_millisecond() {
15389        // A `Duration` with non-integer-millisecond residue
15390        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
15391        // through the shared codec's `render` arm as `"1ms"` (the
15392        // `as_millis()` floor truncates), which the codec's `parse`
15393        // arm then deserializes as `Duration::from_millis(1)` =
15394        // 1_000_000 ns — silently *different* from the original.
15395        // Pin the rejection so this round-trip break surfaces at
15396        // validate time, where the offending `Duration` is named,
15397        // rather than as a silent value-laundered round-trip on the
15398        // next codec round-trip.
15399        let mut s = three_member_spec();
15400        let timeout = Duration::from_micros(1500);
15401        s.politicas.timeout = Some(timeout);
15402        assert_eq!(
15403            s.validate().unwrap_err(),
15404            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
15405        );
15406    }
15407
15408    #[test]
15409    fn accepts_policy_timeout_integer_millisecond_forms() {
15410        // The codec's accepted set — integer multiples of 1ms — is
15411        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
15412        // `1h` all pass the canonical gate. Pin the canonical-forms
15413        // sweep so a future tightening of the codec's grammar (e.g.
15414        // dropping `:ms`) surfaces here as a test failure rather
15415        // than a silent contract narrowing on the typed slot.
15416        for timeout in [
15417            Duration::from_millis(1),
15418            Duration::from_millis(500),
15419            Duration::from_millis(1500),
15420            Duration::from_secs(30),
15421            Duration::from_secs(120),
15422            Duration::from_secs(3600),
15423        ] {
15424            let mut s = three_member_spec();
15425            s.politicas.timeout = Some(timeout);
15426            s.validate()
15427                .expect("integer-millisecond :timeout must validate");
15428        }
15429    }
15430
15431    #[test]
15432    fn policy_timeout_zero_takes_precedence_over_canonical() {
15433        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
15434        // pass the canonical-millisecond gate; the more self-locating
15435        // `PolicyTimeoutZero` arm (which names the omit-axis
15436        // remediation directly) must fire first. Pin the ordering so
15437        // a future refactor that reorders the arms surfaces here as a
15438        // test failure rather than a silent diagnostic regression.
15439        let mut s = three_member_spec();
15440        s.politicas.timeout = Some(Duration::ZERO);
15441        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15442    }
15443
15444    #[test]
15445    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
15446        // The diagnostic envelope carries the offending `Duration`
15447        // verbatim so the author can grep their `caixa.lisp` for
15448        // `:timeout "<value>"` and fix it in one edit. Same
15449        // diagnostic shape every other typed-slot canonical-form
15450        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
15451        // peer `:rate-limit :window` axis.
15452        let mut s = three_member_spec();
15453        let timeout = Duration::from_nanos(1_000_001);
15454        s.politicas.timeout = Some(timeout);
15455        match s.validate().unwrap_err() {
15456            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
15457                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
15458            }
15459            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
15460        }
15461    }
15462
15463    #[test]
15464    fn rejects_policy_timeout_above_cap() {
15465        // The fail-before-pass-after pin: 3601s = 1h + 1s is
15466        // structurally one canonical-tick past the
15467        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
15468        // integer-millisecond magnitude the canonical-form arm above
15469        // accepts cleanly, that the codec round-trips losslessly as
15470        // `"3601s"`, and that silently passed validate on every
15471        // pre-gate codebase because the typed slot's only checks were
15472        // the zero-floor and canonical-form arms. The mesh-level
15473        // deadline degenerates only at the runtime substrate (Envoy
15474        // / Cilium L7 timeout overlay) far from the source
15475        // `caixa.lisp` with no field naming the offending policy.
15476        let mut s = three_member_spec();
15477        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
15478        s.politicas.timeout = Some(timeout);
15479        assert_eq!(
15480            s.validate().unwrap_err(),
15481            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
15482        );
15483    }
15484
15485    #[test]
15486    fn rejects_policy_timeout_one_millisecond_above_cap() {
15487        // Boundary case: exactly 1ms past the cap (the granularity
15488        // the canonical-form gate enforces). Catches a future
15489        // "strictly less than" half-measure and pins the diagnostic
15490        // to name the offending `Duration` verbatim. Peer of
15491        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
15492        // boundary pin on the sibling `:limits :memory` top edge.
15493        let mut s = three_member_spec();
15494        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
15495        s.politicas.timeout = Some(timeout);
15496        assert_eq!(
15497            s.validate().unwrap_err(),
15498            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
15499        );
15500    }
15501
15502    #[test]
15503    fn rejects_policy_timeout_far_above_cap() {
15504        // The "obvious authoring footgun" case: a `(:timeout "24h")`
15505        // or `(:timeout "86400s")` — values the canonical-form arm
15506        // accepts as integer-millisecond magnitudes, the codec
15507        // round-trips losslessly through serde, but the mesh-level
15508        // policy cannot honor (a 24-hour synchronous-`:contratos`
15509        // deadline is operationally indistinguishable from
15510        // omit-the-axis). Until this gate landed validate accepted
15511        // it. Pin both common above-cap values (24h, 7d) so a future
15512        // relaxation that drops the upper bound surfaces here.
15513        for timeout in [
15514            Duration::from_secs(86_400),    // 24h
15515            Duration::from_secs(604_800),   // 7d
15516            Duration::from_secs(1_000_000), // ~11.5 days
15517        ] {
15518            let mut s = three_member_spec();
15519            s.politicas.timeout = Some(timeout);
15520            assert_eq!(
15521                s.validate().unwrap_err(),
15522                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
15523            );
15524        }
15525    }
15526
15527    #[test]
15528    fn accepts_policy_timeout_at_cap() {
15529        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
15530        // must validate. The cap is inclusive on the top edge,
15531        // matching the [`POLICY_RETRIES_MAX`] /
15532        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
15533        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
15534        // sibling capped axes. Pin the boundary explicitly so a
15535        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
15536        // instead of `>`) surfaces here as a test failure rather
15537        // than a silent contract narrowing.
15538        let mut s = three_member_spec();
15539        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
15540        s.validate()
15541            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
15542    }
15543
15544    #[test]
15545    fn accepts_policy_timeout_typical_values() {
15546        // The documented production-playbook band positive-control
15547        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
15548        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
15549        // plus a sweep through the long-running-workflow band
15550        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
15551        // validated set explicitly so a future tightening of the
15552        // ceiling surfaces here as a deliberate test edit, not a
15553        // silent contract narrowing.
15554        for timeout in [
15555            Duration::from_millis(1),
15556            Duration::from_millis(500),
15557            Duration::from_secs(1),
15558            Duration::from_secs(10),
15559            Duration::from_secs(15), // Envoy default
15560            Duration::from_secs(30),
15561            Duration::from_secs(60), // AWS App Mesh typical
15562            Duration::from_secs(300),
15563            Duration::from_secs(900),
15564            Duration::from_secs(1800),
15565            Duration::from_secs(3600), // exactly 1h, the cap
15566        ] {
15567            let mut s = three_member_spec();
15568            s.politicas.timeout = Some(timeout);
15569            s.validate()
15570                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
15571        }
15572    }
15573
15574    #[test]
15575    fn policy_timeout_zero_takes_precedence_over_cap() {
15576        // The cross-arm ordering pin: `Duration::ZERO` is
15577        // structurally outside both `>= 1ms` (zero-floor) and
15578        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
15579        // diagnostic is the more self-locating one (it directly
15580        // names the omit-axis remediation), so the validate gate
15581        // must fire on zero first. Same shape every other
15582        // zero-then-shape ordering on this surface uses
15583        // ([`AplicacaoError::PolicyRetriesZero`] then
15584        // [`AplicacaoError::PolicyRetriesExceedsCap`];
15585        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15586        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15587        let mut s = three_member_spec();
15588        s.politicas.timeout = Some(Duration::ZERO);
15589        assert_eq!(
15590            s.validate().unwrap_err(),
15591            AplicacaoError::PolicyTimeoutZero,
15592            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15593        );
15594    }
15595
15596    #[test]
15597    fn policy_timeout_canonical_takes_precedence_over_cap() {
15598        // The cross-arm ordering pin: a `Duration` that is *both*
15599        // sub-millisecond (non-canonical-form) and structurally
15600        // above the cap surfaces the canonical-form diagnostic
15601        // first, because the round-trip-shape break is the more
15602        // fundamental issue (the value can't even round-trip
15603        // through the codec, so the cap diagnostic naming
15604        // `1ms..=1h` would be misleading — there's no integer-ms
15605        // form of the offending value). Pin the order so a future
15606        // refactor that reorders the arms surfaces here as a test
15607        // failure rather than a silent diagnostic regression.
15608        let mut s = three_member_spec();
15609        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
15610        // *and* total magnitude above the 1h cap.
15611        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
15612        s.politicas.timeout = Some(timeout);
15613        assert_eq!(
15614            s.validate().unwrap_err(),
15615            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
15616            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15617        );
15618    }
15619
15620    #[test]
15621    fn policy_timeout_cap_diagnostic_carries_offending_value() {
15622        // The diagnostic-shape pin: the offending `Duration` is
15623        // carried verbatim into the
15624        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
15625        // surfaced error message names the value the author wrote
15626        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
15627        // exceeds the mesh-policy ceiling …"`), not just the cap.
15628        // Same self-locating diagnostic shape every other typed-cap
15629        // arm on this surface carries
15630        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
15631        // offending retry count verbatim).
15632        let mut s = three_member_spec();
15633        let timeout = Duration::from_secs(7200); // 2h
15634        s.politicas.timeout = Some(timeout);
15635        let err = s.validate().unwrap_err();
15636        assert!(
15637            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
15638            "got {err:?}"
15639        );
15640        let msg = err.to_string();
15641        assert!(
15642            msg.contains("7200"),
15643            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
15644        );
15645    }
15646
15647    #[test]
15648    fn policy_timeout_cap_pins_canonical_value() {
15649        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
15650        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
15651        // the shared duration codec emits as a clean canonical
15652        // string (`"<n>h"`). Pinning the literal value here surfaces
15653        // a future drift (a relaxation to 24h, a tightening to 5m)
15654        // as a deliberate test edit, not a silent contract
15655        // narrowing. Same shape every other typed-cap value pin on
15656        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
15657        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
15658        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
15659    }
15660
15661    #[test]
15662    fn policy_timeout_cap_value_round_trips_through_codec() {
15663        // The codec round-trip property the cap arm preserves: the
15664        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
15665        // the shared duration codec — every value at the cap renders
15666        // to a clean canonical string (`"1h"`) and parses back to
15667        // the same `Duration`. Pin this so a future drift between
15668        // the cap constant and the codec's largest emitted unit
15669        // surfaces here. Same shape every other typed boundary pin
15670        // on this surface uses
15671        // (`wasm32_memory_cap_matches_parsed_4_gib`).
15672        let policy = MeshPolicy {
15673            timeout: Some(POLICY_TIMEOUT_MAX),
15674            ..Default::default()
15675        };
15676        let json = serde_json::to_string(&policy).unwrap();
15677        // The codec emits `"1h"` for the canonical 1-hour magnitude.
15678        assert!(
15679            json.contains("\"1h\""),
15680            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
15681        );
15682        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15683        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
15684    }
15685
15686    #[test]
15687    fn rejects_circuit_breaker_window_sub_millisecond() {
15688        // Peer of the `:timeout` sub-millisecond arm on the second
15689        // typed-`Duration` `:politicas` axis: a purely sub-ms
15690        // `Duration` (`from_micros(500)`) renders through the shared
15691        // codec as `"0s"`, which the codec parses back to
15692        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
15693        // zero-floor gate then rejects on re-validate.
15694        let mut s = three_member_spec();
15695        let window = Duration::from_micros(500);
15696        s.politicas.circuit_breaker = Some(CircuitBreaker {
15697            max_failures: 5,
15698            window,
15699        });
15700        assert_eq!(
15701            s.validate().unwrap_err(),
15702            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
15703        );
15704    }
15705
15706    #[test]
15707    fn rejects_circuit_breaker_window_non_integer_millisecond() {
15708        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
15709        // with non-integer-millisecond residue renders through the
15710        // shared codec as the truncated `"<n>ms"` form, parsing back
15711        // to a *different* `Duration` on the next round-trip.
15712        let mut s = three_member_spec();
15713        let window = Duration::from_micros(1500);
15714        s.politicas.circuit_breaker = Some(CircuitBreaker {
15715            max_failures: 5,
15716            window,
15717        });
15718        assert_eq!(
15719            s.validate().unwrap_err(),
15720            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
15721        );
15722    }
15723
15724    #[test]
15725    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
15726        // The canonical-forms sweep on the breaker axis: every
15727        // integer-ms multiple the codec round-trips losslessly
15728        // passes the canonical gate.
15729        for window in [
15730            Duration::from_millis(1),
15731            Duration::from_millis(500),
15732            Duration::from_millis(1500),
15733            Duration::from_secs(30),
15734            Duration::from_secs(60),
15735            Duration::from_secs(3600),
15736        ] {
15737            let mut s = three_member_spec();
15738            s.politicas.circuit_breaker = Some(CircuitBreaker {
15739                max_failures: 5,
15740                window,
15741            });
15742            s.validate()
15743                .expect("integer-millisecond :circuit-breaker :window must validate");
15744        }
15745    }
15746
15747    #[test]
15748    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
15749        // `Duration::ZERO` would pass the canonical-ms gate (the
15750        // sub-ns residue is zero) but must surface the narrower
15751        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
15752        // remediation.
15753        let mut s = three_member_spec();
15754        s.politicas.circuit_breaker = Some(CircuitBreaker {
15755            max_failures: 5,
15756            window: Duration::ZERO,
15757        });
15758        assert_eq!(
15759            s.validate().unwrap_err(),
15760            AplicacaoError::PolicyBreakerZeroWindow
15761        );
15762    }
15763
15764    #[test]
15765    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
15766        // Both axes invalid: max_failures == 0 *and* window is
15767        // sub-ms. The validate gate must fire on max_failures first
15768        // (matching the existing ordering pin
15769        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
15770        // the existing diagnostic continues to lead with the simpler
15771        // "zero threshold" framing.
15772        let mut s = three_member_spec();
15773        s.politicas.circuit_breaker = Some(CircuitBreaker {
15774            max_failures: 0,
15775            window: Duration::from_micros(500),
15776        });
15777        assert_eq!(
15778            s.validate().unwrap_err(),
15779            AplicacaoError::PolicyBreakerZeroFailures
15780        );
15781    }
15782
15783    #[test]
15784    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
15785        let mut s = three_member_spec();
15786        let window = Duration::from_nanos(60_000_000_001);
15787        s.politicas.circuit_breaker = Some(CircuitBreaker {
15788            max_failures: 5,
15789            window,
15790        });
15791        match s.validate().unwrap_err() {
15792            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
15793                assert_eq!(w, window, "diagnostic must carry the offending Duration");
15794            }
15795            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
15796        }
15797    }
15798
15799    #[test]
15800    fn rejects_circuit_breaker_window_above_cap() {
15801        // The fail-before-pass-after pin: 3601s = 1h + 1s is
15802        // structurally one canonical-tick past the
15803        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
15804        // integer-millisecond magnitude the canonical-form arm above
15805        // accepts cleanly, that the codec round-trips losslessly as
15806        // `"3601s"`, and that silently passed validate on every
15807        // pre-gate codebase because the typed slot's only checks were
15808        // the zero-floor and canonical-form arms. The
15809        // rolling-window-to-lifetime-counter degeneration surfaces
15810        // only at the runtime substrate (Envoy's outlier_detection
15811        // interval, the future CiliumClusterwideEnvoyConfig overlay)
15812        // far from the source `caixa.lisp` with no field naming the
15813        // offending policy.
15814        let mut s = three_member_spec();
15815        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15816        s.politicas.circuit_breaker = Some(CircuitBreaker {
15817            max_failures: 5,
15818            window,
15819        });
15820        assert_eq!(
15821            s.validate().unwrap_err(),
15822            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15823        );
15824    }
15825
15826    #[test]
15827    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
15828        // Boundary case: exactly 1ms past the cap (the granularity the
15829        // canonical-form gate enforces). Catches a future "strictly
15830        // less than" half-measure and pins the diagnostic to name the
15831        // offending `Duration` verbatim. Peer of
15832        // `rejects_policy_timeout_one_millisecond_above_cap` on the
15833        // sibling duration-typed `:politicas :timeout` top edge.
15834        let mut s = three_member_spec();
15835        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
15836        s.politicas.circuit_breaker = Some(CircuitBreaker {
15837            max_failures: 5,
15838            window,
15839        });
15840        assert_eq!(
15841            s.validate().unwrap_err(),
15842            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15843        );
15844    }
15845
15846    #[test]
15847    fn rejects_circuit_breaker_window_far_above_cap() {
15848        // The "obvious authoring footgun" case: a `(:window "24h")` or
15849        // `(:window "86400s")` — values the canonical-form arm
15850        // accepts as integer-millisecond magnitudes, the codec
15851        // round-trips losslessly through serde, but the
15852        // rolling-window breaker contract cannot honor (a 24-hour
15853        // rolling failure window is operationally a lifetime counter).
15854        // Until this gate landed validate accepted it. Pin both common
15855        // above-cap values (24h, 7d) so a future relaxation that
15856        // drops the upper bound surfaces here.
15857        for window in [
15858            Duration::from_secs(86_400),    // 24h
15859            Duration::from_secs(604_800),   // 7d
15860            Duration::from_secs(1_000_000), // ~11.5 days
15861        ] {
15862            let mut s = three_member_spec();
15863            s.politicas.circuit_breaker = Some(CircuitBreaker {
15864                max_failures: 5,
15865                window,
15866            });
15867            assert_eq!(
15868                s.validate().unwrap_err(),
15869                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15870            );
15871        }
15872    }
15873
15874    #[test]
15875    fn accepts_circuit_breaker_window_at_cap() {
15876        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
15877        // (1h) — must validate. The cap is inclusive on the top edge,
15878        // matching the [`POLICY_TIMEOUT_MAX`] /
15879        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
15880        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
15881        // sibling capped axes. Pin the boundary explicitly so a
15882        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
15883        // instead of `>`) surfaces here as a test failure rather than
15884        // a silent contract narrowing.
15885        let mut s = three_member_spec();
15886        s.politicas.circuit_breaker = Some(CircuitBreaker {
15887            max_failures: 5,
15888            window: POLICY_BREAKER_WINDOW_MAX,
15889        });
15890        s.validate()
15891            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
15892    }
15893
15894    #[test]
15895    fn accepts_circuit_breaker_window_typical_values() {
15896        // The documented production-playbook band positive-control
15897        // sweep — every value Hystrix / resilience4j / Istio / Envoy
15898        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
15899        // through the long-tail failure-detection band (15m, 30m, 1h)
15900        // the cap accepts. Pin the inclusive validated set explicitly
15901        // so a future tightening of the ceiling surfaces here as a
15902        // deliberate test edit, not a silent contract narrowing.
15903        for window in [
15904            Duration::from_millis(1),
15905            Duration::from_millis(500),
15906            Duration::from_secs(1),
15907            Duration::from_secs(10), // Hystrix / Istio / Envoy default
15908            Duration::from_secs(30),
15909            Duration::from_secs(60),  // resilience4j typical
15910            Duration::from_secs(300), // AWS App Mesh typical
15911            Duration::from_secs(900),
15912            Duration::from_secs(1800),
15913            Duration::from_secs(3600), // exactly 1h, the cap
15914        ] {
15915            let mut s = three_member_spec();
15916            s.politicas.circuit_breaker = Some(CircuitBreaker {
15917                max_failures: 5,
15918                window,
15919            });
15920            s.validate()
15921                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
15922        }
15923    }
15924
15925    #[test]
15926    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
15927        // The cross-arm ordering pin: `Duration::ZERO` is structurally
15928        // outside both `>= 1ms` (zero-floor) and
15929        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
15930        // diagnostic is the more self-locating one (it directly names
15931        // the omit-axis remediation), so the validate gate must fire
15932        // on zero first. Same shape every other zero-then-cap
15933        // ordering on this surface uses
15934        // ([`AplicacaoError::PolicyTimeoutZero`] then
15935        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
15936        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15937        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15938        let mut s = three_member_spec();
15939        s.politicas.circuit_breaker = Some(CircuitBreaker {
15940            max_failures: 5,
15941            window: Duration::ZERO,
15942        });
15943        assert_eq!(
15944            s.validate().unwrap_err(),
15945            AplicacaoError::PolicyBreakerZeroWindow,
15946            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15947        );
15948    }
15949
15950    #[test]
15951    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
15952        // The cross-arm ordering pin: a `Duration` that is *both*
15953        // sub-millisecond (non-canonical-form) and structurally above
15954        // the cap surfaces the canonical-form diagnostic first,
15955        // because the round-trip-shape break is the more fundamental
15956        // issue (the value can't even round-trip through the codec, so
15957        // the cap diagnostic naming `1ms..=1h` would be misleading —
15958        // there's no integer-ms form of the offending value). Pin the
15959        // order so a future refactor that reorders the arms surfaces
15960        // here as a test failure rather than a silent diagnostic
15961        // regression. Peer of
15962        // `policy_timeout_canonical_takes_precedence_over_cap` on the
15963        // sibling duration-typed `:politicas :timeout` axis.
15964        let mut s = three_member_spec();
15965        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
15966        s.politicas.circuit_breaker = Some(CircuitBreaker {
15967            max_failures: 5,
15968            window,
15969        });
15970        assert_eq!(
15971            s.validate().unwrap_err(),
15972            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
15973            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15974        );
15975    }
15976
15977    #[test]
15978    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
15979        // The cross-arm ordering pin between the two breaker axes: a
15980        // `CircuitBreaker` whose *both* `max_failures` is above its
15981        // cap *and* `window` is above its cap surfaces the
15982        // max-failures cap diagnostic first, because the validate
15983        // gate visits the failures arm before the window arm. Pin the
15984        // order so a future refactor that reorders the breaker arms
15985        // surfaces here.
15986        let mut s = three_member_spec();
15987        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15988        s.politicas.circuit_breaker = Some(CircuitBreaker {
15989            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15990            window,
15991        });
15992        assert_eq!(
15993            s.validate().unwrap_err(),
15994            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15995                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
15996            },
15997            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
15998        );
15999    }
16000
16001    #[test]
16002    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
16003        // The diagnostic-shape pin: the offending `Duration` is
16004        // carried verbatim into the
16005        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
16006        // the surfaced error message names the value the author wrote
16007        // (`":politicas :circuit-breaker :window (Duration { secs:
16008        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
16009        // just the cap. Same self-locating diagnostic shape every
16010        // other typed-cap arm on this surface carries
16011        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
16012        // offending `Duration` verbatim).
16013        let mut s = three_member_spec();
16014        let window = Duration::from_secs(7200); // 2h
16015        s.politicas.circuit_breaker = Some(CircuitBreaker {
16016            max_failures: 5,
16017            window,
16018        });
16019        let err = s.validate().unwrap_err();
16020        assert!(
16021            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
16022            "got {err:?}"
16023        );
16024        let msg = err.to_string();
16025        assert!(
16026            msg.contains("7200"),
16027            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
16028        );
16029    }
16030
16031    #[test]
16032    fn circuit_breaker_window_cap_pins_canonical_value() {
16033        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
16034        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
16035        // shared duration codec emits as a clean canonical string
16036        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
16037        // the sibling duration-typed `:politicas :timeout` axis (the
16038        // two duration-typed `:politicas` axes share a uniform top
16039        // edge). Pinning the literal value here surfaces a future
16040        // drift (a relaxation to 24h, a tightening to 5m) as a
16041        // deliberate test edit, not a silent contract narrowing. Same
16042        // shape every other typed-cap value pin on this surface uses
16043        // (`policy_timeout_cap_pins_canonical_value`).
16044        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
16045        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
16046        assert_eq!(
16047            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
16048            "the two duration-typed `:politicas` caps share the same top edge"
16049        );
16050    }
16051
16052    #[test]
16053    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
16054        // The codec round-trip property the cap arm preserves: the
16055        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
16056        // through the shared duration codec — every value at the cap
16057        // renders to a clean canonical string (`"1h"`) and parses back
16058        // to the same `Duration`. Pin this so a future drift between
16059        // the cap constant and the codec's largest emitted unit
16060        // surfaces here. Same shape every other typed boundary pin on
16061        // this surface uses
16062        // (`policy_timeout_cap_value_round_trips_through_codec`).
16063        let policy = MeshPolicy {
16064            circuit_breaker: Some(CircuitBreaker {
16065                max_failures: 5,
16066                window: POLICY_BREAKER_WINDOW_MAX,
16067            }),
16068            ..Default::default()
16069        };
16070        let json = serde_json::to_string(&policy).unwrap();
16071        // The codec emits `"1h"` for the canonical 1-hour magnitude.
16072        assert!(
16073            json.contains("\"1h\""),
16074            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
16075        );
16076        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16077        assert_eq!(
16078            back.circuit_breaker.unwrap().window,
16079            POLICY_BREAKER_WINDOW_MAX
16080        );
16081    }
16082
16083    #[test]
16084    fn is_integer_millisecond_duration_predicate_tracks_codec() {
16085        // Pin the predicate's accepted set against the codec's
16086        // accepted set explicitly. The codec parses
16087        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
16088        // accepted value is an integer-millisecond multiple — so the
16089        // predicate must accept exactly that set. Same shape every
16090        // other predicate-on-the-typed-slot helper carries
16091        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
16092        // Read directly from the codec-owned predicate — the crate's
16093        // single source of truth every typed-`Duration` axis now routes
16094        // through via
16095        // [`crate::render::require_positive_canonical_bounded_duration`].
16096        use super::supervisor::duration_codec::is_integer_millisecond_duration;
16097        assert!(is_integer_millisecond_duration(Duration::ZERO));
16098        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
16099        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
16100        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
16101        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
16102        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
16103        // Non-integer-millisecond residue: rejected.
16104        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
16105        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
16106        assert!(!is_integer_millisecond_duration(Duration::from_micros(
16107            1500
16108        )));
16109        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
16110        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
16111            999_999
16112        )));
16113        // The 1-ns-past-1ms boundary: rejected (no longer a clean
16114        // integer-millisecond multiple).
16115        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
16116            1_000_001
16117        )));
16118    }
16119
16120    #[test]
16121    fn policy_timeout_validated_value_round_trips_through_codec() {
16122        // The structural property the canonical-ms gate enforces:
16123        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
16124        // round-trips losslessly through the shared `duration_codec`
16125        // (serialize → string → deserialize → equal value). Pin this
16126        // end-to-end so a future change to either side (the validate
16127        // gate's accepted granularity, the codec's parse/render unit
16128        // set) that breaks the alignment surfaces here. The
16129        // previous-state shape (typed slot accepts arbitrary
16130        // `Duration`, codec only round-trips integer-ms) would fail
16131        // this test for any `Duration::from_micros(1500)` timeout —
16132        // the validate gate now forecloses that.
16133        for timeout in [
16134            Duration::from_millis(1),
16135            Duration::from_millis(1500),
16136            Duration::from_secs(30),
16137            Duration::from_secs(3600),
16138        ] {
16139            let mut s = three_member_spec();
16140            s.politicas.timeout = Some(timeout);
16141            s.validate().unwrap();
16142            let json = serde_json::to_string(&s.politicas).unwrap();
16143            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16144            assert_eq!(
16145                back.timeout, s.politicas.timeout,
16146                "every validated :timeout must round-trip losslessly through the codec"
16147            );
16148        }
16149    }
16150
16151    #[test]
16152    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
16153        // Peer of the `:timeout` round-trip property on the breaker
16154        // axis.
16155        for window in [
16156            Duration::from_millis(1),
16157            Duration::from_millis(1500),
16158            Duration::from_secs(30),
16159            Duration::from_secs(3600),
16160        ] {
16161            let mut s = three_member_spec();
16162            s.politicas.circuit_breaker = Some(CircuitBreaker {
16163                max_failures: 5,
16164                window,
16165            });
16166            s.validate().unwrap();
16167            let json = serde_json::to_string(&s.politicas).unwrap();
16168            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16169            assert_eq!(
16170                back.circuit_breaker.unwrap().window,
16171                window,
16172                "every validated :circuit-breaker :window must round-trip losslessly"
16173            );
16174        }
16175    }
16176
16177    #[test]
16178    fn empty_politicas_validates() {
16179        // Omitting every policy axis is fine — defaults express "no
16180        // policy on this axis", not "policy = 0". The fixture's typical
16181        // values continue to validate; this test pins that
16182        // MeshPolicy::default() is a clean pass through validate().
16183        let mut s = three_member_spec();
16184        s.politicas = MeshPolicy::default();
16185        s.validate().unwrap();
16186    }
16187
16188    #[test]
16189    fn typical_politicas_validates_with_every_axis_set() {
16190        // The full §III.1 example block (timeout + retries + breaker +
16191        // mtls + rate-limit) — every axis nonzero — must remain a
16192        // clean pass.
16193        let mut s = three_member_spec();
16194        s.politicas = MeshPolicy {
16195            timeout: Some(Duration::from_secs(30)),
16196            retries: Some(3),
16197            circuit_breaker: Some(CircuitBreaker {
16198                max_failures: 5,
16199                window: Duration::from_secs(60),
16200            }),
16201            mtls_required: Some(true),
16202            rate_limit: Some(RateLimit {
16203                rate: 100,
16204                window: Duration::from_secs(1),
16205            }),
16206        };
16207        s.validate().unwrap();
16208    }
16209
16210    #[test]
16211    fn rejects_empty_cluster_name() {
16212        let mut s = three_member_spec();
16213        s.placement.clusters = vec!["rio".into(), "".into()];
16214        assert_eq!(
16215            s.validate().unwrap_err(),
16216            AplicacaoError::PlacementClusterEmpty
16217        );
16218    }
16219
16220    #[test]
16221    fn rejects_duplicate_cluster_names() {
16222        let mut s = three_member_spec();
16223        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
16224        let err = s.validate().unwrap_err();
16225        assert!(
16226            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
16227            "got {err:?}"
16228        );
16229    }
16230
16231    #[test]
16232    fn rejects_placement_cluster_with_uppercase() {
16233        // The canonical "I copied the cluster's display name verbatim"
16234        // typo — K8s context names are lowercase per DNS-1123 label
16235        // rule, but org docs often round-trip a TitleCase identifier
16236        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
16237        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
16238        // on the peer name axis.
16239        let mut s = three_member_spec();
16240        s.placement.clusters = vec!["Rio".into(), "mar".into()];
16241        let err = s.validate().unwrap_err();
16242        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
16243            panic!("expected PlacementClusterInvalid, got other variant");
16244        };
16245        assert_eq!(cluster, "Rio");
16246        assert!(
16247            reason.contains("uppercase"),
16248            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
16249        );
16250        assert!(
16251            reason.contains("\"rio\""),
16252            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
16253        );
16254    }
16255
16256    #[test]
16257    fn rejects_placement_cluster_with_underscore() {
16258        // The canonical "I'm thinking of an env var / hostname slug"
16259        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
16260        // schema. K8s context filtering on `my_cluster` silently misses
16261        // the cluster the author intended; the gate moves it to caixa-
16262        // build time. Same shape as `rejects_membro_caixa_with_underscore`
16263        // (3f9d7a0).
16264        let mut s = three_member_spec();
16265        s.placement.clusters = vec!["my_cluster".into()];
16266        let err = s.validate().unwrap_err();
16267        assert!(
16268            matches!(
16269                err,
16270                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
16271                    if cluster == "my_cluster" && reason.contains('_')
16272            ),
16273            "got {err:?}"
16274        );
16275    }
16276
16277    #[test]
16278    fn rejects_placement_cluster_with_dot() {
16279        // A `:placement :clusters` entry is a single DNS-1123 *label*,
16280        // not a subdomain — even though K8s context names sometimes
16281        // carry a dotted form via kubeconfig conventions, the strictest
16282        // floor among the use sites (DNS-1035 cluster.x-k8s.io
16283        // `metadata.name`, Cilium identity label values) wins. The "I
16284        // want to namespace my cluster names with `.`" intent is
16285        // expressed via `-` (`mar-east`).
16286        let mut s = three_member_spec();
16287        s.placement.clusters = vec!["team.rio".into()];
16288        let err = s.validate().unwrap_err();
16289        assert!(
16290            matches!(
16291                err,
16292                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
16293                    if cluster == "team.rio" && reason.contains('.')
16294            ),
16295            "got {err:?}"
16296        );
16297    }
16298
16299    #[test]
16300    fn rejects_placement_cluster_with_leading_hyphen() {
16301        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
16302        // with an alphanumeric. The K8s apiserver rejects `-rio`
16303        // outright; the rendered fan-out would emit a `metadata.name:
16304        // "-rio"` that fails admission far from the source caixa.lisp.
16305        let mut s = three_member_spec();
16306        s.placement.clusters = vec!["-rio".into()];
16307        let err = s.validate().unwrap_err();
16308        assert!(
16309            matches!(
16310                err,
16311                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
16312                    if cluster == "-rio" && reason.contains("start and end")
16313            ),
16314            "got {err:?}"
16315        );
16316    }
16317
16318    #[test]
16319    fn rejects_placement_cluster_with_trailing_hyphen() {
16320        // The symmetric arm of the boundary rule. Pin separately so
16321        // both ends are covered against a future relaxation that only
16322        // checks one boundary (parallel to
16323        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
16324        let mut s = three_member_spec();
16325        s.placement.clusters = vec!["rio-".into()];
16326        let err = s.validate().unwrap_err();
16327        assert!(
16328            matches!(
16329                err,
16330                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
16331                    if cluster == "rio-"
16332            ),
16333            "got {err:?}"
16334        );
16335    }
16336
16337    #[test]
16338    fn rejects_placement_cluster_with_unicode() {
16339        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
16340        // before it reaches K8s. The byte-by-byte ASCII validity check
16341        // rejects multi-byte UTF-8 sequences by the first byte that
16342        // fails `[a-z0-9-]`.
16343        let mut s = three_member_spec();
16344        s.placement.clusters = vec!["rió".into()];
16345        let err = s.validate().unwrap_err();
16346        assert!(
16347            matches!(
16348                err,
16349                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
16350                    if cluster == "rió"
16351            ),
16352            "got {err:?}"
16353        );
16354    }
16355
16356    #[test]
16357    fn rejects_placement_cluster_with_whitespace() {
16358        // Whitespace is the canonical "I pasted from a sketch / doc"
16359        // footgun. The apiserver rejects every cluster `metadata.name`
16360        // value carrying whitespace.
16361        let mut s = three_member_spec();
16362        s.placement.clusters = vec!["rio cluster".into()];
16363        let err = s.validate().unwrap_err();
16364        assert!(
16365            matches!(
16366                err,
16367                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
16368                    if cluster == "rio cluster"
16369            ),
16370            "got {err:?}"
16371        );
16372    }
16373
16374    #[test]
16375    fn rejects_placement_cluster_too_long() {
16376        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
16377        // pin. The diagnostic names both the cap (63) and the actual
16378        // length so the author can shorten in one edit. Mirrors
16379        // `rejects_membro_caixa_too_long` (3f9d7a0).
16380        let mut s = three_member_spec();
16381        let too_long = "a".repeat(64);
16382        s.placement.clusters = vec![too_long.clone()];
16383        let err = s.validate().unwrap_err();
16384        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
16385            panic!("expected PlacementClusterInvalid");
16386        };
16387        assert_eq!(cluster, too_long);
16388        assert!(
16389            reason.contains("63") && reason.contains("64"),
16390            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16391        );
16392    }
16393
16394    #[test]
16395    fn placement_cluster_max_length_validates() {
16396        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
16397        // future tightening (e.g. dropping to 62) surfaces here as a
16398        // regression, mirroring `membro_caixa_max_length_validates`
16399        // (3f9d7a0).
16400        let mut s = three_member_spec();
16401        s.placement.clusters = vec!["a".repeat(63)];
16402        s.validate().unwrap();
16403    }
16404
16405    #[test]
16406    fn accepts_canonical_placement_cluster_forms() {
16407        // The DNS-1123 label shapes a caixa author is realistically
16408        // going to write for cluster names: single-word lowercase
16409        // (`rio`), regional hyphen-joined (`mar-east`), single
16410        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
16411        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
16412        // Pin every leg so a future tightening that bans (e.g.) digit-
16413        // start identifiers surfaces here.
16414        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
16415            let mut s = three_member_spec();
16416            s.placement.clusters = vec![form.into()];
16417            s.validate().unwrap_or_else(|e| {
16418                panic!("canonical cluster form {form:?} must validate, got {e:?}")
16419            });
16420        }
16421    }
16422
16423    #[test]
16424    fn placement_cluster_empty_takes_precedence_over_invalid() {
16425        // Order pin: the existing `PlacementClusterEmpty` diagnostic
16426        // (which doesn't try to parse) fires before the new
16427        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
16428        // `:clusters` entry keeps its narrower error message — the new
16429        // gate would also reject `""`, but the empty-string arm is the
16430        // more self-locating diagnostic. Mirrors the
16431        // `membro_caixa_empty_takes_precedence_over_invalid` pin
16432        // (3f9d7a0).
16433        let mut s = three_member_spec();
16434        s.placement.clusters = vec!["rio".into(), "".into()];
16435        let err = s.validate().unwrap_err();
16436        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
16437    }
16438
16439    #[test]
16440    fn placement_cluster_invalid_fires_before_duplicate_check() {
16441        // Order pin: a malformed-shape `:clusters` entry surfaces *its
16442        // own* diagnostic, even when a later entry would otherwise
16443        // collapse onto a duplicate name. The per-entry shape gate runs
16444        // inline before the duplicate-key insert, parallel to
16445        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
16446        let mut s = three_member_spec();
16447        s.placement.clusters = vec!["Rio".into(), "rio".into()];
16448        let err = s.validate().unwrap_err();
16449        assert!(
16450            matches!(
16451                err,
16452                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
16453            ),
16454            "got {err:?}"
16455        );
16456    }
16457
16458    #[test]
16459    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
16460        // The diagnostic-shape pin: the error names the offending
16461        // `:clusters` value verbatim so the author can grep their
16462        // caixa.lisp without re-running the build, and carries a
16463        // non-empty `reason` naming the specific violation. Same shape
16464        // every typed-shape gate enshrines
16465        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
16466        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
16467        let mut s = three_member_spec();
16468        s.placement.clusters = vec!["BAD_CLUSTER".into()];
16469        let err = s.validate().unwrap_err();
16470        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
16471            panic!("expected PlacementClusterInvalid");
16472        };
16473        assert_eq!(cluster, "BAD_CLUSTER");
16474        assert!(
16475            !reason.is_empty(),
16476            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
16477        );
16478    }
16479
16480    #[test]
16481    fn rejects_sharded_with_empty_clusters() {
16482        // §III.1: Sharded uses :clusters as the shard pool. An empty
16483        // pool means "shard across no clusters" — meaningless, same as
16484        // Replicated with no hosts.
16485        let mut s = three_member_spec();
16486        s.placement.estrategia = PlacementStrategy::Sharded;
16487        s.placement.shard_key = Some("$tenantId".into());
16488        s.placement.clusters = vec![];
16489        assert!(matches!(
16490            s.validate().unwrap_err(),
16491            AplicacaoError::PlacementWithoutClusters {
16492                estrategia: PlacementStrategy::Sharded
16493            }
16494        ));
16495    }
16496
16497    #[test]
16498    fn rejects_sharded_with_empty_shard_key() {
16499        let mut s = three_member_spec();
16500        s.placement.estrategia = PlacementStrategy::Sharded;
16501        s.placement.shard_key = Some("".into());
16502        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
16503    }
16504
16505    #[test]
16506    fn rejects_shard_key_under_replicated_strategy() {
16507        // The fail-before-pass-after pin: a `:placement (:estrategia
16508        // Replicated :shard-key "tenantId")` manifest carries the
16509        // hash-keyed-distribution slot on a strategy that never consumes
16510        // it. Before the gate the typed slot's value silently vanished
16511        // at the renderer layer (caixa-mesh emits `placement.shardKey`
16512        // verbatim regardless of strategy; the Akka-style cluster-
16513        // sharding reconciler keys off `estrategia == Sharded` and
16514        // ignores the slot otherwise), with no diagnostic. Lifting the
16515        // rejection to a build-time gate makes the
16516        // `shard_key.is_some() == matches!(estrategia, Sharded)`
16517        // partition a structural property of every validated
16518        // [`Placement`].
16519        let mut s = three_member_spec();
16520        // The fixture already uses Replicated; just add a shard-key.
16521        s.placement.shard_key = Some("$tenantId".into());
16522        let err = s.validate().unwrap_err();
16523        let AplicacaoError::ShardKeyOnNonSharded {
16524            estrategia,
16525            shard_key,
16526        } = err
16527        else {
16528            panic!("expected ShardKeyOnNonSharded, got {err:?}");
16529        };
16530        assert_eq!(estrategia, PlacementStrategy::Replicated);
16531        assert_eq!(shard_key, "$tenantId");
16532    }
16533
16534    #[test]
16535    fn rejects_shard_key_under_singlenode_strategy() {
16536        // Peer of the Replicated case above on the SingleNode arm: OTP
16537        // distributed-app takeover (one cluster runs at a time) has no
16538        // hash-keyed routing axis to consume `:shard-key` either, so
16539        // the rejection fires on both non-Sharded arms uniformly.
16540        let mut s = three_member_spec();
16541        s.placement.estrategia = PlacementStrategy::SingleNode;
16542        s.placement.shard_key = Some("$tenantId".into());
16543        let err = s.validate().unwrap_err();
16544        let AplicacaoError::ShardKeyOnNonSharded {
16545            estrategia,
16546            shard_key,
16547        } = err
16548        else {
16549            panic!("expected ShardKeyOnNonSharded, got {err:?}");
16550        };
16551        assert_eq!(estrategia, PlacementStrategy::SingleNode);
16552        assert_eq!(shard_key, "$tenantId");
16553    }
16554
16555    #[test]
16556    fn rejects_empty_shard_key_under_replicated_strategy() {
16557        // The `Some("")` case under non-Sharded is rejected by
16558        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
16559        // fires before the empty-value gate), not
16560        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
16561        // the `Sharded` arm). Pin the partition so a future reorder of
16562        // the validate_placement match arms doesn't silently swap which
16563        // diagnostic the author sees — both are author errors, but
16564        // ShardKeyOnNonSharded names which strategy is the actual fix
16565        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
16566        // only says "pick a non-empty key".
16567        let mut s = three_member_spec();
16568        s.placement.shard_key = Some(String::new());
16569        let err = s.validate().unwrap_err();
16570        assert!(
16571            matches!(
16572                err,
16573                AplicacaoError::ShardKeyOnNonSharded {
16574                    estrategia: PlacementStrategy::Replicated,
16575                    ref shard_key,
16576                } if shard_key.is_empty()
16577            ),
16578            "got {err:?}"
16579        );
16580    }
16581
16582    #[test]
16583    fn replicated_without_shard_key_validates() {
16584        // The complement of the rejection: `:placement :estrategia
16585        // Replicated` with `:shard-key None` is the canonical happy
16586        // path on every existing fixture. Pin the no-shard-key case so
16587        // the new gate doesn't accidentally fire on `None`.
16588        let mut s = three_member_spec();
16589        assert!(matches!(
16590            s.placement.estrategia,
16591            PlacementStrategy::Replicated
16592        ));
16593        s.placement.shard_key = None;
16594        s.validate().unwrap();
16595    }
16596
16597    #[test]
16598    fn singlenode_without_shard_key_validates() {
16599        // Peer of the Replicated no-shard-key case on the SingleNode
16600        // arm — both non-Sharded strategies must validate cleanly when
16601        // the slot is omitted.
16602        let mut s = three_member_spec();
16603        s.placement.estrategia = PlacementStrategy::SingleNode;
16604        s.placement.shard_key = None;
16605        s.validate().unwrap();
16606    }
16607
16608    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
16609        // Fixture builder for the `:placement :shard-key` shape gate
16610        // tests: a three-member Aplicacao on the `Sharded` strategy
16611        // with the supplied `:shard-key` slot. Co-locates the
16612        // arm-construction so every test below carries one line of
16613        // setup (the offending `:shard-key` value) and the assertion.
16614        let mut s = three_member_spec();
16615        s.placement.estrategia = PlacementStrategy::Sharded;
16616        s.placement.shard_key = Some(key.into());
16617        s
16618    }
16619
16620    #[test]
16621    fn rejects_shard_key_with_embedded_space() {
16622        // The canonical paste-from-aligned-doc footgun:
16623        // `:shard-key "$tenant Id"` — the Akka-style entity-id
16624        // extractor reads the slot as a single-token reference, and an
16625        // embedded space breaks the token boundary at the runtime
16626        // hash-extractor pass with no diagnostic naming the offending
16627        // entry.
16628        let s = sharded_spec_with_key("$tenant Id");
16629        let err = s.validate().unwrap_err();
16630        assert!(
16631            matches!(
16632                err,
16633                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16634                    if shard_key == "$tenant Id" && reason.contains("space")
16635            ),
16636            "got {err:?}"
16637        );
16638    }
16639
16640    #[test]
16641    fn rejects_shard_key_with_leading_space() {
16642        // Leading-space arm of the embedded-whitespace footgun — the
16643        // paste-from-aligned-doc / paste-from-CSV-cell variant where
16644        // the leading column-padding leaked into the slot.
16645        let s = sharded_spec_with_key(" $tenantId");
16646        let err = s.validate().unwrap_err();
16647        assert!(
16648            matches!(
16649                err,
16650                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
16651                    if shard_key == " $tenantId"
16652            ),
16653            "got {err:?}"
16654        );
16655    }
16656
16657    #[test]
16658    fn rejects_shard_key_with_trailing_newline() {
16659        // The canonical paste-from-shell-heredoc footgun — every
16660        // `<<EOF` heredoc terminator paste leaves a trailing newline
16661        // the YAML emitter then folds away inconsistently across
16662        // emitter implementations.
16663        let s = sharded_spec_with_key("$tenantId\n");
16664        let err = s.validate().unwrap_err();
16665        assert!(
16666            matches!(
16667                err,
16668                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16669                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
16670            ),
16671            "got {err:?}"
16672        );
16673    }
16674
16675    #[test]
16676    fn rejects_shard_key_with_embedded_tab() {
16677        // The paste-from-aligned-doc tab-stop variant — tabs land
16678        // alongside spaces in copy-paste from formatted columns.
16679        let s = sharded_spec_with_key("$tenant\tId");
16680        let err = s.validate().unwrap_err();
16681        assert!(
16682            matches!(
16683                err,
16684                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16685                    if shard_key == "$tenant\tId" && reason.contains("tab")
16686            ),
16687            "got {err:?}"
16688        );
16689    }
16690
16691    #[test]
16692    fn rejects_shard_key_with_control_character() {
16693        // The paste-from-binary / paste-from-screen-cleared-terminal
16694        // footgun — an embedded `\x01` (SOH) byte that some YAML
16695        // emitters silently strip and others escape as ``,
16696        // breaking round-trip across emitter implementations.
16697        let s = sharded_spec_with_key("$tenant\u{0001}Id");
16698        let err = s.validate().unwrap_err();
16699        assert!(
16700            matches!(
16701                err,
16702                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16703                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
16704            ),
16705            "got {err:?}"
16706        );
16707    }
16708
16709    #[test]
16710    fn rejects_shard_key_with_non_ascii() {
16711        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
16712        // footgun — non-ASCII bytes normalize differently between the
16713        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
16714        // YAML parser, the same entity ID can silently map to two
16715        // distinct shards on a re-render.
16716        let s = sharded_spec_with_key("$tenàntId");
16717        let err = s.validate().unwrap_err();
16718        assert!(
16719            matches!(
16720                err,
16721                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16722                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
16723            ),
16724            "got {err:?}"
16725        );
16726    }
16727
16728    #[test]
16729    fn rejects_shard_key_too_long() {
16730        // Length cap pin: 64 bytes — one byte over the
16731        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
16732        // here is a paste-from-doc multi-line blob landing in
16733        // `:shard-key` instead of a single-token extractor expression.
16734        let too_long = "a".repeat(64);
16735        let s = sharded_spec_with_key(&too_long);
16736        let err = s.validate().unwrap_err();
16737        let AplicacaoError::ShardKeyInvalid {
16738            ref shard_key,
16739            ref reason,
16740        } = err
16741        else {
16742            panic!("expected ShardKeyInvalid, got {err:?}");
16743        };
16744        assert_eq!(shard_key, &too_long);
16745        assert!(
16746            reason.contains("63") && reason.contains("64"),
16747            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16748        );
16749    }
16750
16751    #[test]
16752    fn shard_key_max_length_validates() {
16753        // Boundary pin: 63 bytes exactly — the
16754        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
16755        // dropping to 62) surfaces here as a regression, mirroring
16756        // `placement_cluster_max_length_validates` /
16757        // `placement_affinity_max_length_validates` on the peer
16758        // identifier-shaped slots.
16759        let s = sharded_spec_with_key(&"a".repeat(63));
16760        s.validate().unwrap();
16761    }
16762
16763    #[test]
16764    fn accepts_canonical_shard_key_forms() {
16765        // The Akka-style entity-id extractor shapes a caixa author is
16766        // realistically going to write — pin every leg so a future
16767        // tightening that bans (e.g.) the `${...}` interpolation
16768        // variant or the `metadata.<field>` JSONPath form surfaces
16769        // here as a regression. The canonical forms span:
16770        //
16771        //   - bare property name (`tenantId`, `customerId`)
16772        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
16773        //   - JSONPath-style nested reference (`metadata.tenantId`,
16774        //     `$.user.id`)
16775        //   - interpolation-style template (`${tenant}`)
16776        //   - snake_case property name (`customer_id`)
16777        //   - kebab-case property name (`customer-id` — accepted
16778        //     because the slot is a printable-ASCII single-token
16779        //     reference, not a DNS-1123 label like
16780        //     `:placement :affinity` / `:clusters`)
16781        //   - single character (`a`, `$` — boundary)
16782        for form in [
16783            "tenantId",
16784            "customerId",
16785            "$tenantId",
16786            "metadata.tenantId",
16787            "$.user.id",
16788            "${tenant}",
16789            "customer_id",
16790            "customer-id",
16791            "a",
16792            "$",
16793        ] {
16794            let s = sharded_spec_with_key(form);
16795            s.validate().unwrap_or_else(|e| {
16796                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
16797            });
16798        }
16799    }
16800
16801    #[test]
16802    fn shard_key_empty_takes_precedence_over_invalid() {
16803        // Order pin: the existing `ShardedKeyEmpty` diagnostic
16804        // (reserved for the `Sharded` `Some("")` arm) fires before the
16805        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
16806        // `:shard-key` keeps its narrower error message — the new gate
16807        // would also reject `""` defensively, but the empty-string arm
16808        // is the more self-locating diagnostic. Mirrors the
16809        // `placement_cluster_empty_takes_precedence_over_invalid` pin
16810        // on the peer identifier-shaped slot.
16811        let s = sharded_spec_with_key("");
16812        let err = s.validate().unwrap_err();
16813        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
16814    }
16815
16816    #[test]
16817    fn shard_key_invalid_diagnostic_carries_offending_value() {
16818        // The diagnostic-shape pin: the error names the offending
16819        // `:shard-key` value verbatim so the author can grep their
16820        // caixa.lisp without re-running the build, and carries a
16821        // parser-shaped `reason:` naming the specific violation —
16822        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16823        // on the peer identifier-shaped slot.
16824        let s = sharded_spec_with_key("$tenant Id");
16825        let err = s.validate().unwrap_err();
16826        let AplicacaoError::ShardKeyInvalid {
16827            ref shard_key,
16828            ref reason,
16829        } = err
16830        else {
16831            panic!("expected ShardKeyInvalid, got {err:?}");
16832        };
16833        assert_eq!(shard_key, "$tenant Id");
16834        assert!(
16835            !reason.is_empty(),
16836            "reason must name the specific violation, got empty string"
16837        );
16838    }
16839
16840    #[test]
16841    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
16842        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
16843        // `:shard-key` carried on non-Sharded strategies) fires before
16844        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
16845        // a `Replicated` strategy surfaces the more self-locating
16846        // strategy-mismatch diagnostic (naming the actual fix — drop
16847        // the slot, or switch to Sharded) rather than the shape
16848        // diagnostic. The strategy-mismatch arm is the more actionable
16849        // diagnostic: a malformed shard-key on Replicated is "you
16850        // shouldn't have a :shard-key here at all", not "your
16851        // :shard-key value is malformed".
16852        let mut s = three_member_spec();
16853        // Replicated is the default fixture strategy.
16854        s.placement.shard_key = Some("$tenant Id".into());
16855        let err = s.validate().unwrap_err();
16856        assert!(
16857            matches!(
16858                err,
16859                AplicacaoError::ShardKeyOnNonSharded {
16860                    estrategia: PlacementStrategy::Replicated,
16861                    ..
16862                }
16863            ),
16864            "got {err:?}"
16865        );
16866    }
16867
16868    #[test]
16869    fn rejects_empty_affinity_hint() {
16870        let mut s = three_member_spec();
16871        s.placement.affinity = Some("".into());
16872        assert_eq!(
16873            s.validate().unwrap_err(),
16874            AplicacaoError::PlacementAffinityEmpty
16875        );
16876    }
16877
16878    #[test]
16879    fn placement_without_affinity_validates() {
16880        // Omitting :affinity is fine — the placement engine falls back
16881        // to the default heuristic. Pin the no-hint case so the
16882        // affinity-empty rejection doesn't accidentally fire on `None`.
16883        let mut s = three_member_spec();
16884        s.placement.affinity = None;
16885        s.validate().unwrap();
16886    }
16887
16888    #[test]
16889    fn rejects_placement_affinity_with_uppercase() {
16890        // The canonical "I copied the ADR's display name verbatim" typo
16891        // — placement hints land verbatim in K8s label-selector
16892        // territory, where the apiserver enforces the DNS-1123 label
16893        // rule (lowercase-only) on every identity-keyed admission axis.
16894        // Mirrors `rejects_placement_cluster_with_uppercase` on the
16895        // sibling slot.
16896        let mut s = three_member_spec();
16897        s.placement.affinity = Some("DataLocality".into());
16898        let err = s.validate().unwrap_err();
16899        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16900            panic!("expected PlacementAffinityInvalid, got other variant");
16901        };
16902        assert_eq!(affinity, "DataLocality");
16903        assert!(
16904            reason.contains("uppercase"),
16905            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
16906        );
16907        assert!(
16908            reason.contains("\"datalocality\""),
16909            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
16910        );
16911    }
16912
16913    #[test]
16914    fn rejects_placement_affinity_with_underscore() {
16915        // The canonical "I'm thinking of an env var / Python identifier"
16916        // leak — `_` is forbidden by every DNS-1123 label schema. Same
16917        // shape as `rejects_placement_cluster_with_underscore` on the
16918        // sibling slot.
16919        let mut s = three_member_spec();
16920        s.placement.affinity = Some("data_locality".into());
16921        let err = s.validate().unwrap_err();
16922        assert!(
16923            matches!(
16924                err,
16925                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16926                    if affinity == "data_locality" && reason.contains('_')
16927            ),
16928            "got {err:?}"
16929        );
16930    }
16931
16932    #[test]
16933    fn rejects_placement_affinity_with_dot() {
16934        // A `:placement :affinity` value is a single DNS-1123 *label*
16935        // (it lands as a K8s label value selector key), not a subdomain.
16936        // The "I want to namespace my hint with `.`" intent is expressed
16937        // via `-` (`data-locality-east`).
16938        let mut s = three_member_spec();
16939        s.placement.affinity = Some("data.locality".into());
16940        let err = s.validate().unwrap_err();
16941        assert!(
16942            matches!(
16943                err,
16944                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16945                    if affinity == "data.locality" && reason.contains('.')
16946            ),
16947            "got {err:?}"
16948        );
16949    }
16950
16951    #[test]
16952    fn rejects_placement_affinity_with_unicode() {
16953        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
16954        // before it reaches K8s. The byte-by-byte ASCII validity check
16955        // rejects multi-byte UTF-8 sequences by the first byte that
16956        // fails `[a-z0-9-]`.
16957        let mut s = three_member_spec();
16958        s.placement.affinity = Some("data-localité".into());
16959        let err = s.validate().unwrap_err();
16960        assert!(
16961            matches!(
16962                err,
16963                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16964                    if affinity == "data-localité"
16965            ),
16966            "got {err:?}"
16967        );
16968    }
16969
16970    #[test]
16971    fn rejects_placement_affinity_with_leading_hyphen() {
16972        // DNS-1123 boundary rule: labels must start with an
16973        // alphanumeric. Pin separately from the trailing-hyphen arm so
16974        // a future relaxation that only checks one boundary surfaces
16975        // here as a regression (parallel to
16976        // `rejects_placement_cluster_with_leading_hyphen`).
16977        let mut s = three_member_spec();
16978        s.placement.affinity = Some("-data-locality".into());
16979        let err = s.validate().unwrap_err();
16980        assert!(
16981            matches!(
16982                err,
16983                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16984                    if affinity == "-data-locality" && reason.contains("start and end")
16985            ),
16986            "got {err:?}"
16987        );
16988    }
16989
16990    #[test]
16991    fn rejects_placement_affinity_with_trailing_hyphen() {
16992        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
16993        // ends are covered against a future relaxation.
16994        let mut s = three_member_spec();
16995        s.placement.affinity = Some("data-locality-".into());
16996        let err = s.validate().unwrap_err();
16997        assert!(
16998            matches!(
16999                err,
17000                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
17001                    if affinity == "data-locality-"
17002            ),
17003            "got {err:?}"
17004        );
17005    }
17006
17007    #[test]
17008    fn rejects_placement_affinity_with_whitespace() {
17009        // Whitespace is the canonical "I pasted from a sketch / doc"
17010        // footgun. The apiserver rejects every label-selector value
17011        // carrying whitespace.
17012        let mut s = three_member_spec();
17013        s.placement.affinity = Some("data locality".into());
17014        let err = s.validate().unwrap_err();
17015        assert!(
17016            matches!(
17017                err,
17018                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
17019                    if affinity == "data locality"
17020            ),
17021            "got {err:?}"
17022        );
17023    }
17024
17025    #[test]
17026    fn rejects_placement_affinity_too_long() {
17027        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
17028        // pin. The diagnostic names both the cap (63) and the actual
17029        // length so the author can shorten in one edit. Mirrors
17030        // `rejects_placement_cluster_too_long`.
17031        let mut s = three_member_spec();
17032        let too_long = "a".repeat(64);
17033        s.placement.affinity = Some(too_long.clone());
17034        let err = s.validate().unwrap_err();
17035        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
17036            panic!("expected PlacementAffinityInvalid");
17037        };
17038        assert_eq!(affinity, too_long);
17039        assert!(
17040            reason.contains("63") && reason.contains("64"),
17041            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
17042        );
17043    }
17044
17045    #[test]
17046    fn placement_affinity_max_length_validates() {
17047        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
17048        // future tightening (e.g. dropping to 62) surfaces here as a
17049        // regression, mirroring `placement_cluster_max_length_validates`.
17050        let mut s = three_member_spec();
17051        s.placement.affinity = Some("a".repeat(63));
17052        s.validate().unwrap();
17053    }
17054
17055    #[test]
17056    fn accepts_canonical_placement_affinity_forms() {
17057        // The DNS-1123 label shapes a caixa author is realistically
17058        // going to write for placement hints: the M3 canonical examples
17059        // (`data-locality`, `low-latency`, `anti-affinity`), the
17060        // single-token form (`affinity`), the single-character boundary
17061        // (`a`), the digit-start (DNS-1123 allows this, unlike
17062        // DNS-1035), and a regional-suffixed form. Pin every leg so a
17063        // future tightening that bans (e.g.) digit-start identifiers
17064        // surfaces here.
17065        for form in [
17066            "data-locality",
17067            "low-latency",
17068            "anti-affinity",
17069            "affinity",
17070            "a",
17071            "3-tier",
17072            "locality-east",
17073        ] {
17074            let mut s = three_member_spec();
17075            s.placement.affinity = Some(form.into());
17076            s.validate().unwrap_or_else(|e| {
17077                panic!("canonical affinity form {form:?} must validate, got {e:?}")
17078            });
17079        }
17080    }
17081
17082    #[test]
17083    fn placement_affinity_empty_takes_precedence_over_invalid() {
17084        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
17085        // (which doesn't try to parse) fires before the new
17086        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
17087        // `:affinity` keeps its narrower error message — the new gate
17088        // would also reject `""`, but the empty-string arm is the more
17089        // self-locating diagnostic. Mirrors the
17090        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
17091        let mut s = three_member_spec();
17092        s.placement.affinity = Some(String::new());
17093        let err = s.validate().unwrap_err();
17094        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
17095    }
17096
17097    #[test]
17098    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
17099        // The diagnostic shape pin: every rejection carries the offending
17100        // `affinity:` verbatim plus a parser-shaped `reason:` so the
17101        // author can grep their caixa.lisp for `:affinity "<hint>"` and
17102        // fix it in one edit. Mirrors the
17103        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
17104        // pin on the sibling slot.
17105        let mut s = three_member_spec();
17106        s.placement.affinity = Some("Data_Locality".into());
17107        let err = s.validate().unwrap_err();
17108        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
17109            panic!("expected PlacementAffinityInvalid");
17110        };
17111        assert_eq!(affinity, "Data_Locality");
17112        assert!(
17113            !reason.is_empty(),
17114            "diagnostic reason must not be empty (got: {reason:?})"
17115        );
17116    }
17117
17118    #[test]
17119    fn singlenode_with_takeover_candidates_validates() {
17120        // OTP distributed-application convention (MESH-COMPOSITION
17121        // §II.1): SingleNode runs on one cluster at a time but the
17122        // :clusters list enumerates the takeover candidates. Multiple
17123        // entries are not a contradiction — they are the failover pool.
17124        let mut s = three_member_spec();
17125        s.placement.estrategia = PlacementStrategy::SingleNode;
17126        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
17127        s.validate().unwrap();
17128    }
17129
17130    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
17131
17132    #[test]
17133    fn mesh_policy_default_is_empty() {
17134        // The Default impl carries None on every axis — the typed
17135        // analog of an unset `:politicas (())` slot. Renderers that
17136        // overlay the policy onto a cluster artifact key off this
17137        // predicate to skip the slot entirely; pinning so a future
17138        // axis added to MeshPolicy can't silently break the contract
17139        // (a new field whose Default is non-None would flip is_empty
17140        // to false on every existing caixa, surfacing here).
17141        assert!(MeshPolicy::default().is_empty());
17142    }
17143
17144    #[test]
17145    fn mesh_policy_with_only_timeout_is_not_empty() {
17146        let p = MeshPolicy {
17147            timeout: Some(Duration::from_secs(30)),
17148            ..Default::default()
17149        };
17150        assert!(!p.is_empty());
17151    }
17152
17153    #[test]
17154    fn mesh_policy_with_only_retries_is_not_empty() {
17155        let p = MeshPolicy {
17156            retries: Some(3),
17157            ..Default::default()
17158        };
17159        assert!(!p.is_empty());
17160    }
17161
17162    #[test]
17163    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
17164        let p = MeshPolicy {
17165            circuit_breaker: Some(CircuitBreaker {
17166                max_failures: 5,
17167                window: Duration::from_secs(60),
17168            }),
17169            ..Default::default()
17170        };
17171        assert!(!p.is_empty());
17172    }
17173
17174    #[test]
17175    fn mesh_policy_with_only_mtls_required_is_not_empty() {
17176        // Even `mtls_required: Some(false)` (an explicit opt-out) is
17177        // not empty — the author *named* the axis, the renderer needs
17178        // to honor that vs. fall back to the cluster default.
17179        let p = MeshPolicy {
17180            mtls_required: Some(false),
17181            ..Default::default()
17182        };
17183        assert!(!p.is_empty());
17184    }
17185
17186    #[test]
17187    fn mesh_policy_with_only_rate_limit_is_not_empty() {
17188        let p = MeshPolicy {
17189            rate_limit: Some(RateLimit {
17190                rate: 100,
17191                window: Duration::from_secs(1),
17192            }),
17193            ..Default::default()
17194        };
17195        assert!(!p.is_empty());
17196    }
17197
17198    #[test]
17199    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
17200        // The three-member happy-path fixture sets timeout + retries +
17201        // mtls_required — every populated axis must read non-empty.
17202        // Pin the round-trip so the M3.x per-:politicas emitter (the
17203        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
17204        // on is_empty() to decide whether to emit at all without
17205        // re-deriving the contract from inline field probes.
17206        assert!(!three_member_spec().politicas.is_empty());
17207    }
17208
17209    // ── shared duration codec: cross-slot integer-magnitude gate ──
17210    //
17211    // The integer-magnitude discipline applied to
17212    // `supervisor::duration_codec::parse` lifts onto every typed slot
17213    // that routes through the shared codec — `MeshPolicy::timeout`
17214    // (`:politicas :timeout`) and `CircuitBreaker::window`
17215    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
17216    // These cross-slot tests pin that the gate fires at the serde
17217    // layer for both typed slots, not just for the supervisor side.
17218
17219    #[test]
17220    fn policy_timeout_serde_rejects_fractional_seconds() {
17221        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
17222        // so the shared codec's integer-magnitude gate applies on
17223        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
17224        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
17225        // deserialize with the canonical-form diagnostic naming the
17226        // offending `"1.5"` and the remediation `"1500ms"`.
17227        let payload = r#"{"timeout":"1.5s"}"#;
17228        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17229        let msg = err.to_string();
17230        assert!(
17231            msg.contains("not a non-negative integer"),
17232            "expected integer-magnitude diagnostic in {msg:?}"
17233        );
17234        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
17235        assert!(
17236            msg.contains("\"1500ms\""),
17237            "missing canonical-form remediation in {msg:?}"
17238        );
17239    }
17240
17241    #[test]
17242    fn policy_timeout_serde_rejects_leading_plus_sign() {
17243        // Pin the leading-`+` arm cross-slot — the prior f64 parser
17244        // accepted `"+30s"` silently and round-tripped to `"30s"`.
17245        let payload = r#"{"timeout":"+30s"}"#;
17246        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17247        let msg = err.to_string();
17248        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
17249    }
17250
17251    #[test]
17252    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
17253        // `CircuitBreaker::window` uses `with =
17254        // "supervisor::duration_codec_required"` (the required-Duration
17255        // variant that delegates to the same shared parser). `"0.5m"`
17256        // parsed to 30s and round-tripped to `"30s"` on next emit —
17257        // DRIFT closed.
17258        let payload = format!(
17259            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
17260            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
17261            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
17262        );
17263        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
17264        let msg = err.to_string();
17265        assert!(
17266            msg.contains("not a non-negative integer"),
17267            "expected integer-magnitude diagnostic in {msg:?}"
17268        );
17269        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
17270        assert!(
17271            msg.contains("\"30s\""),
17272            "missing canonical-form remediation in {msg:?}"
17273        );
17274    }
17275
17276    #[test]
17277    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
17278        // Pin the happy-path on the cross-slot side: every canonical
17279        // author shape `render` ever emits parses cleanly through the
17280        // shared codec on the `CircuitBreaker` slot. The
17281        // codec's accepted set (post-gate) is exactly its emitted set
17282        // for the integer-magnitude class.
17283        for window_lit in ["30s", "500ms", "2m", "1h"] {
17284            let payload = format!(
17285                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
17286                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
17287                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
17288            );
17289            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
17290                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
17291            });
17292            assert_eq!(cb.max_failures, 5);
17293        }
17294    }
17295
17296    // ── rate_limit_codec: integer-magnitude gate ──
17297    //
17298    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
17299    // / 737a676 / d53c922 trajectory landed on every typed-duration /
17300    // typed-byte-size codec in caixa-core lifts onto the fifth typed
17301    // codec — `rate_limit_codec` — through the digit-only magnitude
17302    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
17303    // These tests pin the gate at the serde layer for `:politicas
17304    // :rate-limit` (the only typed slot the codec backs), and at the
17305    // codec-internal `parse` layer for the canonical positive cases.
17306
17307    #[test]
17308    fn rate_limit_serde_rejects_fractional_rate() {
17309        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
17310        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
17311        // wording, which didn't name the canonical-form remediation or
17312        // the round-trip drift the next emit would produce. Now refused
17313        // at deserialize with the canonical-form diagnostic naming the
17314        // offending `"1.5"` magnitude and the round-trip drift wording.
17315        let payload = r#"{"rateLimit":"1.5/s"}"#;
17316        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17317        let msg = err.to_string();
17318        assert!(
17319            msg.contains("not a non-negative integer"),
17320            "expected integer-magnitude diagnostic in {msg:?}"
17321        );
17322        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
17323        assert!(
17324            msg.contains("THEORY.md"),
17325            "missing render-determinism contract citation in {msg:?}"
17326        );
17327    }
17328
17329    #[test]
17330    fn rate_limit_serde_rejects_leading_plus_sign() {
17331        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
17332        // permissive-`+` parse), so `"+100/s"` silently parsed to
17333        // `RateLimit { 100, 1s }` and round-tripped through `render` to
17334        // `"100/s"` — a *different* canonical string on the next emit,
17335        // breaking the THEORY.md Part V render-determinism contract
17336        // exactly the way the peer duration codecs' `"+30s"` case did.
17337        // This is the load-bearing class the digit-only gate closes
17338        // beyond what `u32::from_str`'s strictness covers on its own.
17339        let payload = r#"{"rateLimit":"+100/s"}"#;
17340        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17341        let msg = err.to_string();
17342        assert!(
17343            msg.contains("not a non-negative integer"),
17344            "expected integer-magnitude diagnostic in {msg:?}"
17345        );
17346        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
17347    }
17348
17349    #[test]
17350    fn rate_limit_serde_rejects_leading_minus_sign() {
17351        // The signed-negative arm: `"-1/s"` lands on the
17352        // non-canonical-but-numeric branch via the `i64` fallback (the
17353        // `f64` parse also succeeds), surfacing the canonical-form
17354        // diagnostic. Replaces the prior value-laundered "not a u32"
17355        // wording with the unified diagnostic across signs.
17356        let payload = r#"{"rateLimit":"-1/s"}"#;
17357        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17358        let msg = err.to_string();
17359        assert!(
17360            msg.contains("not a non-negative integer"),
17361            "expected integer-magnitude diagnostic in {msg:?}"
17362        );
17363        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
17364    }
17365
17366    #[test]
17367    fn rate_limit_serde_rejects_decimal_shaped_integer() {
17368        // `"100.0/s"` is integer-valued numerically but not in the
17369        // codec's accepted set — `render` emits `"100/s"`, so the
17370        // round-trip would drift. Lifted to the canonical-form
17371        // diagnostic peer with the duration codec's `"1.0s"` case
17372        // (1c55a2a).
17373        let payload = r#"{"rateLimit":"100.0/s"}"#;
17374        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17375        let msg = err.to_string();
17376        assert!(
17377            msg.contains("not a non-negative integer"),
17378            "expected integer-magnitude diagnostic in {msg:?}"
17379        );
17380        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
17381    }
17382
17383    #[test]
17384    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
17385        // Non-numeric, non-digit-only input lands on the existing
17386        // narrower `"not a u32"` arm (preserved for diagnostic-shape
17387        // stability on the parser-shape footgun case). Pin this so a
17388        // future relaxation of the numeric-fallback predicate doesn't
17389        // silently collapse garbage onto the canonical-form arm — same
17390        // partition the peer duration codecs draw between
17391        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
17392        let payload = r#"{"rateLimit":"abc/s"}"#;
17393        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17394        let msg = err.to_string();
17395        assert!(
17396            msg.contains("not a u32"),
17397            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
17398        );
17399        assert!(
17400            !msg.contains("not a non-negative integer"),
17401            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
17402        );
17403    }
17404
17405    #[test]
17406    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
17407        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
17408        // u32's range. The digit-only gate passes; `u32::from_str`
17409        // fails on overflow. Surface that with the overflow-shaped
17410        // diagnostic naming the offending magnitude verbatim, peer
17411        // with `supervisor::duration_codec`'s overflow arm. Pinning
17412        // the wording so a future refactor doesn't silently collapse
17413        // overflow onto the canonical-form arm.
17414        let payload = r#"{"rateLimit":"4294967296/s"}"#;
17415        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17416        let msg = err.to_string();
17417        assert!(
17418            msg.contains("overflows u32"),
17419            "expected overflow diagnostic in {msg:?}"
17420        );
17421        assert!(
17422            msg.contains("\"4294967296\""),
17423            "missing offending magnitude in {msg:?}"
17424        );
17425    }
17426
17427    #[test]
17428    fn rate_limit_serde_rejects_leading_zero_magnitude() {
17429        // `"0100/s"` is digit-only, so the existing
17430        // non-digit-only / sign / fractional arm doesn't catch it —
17431        // `u32::from_str("0100")` returns `Ok(100)`, so before this
17432        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
17433        // round-tripped through `render` to `"100/s"` — a *different*
17434        // canonical string on the next emit, breaking the THEORY.md
17435        // Part V render-determinism contract exactly the way the
17436        // peer `"+100/s"` case did before the leading-`+` arm landed.
17437        // This is the load-bearing class the leading-zero gate closes
17438        // beyond what the existing digit-only / sign / fractional
17439        // gates cover, and the peer arm to the leading-`+` test
17440        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
17441        // canonical-form-drift axis.
17442        let payload = r#"{"rateLimit":"0100/s"}"#;
17443        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17444        let msg = err.to_string();
17445        assert!(
17446            msg.contains("non-canonical leading zero"),
17447            "expected leading-zero diagnostic in {msg:?}"
17448        );
17449        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
17450        assert!(
17451            msg.contains("THEORY.md"),
17452            "missing render-determinism contract citation in {msg:?}"
17453        );
17454    }
17455
17456    #[test]
17457    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
17458        // `"00/s"` is the degenerate leading-zero case — every byte
17459        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
17460        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
17461        // a *different* canonical string, same render-determinism
17462        // violation. The single-byte `"0/s"` itself is in the
17463        // accepted set (round-trips losslessly through `render`,
17464        // refused downstream by `PolicyRateLimitZero`); the
17465        // multi-byte `"00/s"` is not. Pins the boundary between the
17466        // accepted single-`0` and the rejected leading-zero class.
17467        let payload = r#"{"rateLimit":"00/s"}"#;
17468        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17469        let msg = err.to_string();
17470        assert!(
17471            msg.contains("non-canonical leading zero"),
17472            "expected leading-zero diagnostic in {msg:?}"
17473        );
17474        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
17475    }
17476
17477    #[test]
17478    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
17479        // Cross-window pin — the gate is window-agnostic; the
17480        // leading-zero class is a property of the magnitude, not the
17481        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
17482        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
17483        // single-window coverage extended across the three canonical
17484        // windows the codec accepts.
17485        let payload = r#"{"rateLimit":"007/h"}"#;
17486        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17487        let msg = err.to_string();
17488        assert!(
17489            msg.contains("non-canonical leading zero"),
17490            "expected leading-zero diagnostic in {msg:?}"
17491        );
17492        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
17493    }
17494
17495    #[test]
17496    fn rate_limit_serde_rejects_leading_whitespace() {
17497        // `" 100/s"` — the canonical paste-from-aligned-doc /
17498        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
17499        // the top-level `s.trim()` silently ate the leading space and
17500        // parsed the value to `RateLimit { 100, 1s }`, which then
17501        // round-tripped through `render` to `"100/s"` (a *different*
17502        // canonical string on the next emit) — the exact
17503        // canonical-form-drift class the leading-`+` / leading-zero
17504        // arms already close, extended to the whitespace byte class.
17505        let payload = r#"{"rateLimit":" 100/s"}"#;
17506        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17507        let msg = err.to_string();
17508        assert!(
17509            msg.contains("contains whitespace byte"),
17510            "expected whitespace diagnostic in {msg:?}"
17511        );
17512        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17513        assert!(
17514            msg.contains("THEORY.md"),
17515            "missing render-determinism contract citation in {msg:?}"
17516        );
17517    }
17518
17519    #[test]
17520    fn rate_limit_serde_rejects_trailing_whitespace() {
17521        // `"100/s "` — the canonical shell-history / trailing-space
17522        // paste footgun. Before this gate the top-level `s.trim()`
17523        // silently ate the trailing space and parsed to
17524        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
17525        // next emit — same canonical-form drift as the leading-space
17526        // sibling, closed on the same whitespace-byte arm.
17527        let payload = r#"{"rateLimit":"100/s "}"#;
17528        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17529        let msg = err.to_string();
17530        assert!(
17531            msg.contains("contains whitespace byte"),
17532            "expected whitespace diagnostic in {msg:?}"
17533        );
17534        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17535    }
17536
17537    #[test]
17538    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
17539        // `"100 / s"` — the canonical typographically-spaced author
17540        // shape (the same idiom every prose reference to a rate limit
17541        // renders as, mistakenly retained when the value is pasted
17542        // into a codec-shaped slot). Before this gate the per-part
17543        // `rate_str.trim()` / `unit.trim()` calls silently ate both
17544        // spaces on either side of `/` and parsed to
17545        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
17546        // codec's *internal* whitespace-tolerance vector, orthogonal
17547        // to the leading / trailing surface but the same canonical-
17548        // form-drift class. Pins the arm as strictly stronger than the
17549        // pre-existing top-level `s.trim()` behavior: it fires on
17550        // whitespace anywhere in the value, not just at the string
17551        // boundary.
17552        let payload = r#"{"rateLimit":"100 / s"}"#;
17553        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17554        let msg = err.to_string();
17555        assert!(
17556            msg.contains("contains whitespace byte"),
17557            "expected whitespace diagnostic in {msg:?}"
17558        );
17559        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17560    }
17561
17562    #[test]
17563    fn rate_limit_serde_rejects_tab_byte() {
17564        // `"\t100/s"` — the canonical paste-from-indented-doc /
17565        // paste-from-YAML-block-scalar footgun where a tab byte leads
17566        // the magnitude. Pins that the gate covers tab (`0x09`) as
17567        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
17568        // members and both would be silently swallowed by `s.trim()`
17569        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
17570        // space alone to the full ASCII-whitespace set (space `0x20`,
17571        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
17572        // the tab arm as a representative of the non-space members.
17573        let payload = r#"{"rateLimit":"\t100/s"}"#;
17574        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17575        let msg = err.to_string();
17576        assert!(
17577            msg.contains("contains whitespace byte"),
17578            "expected whitespace diagnostic in {msg:?}"
17579        );
17580        assert!(
17581            msg.contains("0x09"),
17582            "missing offending tab byte in {msg:?}"
17583        );
17584    }
17585
17586    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
17587    //
17588    // Successor to the ASCII-whitespace arm (1ad7755) on
17589    // `rate_limit_codec` — closes the strictly-complementary class the
17590    // byte-scan cannot see, through the lifted
17591    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
17592
17593    #[test]
17594    fn rate_limit_serde_rejects_leading_nbsp() {
17595        // NBSP prefix — paste-from-typography footgun. Byte-scan
17596        // misses, `str::trim` silently strips it, value drifts to
17597        // `"100/s"` on next serialize.
17598        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
17599        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17600        let msg = err.to_string();
17601        assert!(
17602            msg.contains("non-ASCII Unicode whitespace character"),
17603            "expected non-ASCII whitespace diagnostic in {msg:?}"
17604        );
17605        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
17606    }
17607
17608    #[test]
17609    fn rate_limit_serde_rejects_internal_em_space() {
17610        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
17611        // paste-from-typography footgun on the `<integer>/<unit>`
17612        // shape.
17613        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
17614        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17615        let msg = err.to_string();
17616        assert!(
17617            msg.contains("non-ASCII Unicode whitespace character"),
17618            "expected non-ASCII whitespace diagnostic in {msg:?}"
17619        );
17620        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
17621    }
17622
17623    #[test]
17624    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
17625        // Positive-control pin: every ASCII-only canonical form the
17626        // renderer emits stays accepted through the new arm.
17627        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
17628            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
17629            let p: MeshPolicy = serde_json::from_str(&payload)
17630                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
17631            assert!(p.rate_limit.is_some());
17632        }
17633    }
17634
17635    #[test]
17636    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
17637        // The boundary case — `"0/s"` is the canonical form
17638        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
17639        // it at the parse layer; the downstream
17640        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
17641        // `rate == 0` at the typed-validate layer above. Pins the
17642        // partition: the leading-zero gate at the codec layer does
17643        // not poach the rate-zero semantic-validation arm at the
17644        // typed-validate layer above (a future stricter codec must
17645        // not reject `"0/s"` here, or it'd collapse the diagnostic
17646        // partitioning that lets `PolicyRateLimitZero` name the
17647        // offending typed slot).
17648        let payload = r#"{"rateLimit":"0/s"}"#;
17649        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
17650            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
17651        });
17652        let rl = policy.rate_limit.expect("rate_limit must be Some");
17653        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
17654        assert_eq!(
17655            rl.window,
17656            Duration::from_secs(1),
17657            "single-`0` magnitude with `s` unit must parse to window=1s"
17658        );
17659    }
17660
17661    #[test]
17662    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
17663        // The complementary boundary pin — every magnitude
17664        // `render` emits starts with `[1-9]` (or is the single byte
17665        // `"0"`), so the canonical-form predicate is `(len == 1) ||
17666        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
17667        // '1'` case explicitly so a future tightening of the gate
17668        // (e.g. an over-eager "no leading digit < 5" rule, or a
17669        // mistakenly anchored start-of-magnitude byte check) lands
17670        // here before the canonical-forms-iterating test would catch
17671        // it.
17672        let payload = r#"{"rateLimit":"100/s"}"#;
17673        let policy: MeshPolicy = serde_json::from_str(payload)
17674            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
17675        let rl = policy.rate_limit.expect("rate_limit must be Some");
17676        assert_eq!(
17677            rl.rate, 100,
17678            "canonical-100 magnitude must parse to rate=100"
17679        );
17680    }
17681
17682    #[test]
17683    fn rate_limit_serde_accepts_integer_canonical_forms() {
17684        // Pin the happy-path: every canonical author shape `render`
17685        // ever emits parses cleanly through the codec post-gate. The
17686        // codec's accepted set (post-gate) is exactly its emitted set
17687        // for the integer-magnitude class — same property
17688        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
17689        // gates guarantee on the peer codecs. Iterating across rate
17690        // magnitudes (including `"0"`, which the codec accepts even
17691        // though `validate_politicas` rejects `rate == 0` at the typed
17692        // layer above) closes the codec contract at the parse layer
17693        // independently of the validate layer.
17694        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
17695            for unit_lit in ["s", "m", "h"] {
17696                let lit = format!("{rate_lit}/{unit_lit}");
17697                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
17698                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
17699                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
17700                });
17701                let rl = policy.rate_limit.expect("rate_limit must be Some");
17702                assert_eq!(
17703                    rl.rate,
17704                    rate_lit.parse::<u32>().unwrap(),
17705                    "rate mismatch for {lit:?}"
17706                );
17707            }
17708        }
17709    }
17710
17711    #[test]
17712    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
17713        // The structural property the gate enforces: serialize ∘
17714        // deserialize is the identity on every canonical author shape.
17715        // Peer of `parse_byte_size`'s and `parse_duration`'s
17716        // `_round_trips_through_render_for_every_canonical_form` tests
17717        // on the rate-limit axis. Before the gate, `"+100/s"` violated
17718        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
17719        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
17720        for rate in [1u32, 100, 5000, 1_000_000] {
17721            for (window, unit) in [
17722                (Duration::from_secs(1), "s"),
17723                (Duration::from_secs(60), "m"),
17724                (Duration::from_secs(3600), "h"),
17725            ] {
17726                let policy = MeshPolicy {
17727                    rate_limit: Some(RateLimit { rate, window }),
17728                    ..Default::default()
17729                };
17730                let json = serde_json::to_string(&policy).unwrap();
17731                let expected = format!("\"{rate}/{unit}\"");
17732                assert!(
17733                    json.contains(&expected),
17734                    "expected {expected:?} in {json:?}"
17735                );
17736                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17737                assert_eq!(
17738                    back.rate_limit, policy.rate_limit,
17739                    "round-trip for {json:?}"
17740                );
17741            }
17742        }
17743    }
17744
17745    // ── self-membership cross-slot gate ──────────────────────────────
17746
17747    #[test]
17748    fn validate_no_self_membership_rejects_self_named_membro() {
17749        // An Aplicacao whose `:membros` lists its own `:nome` is a
17750        // one-node lacre-closure recursion — rejected, naming the parent.
17751        let membros = vec![
17752            membro("catalog", "^0.1"),
17753            membro("checkout", "^0.1"),
17754            membro("cart", "^0.1"),
17755        ];
17756        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
17757        assert!(
17758            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
17759            "got {err:?}"
17760        );
17761    }
17762
17763    #[test]
17764    fn validate_no_self_membership_accepts_distinct_membros() {
17765        // Positive control: distinct member names (including a member
17766        // that is itself an Aplicacao — recursive composition is valid,
17767        // MESH-COMPOSITION §V) pass the gate.
17768        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
17769        validate_no_self_membership(&membros, "checkout").unwrap();
17770    }
17771
17772    #[test]
17773    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
17774        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
17775        // `NoMembros` arm (the more-fundamental "graph must have nodes"
17776        // gate), not by this cross-slot self-edge gate. Keeping the
17777        // self-membership predicate vacuously-ok on the empty input
17778        // matches its supervisor-axis peer
17779        // (`validate_no_self_supervision_empty_children_is_ok`) and
17780        // makes the gate composable from any future call site (an M4
17781        // CR materializer's per-membros validator) without re-checking
17782        // emptiness.
17783        validate_no_self_membership(&[], "checkout").unwrap();
17784    }
17785
17786    #[test]
17787    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
17788        // Pinning the Display: the self-membership diagnostic must name
17789        // the offending caixa verbatim + the "lists itself" framing the
17790        // author can grep for, so the cluster-far failure surfaces at
17791        // build time with one-line remediation. Same diagnostic shape
17792        // as the supervisor-axis `ChildSupervisesSelf` peer.
17793        let membros = vec![membro("orquestra", "^0.1")];
17794        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
17795        let msg = err.to_string();
17796        assert!(
17797            msg.contains("orquestra"),
17798            "diagnostic must name the offending caixa nome (got: {msg:?})"
17799        );
17800        assert!(
17801            msg.contains("lists itself"),
17802            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
17803        );
17804    }
17805
17806    #[test]
17807    fn default_servico_port_constant_pins_canonical_8080_literal() {
17808        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
17809        // at the verbatim `8080` literal both consumers (the
17810        // `Entrada::port` serde default via [`default_port`] and the
17811        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
17812        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
17813        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
17814        // discipline (a085b26) on the per-renderer canonical-K8s-axis
17815        // string-constant axis: a future refactor that drifts the
17816        // constant out from under either consumer surfaces here ahead
17817        // of every per-renderer's first emission. The literal value
17818        // matches the well-known HTTP-alt port the `pleme-computeunit`
17819        // library chart already emits as its `trigger.service.port`
17820        // default — by construction the same value the substrate
17821        // assumes about every Servico's in-cluster L4 listener.
17822        assert_eq!(
17823            DEFAULT_SERVICO_PORT, 8080,
17824            "canonical Servico port literal must remain `8080` verbatim — \
17825             this is the value both the `Entrada::port` serde default and the \
17826             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
17827        );
17828    }
17829
17830    #[test]
17831    fn default_port_helper_returns_canonical_servico_port_constant() {
17832        // The bridge-arm — pins that the [`default_port`] helper
17833        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
17834        // attribute hooks routes through the lifted
17835        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
17836        // literal. A future refactor that re-introduces the `8080`
17837        // literal at the helper's return site (silently re-opening
17838        // the drift footgun this lift closed) surfaces here ahead of
17839        // every author-side `(:entrada (:host … :para …))` slot
17840        // without an explicit `:port`. Peer with the
17841        // `default_namespace_re_export_points_at_caixa_core_canonical`
17842        // pin on the caixa-mesh-side re-export axis.
17843        assert_eq!(
17844            default_port(),
17845            DEFAULT_SERVICO_PORT,
17846            "the serde-default helper must route through the lifted constant"
17847        );
17848    }
17849
17850    #[test]
17851    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
17852        // The end-to-end pin — an author-surface `(:entrada (:host …
17853        // :para …))` without an explicit `:port` slot deserializes to
17854        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
17855        // verbatim. Routes the canonical lifted constant through both
17856        // the serde-default machinery (the `#[serde(default =
17857        // "default_port")]` attribute) and the typed-value-shape
17858        // contract (the resulting [`Entrada::port`] value). A future
17859        // refactor that drifts either axis — replacing the serde
17860        // hook's helper, changing the typed slot's wire shape — would
17861        // surface here before any per-renderer's CNP / Gateway /
17862        // HTTPRoute emission consumed the drifted default.
17863        let entrada: Entrada =
17864            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
17865        assert_eq!(
17866            entrada.port, DEFAULT_SERVICO_PORT,
17867            "the serde default must materialize as the lifted canonical Servico port"
17868        );
17869    }
17870
17871    #[test]
17872    fn servico_port_min_pins_canonical_accept_set_floor() {
17873        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
17874        // verbatim `1` literal every typed `:entrada :port` acceptance
17875        // gate keys off. Peer with the
17876        // [`default_servico_port_constant_pins_canonical_8080_literal`]
17877        // discipline on the canonical-Servico-port-constant axis: a
17878        // future refactor that drifts the accept-set floor out from
17879        // under the sole consumer at [`AplicacaoSpec::validate`]'s
17880        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
17881        // every per-`:entrada` `EntradaPortZero` diagnostic. The
17882        // literal value matches the IANA-registered TCP/UDP port
17883        // space floor (`1..=65535` — port `0` is the "any ephemeral"
17884        // sentinel, not a well-defined destination the substrate's
17885        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
17886        // axis can honor).
17887        assert_eq!(
17888            SERVICO_PORT_MIN, 1,
17889            "canonical Servico port accept-set floor must remain `1` verbatim — \
17890             this is the value the `AplicacaoSpec::validate` gate at \
17891             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
17892        );
17893    }
17894
17895    #[test]
17896    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
17897        // The cross-const invariant pin — the substrate's canonical
17898        // default port must satisfy its own accept-set floor by
17899        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
17900        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
17901        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
17902        // override the operator pins through a future
17903        // `:placement :default-port` slot that lands out-of-range, a
17904        // per-edition Servico-port migration that lifted the floor
17905        // above the previous default without coordinating the pair —
17906        // would silently invalidate the serde-default emission at
17907        // every author-side `(:entrada (:host … :para …))` slot
17908        // without an explicit `:port`: the default port would fall
17909        // below the accept-set floor, the `AplicacaoSpec::validate`
17910        // gate would reject every default-carrying Aplicacao as
17911        // `EntradaPortZero`, and the substrate's typed
17912        // `(defcaixa … :kind Aplicacao)` surface would fail validate
17913        // on every Aplicacao whose author omitted `:entrada :port`
17914        // for the substrate's chosen default — a class of authoring-
17915        // surface footguns the compile-time pin structurally closes.
17916        // Peer with the
17917        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
17918        // (27f9b34) cross-const invariant pin discipline on the peer
17919        // canonical-Helm-per-values-block child-chart-enablement-toggle
17920        // axis pair.
17921        assert!(
17922            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
17923            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
17924             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
17925             every default-carrying `(:entrada (:host … :para …))` slot without an \
17926             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
17927             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
17928        );
17929    }
17930
17931    #[test]
17932    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
17933        // The gate-site pin — asserts the `AplicacaoSpec::validate`
17934        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
17935        // `EntradaPortZero` diagnostic on the below-floor input
17936        // `port: 0` (the only below-floor value the `u16` field can
17937        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
17938        // is the singleton `{0}`). A future refactor that drifts the
17939        // gate off the lifted const (silently re-introducing an
17940        // inline `if e.port == 0` byte-check) surfaces here — the
17941        // pin cannot distinguish `< 1` from `== 0` on the current
17942        // floor, but it *does* pin that the diagnostic fires on `0`
17943        // through whichever gate is wired, so any future accept-set
17944        // floor migration (a hypothetical unprivileged-only
17945        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
17946        // update this test alongside the const declaration —
17947        // structurally guaranteeing the gate + accept-set + pin
17948        // trio move together. Peer with the
17949        // [`rejects_zero_entrada_port`] behavioral pin on the same
17950        // per-`:entrada :port` axis — that pin asserts the pre-lift
17951        // behavioral contract (`port: 0` → `EntradaPortZero`); this
17952        // pin adds the structural link to the lifted floor const.
17953        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
17954        let mut s = three_member_spec();
17955        s.entrada.as_mut().unwrap().port = 0;
17956        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
17957    }
17958
17959    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
17960
17961    #[test]
17962    fn membro_serde_keys_match_lifted_membro_key_consts() {
17963        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
17964        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
17965        // name the exact camelCase JSON keys the
17966        // `#[serde(rename_all = "camelCase")]` attribute on
17967        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
17968        // that each canonical byte-sequence appears verbatim in the
17969        // JSON — a future accidental `rename_all = "snake_case"` /
17970        // `"kebab-case"` / verbatim-field-name flip at the derive
17971        // attribute (any of which would silently break every downstream
17972        // JSON consumer that reaches for one of the two consts via
17973        // `Value::get(...)`) surfaces here as a build-time test failure
17974        // at `aplicacao.rs`, not as an apply-time
17975        // `.get(<stale-canonical-const>)` returning `None` far from the
17976        // derive-attr drift's commit. Peer with the sibling
17977        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
17978        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
17979        // same discipline the SupervisorSpec top-level lift established,
17980        // extended here to the M3 [`Membro`] per-`:membros` axis.
17981        let m = Membro {
17982            caixa: "catalog".into(),
17983            versao: "^0.1".into(),
17984        };
17985        let json = serde_json::to_string(&m).unwrap();
17986        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
17987            let quoted = format!("\"{key}\"");
17988            assert!(
17989                json.contains(&quoted),
17990                "serialized Membro must carry the lifted MEMBRO_KEY_* \
17991                 byte-sequence {quoted} verbatim in the JSON emission \
17992                 (got: {json})",
17993            );
17994        }
17995    }
17996
17997    #[test]
17998    fn membro_key_consts_are_pairwise_distinct() {
17999        // Cross-axis drift-detection pin: a future collapse of the two
18000        // canonical [`Membro`] per-entry byte-strings onto the same
18001        // value (e.g. an accidental copy-paste flip of
18002        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
18003        // silently reroute every downstream probe on one axis onto the
18004        // sibling axis's overlay entry and pass every propagation-probe
18005        // test that expected only the stale axis's value. Peer of the
18006        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
18007        // (40cc4e5).
18008        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
18009        for (i, a) in all.iter().enumerate() {
18010            for b in all.iter().skip(i + 1) {
18011                assert_ne!(
18012                    a, b,
18013                    "MEMBRO_KEY_* consts must be pairwise-distinct \
18014                     canonical byte-sequences — got `{a}` == `{b}`",
18015                );
18016            }
18017        }
18018    }
18019
18020    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
18021    //    URL-path fallback resolver every HTTPRoute-aware renderer
18022    //    reaching for a per-rule path-list resolution routes through.
18023    //    The four pin tests below fix the four-way accept-set the
18024    //    resolver must always honor: (:paths-non-empty-verbatim,
18025    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
18026    //    :paths-preserves-order-across-multiple-entries) — drift on any
18027    //    arm surfaces at caixa-core build time rather than at cluster-
18028    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
18029    //    sibling `:politicas` typed-primitive dispatch axis.
18030
18031    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
18032        Entrada {
18033            host: "example.com".into(),
18034            para: "cart".into(),
18035            paths: paths.into_iter().map(String::from).collect(),
18036            port: DEFAULT_SERVICO_PORT,
18037        }
18038    }
18039
18040    #[test]
18041    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
18042        // The typed `:entrada :paths` slot carries an author-declared
18043        // list — the resolver returns each entry verbatim, no
18044        // catch-all substitution. The canonical "author declared
18045        // paths, honor them verbatim" arm of the path-list dispatch.
18046        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
18047        assert_eq!(
18048            e.resolved_paths(),
18049            vec!["/api/cart", "/api/products"],
18050            "resolved_paths must return each `:entrada :paths` entry \
18051             verbatim when the typed slot is non-empty (got {:?})",
18052            e.resolved_paths(),
18053        );
18054    }
18055
18056    #[test]
18057    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
18058        // Empty `:entrada :paths` slot — the resolver substitutes the
18059        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
18060        // catch-all fallback verbatim. Pins the empty-arm of the
18061        // resolver's four-way accept-set against a future silent
18062        // detour that returned an empty Vec (which would emit an
18063        // HTTPRoute with zero rules — silently dropping every
18064        // external `:entrada` flow at admission time), routed to a
18065        // different fallback shape, or dropped the catch-all
18066        // altogether.
18067        let e = entrada_with_paths(vec![]);
18068        assert_eq!(
18069            e.resolved_paths(),
18070            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
18071            "resolved_paths on empty `:entrada :paths` must fall back \
18072             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
18073             all — got {:?}",
18074            e.resolved_paths(),
18075        );
18076    }
18077
18078    #[test]
18079    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
18080        // Single-entry `:entrada :paths` — the resolver returns the
18081        // single declared path verbatim, NOT the catch-all fallback
18082        // (author declared a path, honor it — the empty-arm and the
18083        // len-1 arm are semantically distinct axes of the resolver's
18084        // accept-set). Pins that the resolver treats "author declared
18085        // one path" as authored input, not as the empty case.
18086        let e = entrada_with_paths(vec!["/api/only"]);
18087        assert_eq!(
18088            e.resolved_paths(),
18089            vec!["/api/only"],
18090            "resolved_paths on single-entry `:entrada :paths` must \
18091             return the declared path verbatim, NOT the catch-all \
18092             fallback (got {:?})",
18093            e.resolved_paths(),
18094        );
18095    }
18096
18097    #[test]
18098    fn resolved_paths_preserves_author_declared_order() {
18099        // The `:entrada :paths` list is author-ordered — the resolver
18100        // preserves the author's declaration order verbatim, since
18101        // per-rule dispatch order at the K8s Gateway API HTTPRoute
18102        // consumer is significant (first-match-wins under the
18103        // path-prefix matcher). Pins against a future silent
18104        // re-sort / dedup / normalize detour that reordered author
18105        // input.
18106        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
18107        assert_eq!(
18108            e.resolved_paths(),
18109            vec!["/z/last", "/a/first", "/m/mid"],
18110            "resolved_paths must preserve author-declared `:entrada \
18111             :paths` order verbatim — got {:?}",
18112            e.resolved_paths(),
18113        );
18114    }
18115
18116    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
18117    //    slot `&[String]` slice accessor every per-`:entrada` consumer
18118    //    that must see the author's declaration verbatim (not the
18119    //    fallback-applied projection the sibling `resolved_paths`
18120    //    returns) routes through. The three pin tests below fix the
18121    //    accept-set the accessor must honor: (:non-empty-byte-equal,
18122    //    :empty-projects-empty-slice, :preserves-author-declared-order)
18123    //    — drift on any arm surfaces at caixa-core build time rather
18124    //    than at cluster-apply time. Peer discipline with the sibling
18125    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
18126    //    peer M3 mesh-slot `Vec<String>`-carry axis.
18127
18128    #[test]
18129    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
18130        // Byte-equal pin: [`Entrada::paths`] must project the raw
18131        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
18132        // slice borrowed from the typed slot's own [`Vec<String>`]
18133        // storage — no re-ordering, no dedup, no per-entry normalization,
18134        // no fallback substitution (the fallback-applying projection is
18135        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
18136        // a future silent detour that re-normalized the list, dropped
18137        // duplicates the [`AplicacaoSpec::validate`]
18138        // `EntradaPathDuplicate` refusal already rejects at build time,
18139        // or (most severe) accidentally routed through the fallback-
18140        // applying sibling and returned the substrate catch-all when
18141        // the author declared an empty list — collapsing the raw-slot
18142        // and fallback-applied axes into one and breaking the
18143        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
18144        //
18145        // Peer of the sibling
18146        // [`Placement::clusters`]-shape byte-equal pin
18147        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
18148        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
18149        let fixtures: Vec<Vec<String>> = vec![
18150            Vec::new(),
18151            vec!["/api/cart".into()],
18152            vec!["/api/cart".into(), "/api/products".into()],
18153            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
18154        ];
18155        for paths in fixtures {
18156            let e = Entrada {
18157                host: "example.com".into(),
18158                para: "cart".into(),
18159                paths: paths.clone(),
18160                port: DEFAULT_SERVICO_PORT,
18161            };
18162            assert_eq!(
18163                e.paths(),
18164                paths.as_slice(),
18165                "Entrada::paths must return :entrada :paths verbatim \
18166                 (got {:?}, expected {:?})",
18167                e.paths(),
18168                paths.as_slice(),
18169            );
18170            assert_eq!(
18171                e.paths(),
18172                e.paths.as_slice(),
18173                "Entrada::paths accessor and .paths.as_slice() field \
18174                 access must byte-equal — the accessor is the substrate-\
18175                 primitive typed dispatch every downstream per-`:entrada` \
18176                 raw-slot path-list consumer must route through",
18177            );
18178            assert_eq!(
18179                e.paths().len(),
18180                e.paths.len(),
18181                "Entrada::paths().len() must byte-equal self.paths.len() \
18182                 — a length drift would silently split the paired \
18183                 pre-flight cascade-head `.is_empty()` probe input in \
18184                 the sibling [`Entrada::resolved_paths`] resolver from \
18185                 the per-entry validate loop's traversal input in \
18186                 [`AplicacaoSpec::validate`]",
18187            );
18188        }
18189    }
18190
18191    #[test]
18192    fn resolved_paths_reads_through_lifted_paths_accessor() {
18193        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
18194        // pre-flight `.paths().is_empty()` cascade-head probe (which
18195        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
18196        // catch-all fallback arm when the accessor projects the empty
18197        // slice) and the per-entry `.paths().iter().map(String::as_str)`
18198        // projection (which must reach every entry in the same order
18199        // the accessor projects, so the sibling
18200        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
18201        // per-entry projection stay in lockstep by construction) must
18202        // both key off the lifted accessor. Pins the two-site coherence
18203        // by exercising each production consumer end-to-end: (1) the
18204        // catch-all-fallback arm under the empty slice, (2) the
18205        // author-declared-verbatim arm under a two-entry cohort whose
18206        // per-entry projection must byte-equal the input's per-entry
18207        // author-declared paths in the author's declared order.
18208        //
18209        // Peer of the sibling M3
18210        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
18211        // `validate_placement_reads_through_lifted_clusters_accessor`
18212        // on the sibling `Placement::clusters` reader-site convergence.
18213        let empty = entrada_with_paths(vec![]);
18214        assert_eq!(
18215            empty.resolved_paths(),
18216            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
18217            "resolved_paths on empty :entrada :paths must trip the \
18218             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
18219             catch-all fallback — routing through the lifted paths() \
18220             accessor must not silently drop the fallback arm",
18221        );
18222
18223        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
18224        assert_eq!(
18225            declared.resolved_paths(),
18226            vec!["/api/cart", "/api/products"],
18227            "resolved_paths on non-empty :entrada :paths must return each \
18228             entry verbatim in the author's declared order — routing \
18229             through the lifted paths() accessor must not silently \
18230             reorder or drop entries",
18231        );
18232        // Byte-equal pin against the raw-slot accessor to keep the
18233        // fallback-applying resolver's per-entry projection input in
18234        // lockstep with the raw-slot accessor's projection.
18235        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
18236        assert_eq!(
18237            declared.resolved_paths(),
18238            raw_projected,
18239            "resolved_paths non-empty projection must byte-equal the \
18240             lifted paths() accessor's per-entry String::as_str projection \
18241             — the two projections share the same input slice by \
18242             construction, so any drift here would surface a silent \
18243             re-ordering / dedup / normalization detour in the resolver",
18244        );
18245    }
18246
18247    #[test]
18248    fn validate_reads_through_lifted_entrada_paths_accessor() {
18249        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
18250        // per-entry value-shape gate's `for p in e.paths()` traversal
18251        // (which must reach every entry in the same order the accessor
18252        // projects, so both the per-entry `EntradaPathEmpty` /
18253        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
18254        // the duplicate-detection HashSet insert that trips
18255        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
18256        // projection) must route through the lifted accessor. Pins the
18257        // coherence by exercising each production consumer end-to-end:
18258        // (1) the `EntradaPathEmpty` refusal fires on the second entry
18259        // of a two-entry cohort whose head is valid but tail is empty
18260        // (which requires the loop to reach the second entry through
18261        // the accessor), and (2) the `EntradaPathDuplicate` refusal
18262        // fires on the second entry of a two-entry cohort that shares
18263        // a path (which requires the loop to reach both entries — a
18264        // first-entry-only projection would silently pass since the
18265        // dedup HashSet has room for the first insert).
18266        //
18267        // Peer of the sibling
18268        // `validate_placement_reads_through_lifted_clusters_accessor`
18269        // on the sibling `Placement::clusters` reader-site convergence.
18270        let base = crate::AplicacaoSpec {
18271            membros: vec![crate::Membro {
18272                caixa: "cart".into(),
18273                versao: "^0.1".into(),
18274            }],
18275            contratos: Vec::new(),
18276            politicas: crate::MeshPolicy::default(),
18277            placement: crate::Placement {
18278                estrategia: crate::PlacementStrategy::SingleNode,
18279                clusters: vec!["rio".into()],
18280                shard_key: None,
18281                affinity: None,
18282            },
18283            entrada: Some(Entrada {
18284                host: "example.com".into(),
18285                para: "cart".into(),
18286                paths: vec!["/api/cart".into(), String::new()],
18287                port: DEFAULT_SERVICO_PORT,
18288            }),
18289        };
18290        assert_eq!(
18291            base.validate(),
18292            Err(crate::AplicacaoError::EntradaPathEmpty),
18293            "validate must trip EntradaPathEmpty on the second entry of \
18294             a two-entry cohort — routing through the lifted paths() \
18295             accessor must not silently short-circuit the loop at the \
18296             valid head entry",
18297        );
18298
18299        let mut dup = base;
18300        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
18301        assert_eq!(
18302            dup.validate(),
18303            Err(crate::AplicacaoError::EntradaPathDuplicate {
18304                path: "/api/cart".into(),
18305            }),
18306            "validate must trip EntradaPathDuplicate on the second entry \
18307             of a two-entry cohort that shares a path — routing through \
18308             the lifted paths() accessor must not silently short-circuit \
18309             the dedup HashSet insert at the first entry",
18310        );
18311    }
18312
18313    // ── Entrada::hostname / Entrada::hostnames — the substrate-
18314    //    canonical per-`:entrada` DNS-hostname resolver pair every
18315    //    Gateway-API-aware renderer reaching for a per-listener
18316    //    singular `hostname:` filter (Gateway) or a per-route plural
18317    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
18318    //    The three pin tests below fix the two-way accept-set the pair
18319    //    must always honor: (:singular-byte-equal-to-host,
18320    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
18321    //    on any arm surfaces at caixa-core build time rather than at
18322    //    cluster-apply time when the API server refuses the HTTPRoute
18323    //    for non-intersecting hostname filters. Peer discipline with
18324    //    the sibling `resolved_paths` accept-set pin block above on the
18325    //    per-`:entrada` path-list resolver axis.
18326
18327    fn entrada_with_host(host: &str) -> Entrada {
18328        Entrada {
18329            host: host.into(),
18330            para: "cart".into(),
18331            paths: Vec::new(),
18332            port: DEFAULT_SERVICO_PORT,
18333        }
18334    }
18335
18336    #[test]
18337    fn hostname_returns_entrada_host_byte_equal() {
18338        // The canonical singular-axis pin: [`Entrada::hostname`] must
18339        // return the `:entrada :host` field byte-for-byte, borrowed
18340        // from the typed slot's own [`String`] storage. Pins against a
18341        // future silent detour that re-normalized the host (an
18342        // accidental `.to_lowercase()` — validate_entrada_host already
18343        // enforces lowercase, so any re-normalization is redundant + a
18344        // drift surface between the validator and the accessor), a
18345        // trailing-`.` fully-qualified DNS shape substitution, or a
18346        // Punycode round-trip that lowered a Unicode host through IDNA.
18347        let e = entrada_with_host("checkout.quero.cloud");
18348        assert_eq!(
18349            e.hostname(),
18350            "checkout.quero.cloud",
18351            "Entrada::hostname must return :entrada :host verbatim \
18352             (got {:?})",
18353            e.hostname(),
18354        );
18355        assert_eq!(
18356            e.hostname(),
18357            e.host.as_str(),
18358            "Entrada::hostname must byte-equal the .host field access",
18359        );
18360    }
18361
18362    #[test]
18363    fn hostnames_returns_singleton_of_hostname_accessor() {
18364        // The pair-invariant pin: [`Entrada::hostnames`] must always
18365        // return exactly `vec![hostname()]` — the singleton list whose
18366        // sole entry is the substrate's canonical per-`:entrada`
18367        // singular hostname. Pins the two-consumer coherence axis: the
18368        // Gateway listener's singular `hostname:` filter and the
18369        // HTTPRoute's plural `spec.hostnames[]` filter list must
18370        // agree, else the Gateway API v1.x conformance layer rejects
18371        // the HTTPRoute at attach time with
18372        // `Accepted:False/NoMatchingParent` (the parent Gateway's
18373        // listener hostname doesn't intersect the route's hostname
18374        // filter list) — a divergence whose apply-time symptom is far
18375        // from any single-site commit and never surfaces in the
18376        // emitted YAML. Pinning the pair-invariant here makes any
18377        // future accidental split (an accidental `.to_string() + "."`
18378        // trailing-`.` on the plural side that didn't land on the
18379        // singular side, an accidental prefix stripping on one axis,
18380        // an accidental wildcard prepend the SNI fan-out overlay
18381        // authors on the plural side without a paired singular
18382        // migration) trip at caixa-core build time.
18383        let e = entrada_with_host("checkout.quero.cloud");
18384        assert_eq!(
18385            e.hostnames(),
18386            vec![e.hostname()],
18387            "Entrada::hostnames must return `vec![hostname()]` under \
18388             the pair-invariant — got {:?} vs. singleton {:?}",
18389            e.hostnames(),
18390            vec![e.hostname()],
18391        );
18392    }
18393
18394    #[test]
18395    fn hostnames_is_singleton_under_single_host_author_surface() {
18396        // The singleton-shape pin: under today's single-hostname-per-
18397        // `:entrada` author surface (the `:host` slot is a single
18398        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
18399        // must always return a list of length exactly one. Pins
18400        // against a future silent detour that returned an empty list
18401        // (which would emit an HTTPRoute with `spec.hostnames: []` —
18402        // matching every incoming Host header regardless of the
18403        // Aplicacao's declared ingress apex, silently over-matching
18404        // every foreign VirtualHost the parent Gateway also fronts) or
18405        // a duplicated entry (which the Gateway API v1.x parser
18406        // accepts as a `[]-length-2 list of equal hostnames]` but
18407        // whose semantics differ from the intended singleton). The
18408        // author-surface extension point ("a future `:entrada
18409        // :alt-hosts` list overlay" the docstring names) is the sole
18410        // future axis that flips this pin — that migration will re-
18411        // author this test to pin the new plural cardinality.
18412        let e = entrada_with_host("checkout.quero.cloud");
18413        assert_eq!(
18414            e.hostnames().len(),
18415            1,
18416            "Entrada::hostnames must be a singleton under today's \
18417             single-hostname-per-`:entrada` author surface — got \
18418             length {}: {:?}",
18419            e.hostnames().len(),
18420            e.hostnames(),
18421        );
18422    }
18423
18424    // ── Entrada::destination — the substrate-canonical per-`:entrada`
18425    //    destination-Servico scalar accessor every Gateway-API
18426    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
18427    //    discriminator arg (HTTPRoute name composer) or a per-rule
18428    //    `backendRefs[0].name` axis routes through. The two pin tests
18429    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
18430    //    either arm surfaces at caixa-core build time rather than at
18431    //    cluster-apply time when an HTTPRoute's `metadata.name` and
18432    //    `backendRefs[]` silently disagree on which destination Servico
18433    //    the ingress fronts. Peer discipline with the sibling
18434    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
18435    //    blocks above on the per-`:entrada` path-list / DNS-hostname
18436    //    resolver axes.
18437
18438    #[test]
18439    fn destination_returns_entrada_para_byte_equal() {
18440        // The canonical destination-scalar pin: [`Entrada::destination`]
18441        // must return the `:entrada :para` field byte-for-byte, borrowed
18442        // from the typed slot's own [`String`] storage. Pins against a
18443        // future silent detour that re-normalized the destination (an
18444        // accidental `.to_lowercase()` — the destination Servico is
18445        // already validated as a DNS-1123 label upstream, so any
18446        // re-normalization is redundant + a drift surface between the
18447        // validator and the accessor), a namespace-prefix rewrite (an
18448        // accidental `format!("{namespace}/{para}")` per-CR fully-
18449        // qualified rewrite that didn't land on the peer axis), or a
18450        // per-cluster suffix stamp the operator authors on one
18451        // consumer without the other.
18452        for para in ["cart", "checkout", "catalog", "orders-v2"] {
18453            let e = Entrada {
18454                host: "checkout.quero.cloud".into(),
18455                para: para.into(),
18456                paths: Vec::new(),
18457                port: DEFAULT_SERVICO_PORT,
18458            };
18459            assert_eq!(
18460                e.destination(),
18461                para,
18462                "Entrada::destination must return :entrada :para verbatim \
18463                 (got {:?}, expected {para:?})",
18464                e.destination(),
18465            );
18466            assert_eq!(
18467                e.destination(),
18468                e.para.as_str(),
18469                "Entrada::destination must byte-equal the .para field access",
18470            );
18471        }
18472    }
18473
18474    #[test]
18475    fn destination_borrows_from_entrada_para_storage() {
18476        // The borrow-not-copy pin: [`Entrada::destination`] must
18477        // return a `&str` slice that borrows from the typed slot's
18478        // own [`String`] storage — same-address invariant with
18479        // `entrada.para.as_str()`. Pins against a future silent detour
18480        // that allocated a fresh `String` (`self.para.clone()` in the
18481        // body would type-check but silently drop the borrow, and
18482        // every downstream consumer that assumed the returned slice
18483        // outlives `&self` would break on a stale-reference use-after-
18484        // free). Peer with the sibling `hostname_returns_entrada_
18485        // host_byte_equal` on the singular-DNS-hostname axis.
18486        let e = entrada_with_host("checkout.quero.cloud");
18487        let dest = e.destination();
18488        let para_slice = e.para.as_str();
18489        assert_eq!(
18490            dest.as_ptr(),
18491            para_slice.as_ptr(),
18492            "Entrada::destination must borrow from the .para String's \
18493             backing storage — a fresh allocation here means the \
18494             accessor no longer names the substrate-primitive typed \
18495             dispatch and every downstream consumer would silently \
18496             carry a detached copy",
18497        );
18498        assert_eq!(
18499            dest.len(),
18500            para_slice.len(),
18501            "Entrada::destination and .para.as_str() must byte-equal in \
18502             length as well as in address",
18503        );
18504    }
18505
18506    #[test]
18507    fn port_returns_entrada_port_verbatim_across_permutations() {
18508        // The canonical L4-port-scalar pin: [`Entrada::port`] must
18509        // return the `:entrada :port` field verbatim as a `u16` across
18510        // every author-declared value in the validated accept-set
18511        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
18512        // silent detour that clamped the port (an accidental
18513        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
18514        // land on the peer [`AplicacaoSpec::port_for_destination`]
18515        // resolver), rewrote it through a per-cluster port-remap table
18516        // the operator authors on one consumer without the other, or
18517        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
18518        // serde-default value (which would silently collapse the
18519        // distinction between "author explicitly declared `:port 8080`"
18520        // and "author omitted the slot and inherited the default" the
18521        // future per-cluster override slot depends on). Peer with the
18522        // sibling `destination_returns_entrada_para_byte_equal` +
18523        // `hostname_returns_entrada_host_byte_equal` pins on the
18524        // per-`:entrada` `&str` scalar axes.
18525        for port in [
18526            SERVICO_PORT_MIN,
18527            DEFAULT_SERVICO_PORT,
18528            8443u16,
18529            9090u16,
18530            u16::MAX,
18531        ] {
18532            let e = Entrada {
18533                host: "checkout.quero.cloud".into(),
18534                para: "cart".into(),
18535                paths: Vec::new(),
18536                port,
18537            };
18538            assert_eq!(
18539                e.port(),
18540                port,
18541                "Entrada::port must return :entrada :port verbatim \
18542                 (got {}, expected {port})",
18543                e.port(),
18544            );
18545            assert_eq!(
18546                e.port(),
18547                e.port,
18548                "Entrada::port accessor and .port field access must \
18549                 byte-equal — the accessor is the substrate-primitive \
18550                 typed dispatch every downstream L4-port consumer must \
18551                 route through",
18552            );
18553        }
18554    }
18555
18556    #[test]
18557    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
18558        // Two-consumer coherence pin: the
18559        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
18560        // (which reads through [`Entrada::port`] to compare against
18561        // [`SERVICO_PORT_MIN`]) and the
18562        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
18563        // through [`Entrada::port`] to emit the per-destination
18564        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
18565        // lifted accessor, so any future rebrand on the typed slot's
18566        // reader shape lands at exactly one place. Pins the two-site
18567        // coherence by exercising a below-floor port through validate
18568        // (which must reject) and a validated in-accept-set port through
18569        // port_for_destination (which must emit the same value the
18570        // accessor returns).
18571        let mut spec = three_member_spec();
18572        if let Some(e) = spec.entrada.as_mut() {
18573            e.port = 0;
18574        }
18575        assert_eq!(
18576            spec.validate().unwrap_err(),
18577            AplicacaoError::EntradaPortZero,
18578            "validate must reject `:entrada :port 0` through the lifted \
18579             Entrada::port accessor — port zero lies below \
18580             SERVICO_PORT_MIN and the validator routes through port() \
18581             to name the floor",
18582        );
18583
18584        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
18585            let mut spec = three_member_spec();
18586            if let Some(e) = spec.entrada.as_mut() {
18587                e.port = port;
18588            }
18589            spec.validate().expect(
18590                "entrada with in-accept-set :port must validate — the \
18591                 structural-floor gate reads through Entrada::port",
18592            );
18593            let entrada_ref = spec.entrada().expect(":entrada present");
18594            assert_eq!(
18595                spec.port_for_destination(entrada_ref.destination()),
18596                entrada_ref.port(),
18597                "port_for_destination(entrada.destination()) must equal \
18598                 entrada.port() — the two consumers of the per-:entrada \
18599                 L4-port axis (validator, per-destination resolver) both \
18600                 route through Entrada::port",
18601            );
18602        }
18603    }
18604
18605    #[test]
18606    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
18607        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
18608        // must return the `:contratos :de` field byte-for-byte, borrowed
18609        // from the typed slot's own [`String`] storage. Peer of the
18610        // sibling `destination_returns_entrada_para_byte_equal` pin on
18611        // the per-`:entrada` axis — same "the substrate-primitive
18612        // accessor must byte-equal the raw field access verbatim across
18613        // every author-declared value" discipline extended to the
18614        // per-`:contratos` caller arm. Pins against a future silent
18615        // detour that re-normalized the caller (an accidental
18616        // `.to_lowercase()` — every `:contratos :de` is validated as a
18617        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
18618        // re-normalization is redundant + a drift surface between the
18619        // validator and the accessor), a namespace-prefix rewrite (an
18620        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
18621        // rewrite that didn't land on the peer axis), or a per-cluster
18622        // suffix stamp the operator authors on one consumer without the
18623        // other.
18624        for de in ["cart", "checkout", "catalog", "orders-v2"] {
18625            let c = WitContract {
18626                de: de.into(),
18627                para: "downstream".into(),
18628                wit: "wasi:http/proxy".into(),
18629                endpoint: Some("/lookup".into()),
18630                subject: None,
18631                slot: None,
18632            };
18633            assert_eq!(
18634                c.source(),
18635                de,
18636                "WitContract::source must return :contratos :de verbatim \
18637                 (got {:?}, expected {de:?})",
18638                c.source(),
18639            );
18640            assert_eq!(
18641                c.source(),
18642                c.de.as_str(),
18643                "WitContract::source must byte-equal the .de field access",
18644            );
18645        }
18646    }
18647
18648    #[test]
18649    fn wit_contract_source_borrows_from_de_storage() {
18650        // The borrow-not-copy pin: [`WitContract::source`] must return a
18651        // `&str` slice that borrows from the typed slot's own [`String`]
18652        // storage — same-address invariant with `c.de.as_str()`. Pins
18653        // against a future silent detour that allocated a fresh `String`
18654        // (`self.de.clone()` in the body would type-check but silently
18655        // drop the borrow, and every downstream consumer that assumed
18656        // the returned slice outlives `&self` would break on a stale-
18657        // reference use-after-free). Peer of the sibling
18658        // `destination_borrows_from_entrada_para_storage` on the
18659        // per-`:entrada` axis.
18660        let c = WitContract {
18661            de: "cart".into(),
18662            para: "catalog".into(),
18663            wit: "wasi:http/proxy".into(),
18664            endpoint: Some("/lookup".into()),
18665            subject: None,
18666            slot: None,
18667        };
18668        let src = c.source();
18669        let de_slice = c.de.as_str();
18670        assert_eq!(
18671            src.as_ptr(),
18672            de_slice.as_ptr(),
18673            "WitContract::source must borrow from the .de String's \
18674             backing storage — a fresh allocation here means the \
18675             accessor no longer names the substrate-primitive typed \
18676             dispatch and every downstream consumer would silently \
18677             carry a detached copy",
18678        );
18679        assert_eq!(
18680            src.len(),
18681            de_slice.len(),
18682            "WitContract::source and .de.as_str() must byte-equal in \
18683             length as well as in address",
18684        );
18685    }
18686
18687    #[test]
18688    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
18689        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
18690        // must return the `:contratos :para` field byte-for-byte,
18691        // borrowed from the typed slot's own [`String`] storage. Peer of
18692        // the sibling `destination_returns_entrada_para_byte_equal` on
18693        // the per-`:entrada` axis — both accessors name "the destination-
18694        // Servico byte-string" concept on their respective mesh-slot
18695        // atoms (per-ingress apex vs. per-typed-edge callee) and both
18696        // must project the underlying `.para` field verbatim so every
18697        // downstream renderer that composes them with peer accessors
18698        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
18699        // per-edge L4 port emit site) reads the same byte-string the
18700        // author declared.
18701        for para in ["catalog", "payment", "orders", "inventory-v3"] {
18702            let c = WitContract {
18703                de: "cart".into(),
18704                para: para.into(),
18705                wit: "wasi:http/proxy".into(),
18706                endpoint: Some("/lookup".into()),
18707                subject: None,
18708                slot: None,
18709            };
18710            assert_eq!(
18711                c.destination(),
18712                para,
18713                "WitContract::destination must return :contratos :para \
18714                 verbatim (got {:?}, expected {para:?})",
18715                c.destination(),
18716            );
18717            assert_eq!(
18718                c.destination(),
18719                c.para.as_str(),
18720                "WitContract::destination must byte-equal the .para \
18721                 field access",
18722            );
18723        }
18724    }
18725
18726    #[test]
18727    fn wit_contract_destination_borrows_from_para_storage() {
18728        // The borrow-not-copy pin: [`WitContract::destination`] must
18729        // return a `&str` slice that borrows from the typed slot's own
18730        // [`String`] storage — same-address invariant with
18731        // `c.para.as_str()`. Peer of the sibling
18732        // `destination_borrows_from_entrada_para_storage` on the
18733        // per-`:entrada` axis.
18734        let c = WitContract {
18735            de: "cart".into(),
18736            para: "catalog".into(),
18737            wit: "wasi:http/proxy".into(),
18738            endpoint: Some("/lookup".into()),
18739            subject: None,
18740            slot: None,
18741        };
18742        let dest = c.destination();
18743        let para_slice = c.para.as_str();
18744        assert_eq!(
18745            dest.as_ptr(),
18746            para_slice.as_ptr(),
18747            "WitContract::destination must borrow from the .para \
18748             String's backing storage — a fresh allocation here means \
18749             the accessor no longer names the substrate-primitive typed \
18750             dispatch and every downstream consumer would silently \
18751             carry a detached copy",
18752        );
18753        assert_eq!(
18754            dest.len(),
18755            para_slice.len(),
18756            "WitContract::destination and .para.as_str() must byte-equal \
18757             in length as well as in address",
18758        );
18759    }
18760
18761    #[test]
18762    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
18763        // The canonical per-`:contratos` WIT-world-reference scalar pin:
18764        // [`WitContract::world_ref`] must return the `:contratos :wit`
18765        // field byte-for-byte, borrowed from the typed slot's own
18766        // [`String`] storage. Sibling of the peer per-`:contratos`
18767        // [`WitContract::source`] / [`WitContract::destination`]
18768        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
18769        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
18770        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
18771        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
18772        // "the substrate-primitive accessor must byte-equal the raw
18773        // field access verbatim across every author-declared value"
18774        // discipline extended to the per-`:contratos` WIT-world arm.
18775        // Pins against a future silent detour that re-canonicalized the
18776        // WIT world reference (an accidental `.to_lowercase()` pass that
18777        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
18778        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
18779        // gate is already lowercase-prefixed so any re-normalization is
18780        // redundant + a drift surface between the validator and the
18781        // accessor), an M4-promotion-shape rewrite that formatted a
18782        // typed WIT-world enum through [`Display`] and silently drifted
18783        // the printer output from the source `caixa.lisp`, or a per-
18784        // cluster WIT-alias rewrite that didn't land on the peer field-
18785        // access sites. Five values sweep the shape-dispatch accept-set
18786        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
18787        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
18788        // `wasi:keyvalue/`).
18789        for (wit, endpoint, subject, slot) in [
18790            ("wasi:http/proxy", Some("/lookup"), None, None),
18791            ("http:proxy", Some("/health"), None, None),
18792            ("nats:pub-sub", None, Some("orders.paid"), None),
18793            ("kafka:events", None, Some("checkout-events"), None),
18794            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
18795        ] {
18796            let c = WitContract {
18797                de: "cart".into(),
18798                para: "downstream".into(),
18799                wit: wit.into(),
18800                endpoint: endpoint.map(str::to_string),
18801                subject: subject.map(str::to_string),
18802                slot: slot.map(str::to_string),
18803            };
18804            assert_eq!(
18805                c.world_ref(),
18806                wit,
18807                "WitContract::world_ref must return :contratos :wit \
18808                 verbatim (got {:?}, expected {wit:?})",
18809                c.world_ref(),
18810            );
18811            assert_eq!(
18812                c.world_ref(),
18813                c.wit.as_str(),
18814                "WitContract::world_ref must byte-equal the .wit field \
18815                 access",
18816            );
18817        }
18818    }
18819
18820    #[test]
18821    fn wit_contract_world_ref_borrows_from_wit_storage() {
18822        // The borrow-not-copy pin: [`WitContract::world_ref`] must
18823        // return a `&str` slice that borrows from the typed slot's own
18824        // [`String`] storage — same-address invariant with
18825        // `c.wit.as_str()`. Pins against a future silent detour that
18826        // allocated a fresh `String` (`self.wit.clone()` in the body
18827        // would type-check but silently drop the borrow, and every
18828        // downstream consumer that assumed the returned slice outlives
18829        // `&self` would break on a stale-reference use-after-free — the
18830        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
18831        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
18832        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
18833        // / [`is_pubsub`][WitContract::is_pubsub] /
18834        // [`is_store`][WitContract::is_store] methods route through —
18835        // each borrow from the WitContract's own storage and each would
18836        // silently misbehave if this accessor produced a detached copy).
18837        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
18838        // [`WitContract::destination`] and per-`:entrada`
18839        // [`Entrada::destination`] / [`Entrada::hostname`] and
18840        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
18841        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
18842        let c = WitContract {
18843            de: "cart".into(),
18844            para: "catalog".into(),
18845            wit: "wasi:http/proxy".into(),
18846            endpoint: Some("/lookup".into()),
18847            subject: None,
18848            slot: None,
18849        };
18850        let world = c.world_ref();
18851        let wit_slice = c.wit.as_str();
18852        assert_eq!(
18853            world.as_ptr(),
18854            wit_slice.as_ptr(),
18855            "WitContract::world_ref must borrow from the .wit String's \
18856             backing storage — a fresh allocation here means the \
18857             accessor no longer names the substrate-primitive typed \
18858             dispatch and every downstream consumer would silently carry \
18859             a detached copy",
18860        );
18861        assert_eq!(
18862            world.len(),
18863            wit_slice.len(),
18864            "WitContract::world_ref and .wit.as_str() must byte-equal in \
18865             length as well as in address",
18866        );
18867    }
18868
18869    #[test]
18870    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
18871        // Sibling-triple invariant pin composing all three per-`:contratos`
18872        // substrate-primitive typed dispatches — [`WitContract::source`]
18873        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
18874        // [`WitContract::world_ref`] — at the joint
18875        // `(source(), destination(), world_ref())` call shape every
18876        // renderer that fans on per-edge caller-callee-shape identity
18877        // keys off. The invariant, evaluated per-contract:
18878        //
18879        //   (c.source(), c.destination(), c.world_ref())
18880        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
18881        //
18882        // Closes the last unlifted per-`:contratos` scalar axis — every
18883        // downstream consumer that reads the triple now routes through
18884        // exactly three typed dispatches on the substrate primitive,
18885        // not two typed + one open-coded field access. A future refactor
18886        // that silently split any one accessor's projection (an
18887        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
18888        // canonicalization that didn't reach the peer `source`/
18889        // `destination` arms, an accidental `source()` per-cluster
18890        // caller-alias rewrite that didn't land on the `world_ref` peer)
18891        // surfaces at caixa-core build time. Peer of the sibling per-
18892        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
18893        // per-`:entrada` `(hostname(), destination())` (6db982c /
18894        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
18895        // axes, extended to the per-`:contratos` triple.
18896        for (de, para, wit, endpoint, subject, slot) in [
18897            (
18898                "cart",
18899                "catalog",
18900                "wasi:http/proxy",
18901                Some("/lookup"),
18902                None,
18903                None,
18904            ),
18905            (
18906                "checkout",
18907                "orders",
18908                "nats:pub-sub",
18909                None,
18910                Some("orders.paid"),
18911                None,
18912            ),
18913            (
18914                "cart",
18915                "kv",
18916                "wasi:keyvalue/store",
18917                None,
18918                None,
18919                Some("carts/{cart_id}"),
18920            ),
18921            (
18922                "orders-v2",
18923                "inventory-v3",
18924                "http:proxy",
18925                Some("/reserve"),
18926                None,
18927                None,
18928            ),
18929        ] {
18930            let c = WitContract {
18931                de: de.into(),
18932                para: para.into(),
18933                wit: wit.into(),
18934                endpoint: endpoint.map(str::to_string),
18935                subject: subject.map(str::to_string),
18936                slot: slot.map(str::to_string),
18937            };
18938            assert_eq!(
18939                (c.source(), c.destination(), c.world_ref()),
18940                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
18941                "(WitContract::source, ::destination, ::world_ref) must \
18942                 project (.de, .para, .wit) verbatim across every author-\
18943                 declared triple (got ({:?}, {:?}, {:?}), expected \
18944                 ({de:?}, {para:?}, {wit:?}))",
18945                c.source(),
18946                c.destination(),
18947                c.world_ref(),
18948            );
18949        }
18950    }
18951
18952    #[test]
18953    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
18954        // The canonical per-`:contratos` owned-form caller-callee-pair
18955        // pin: [`WitContract::edge_pair`] must return the
18956        // `(source(), destination())` tuple in owned form byte-for-byte,
18957        // projected through the lifted [`WitContract::source`] /
18958        // [`WitContract::destination`] scalar accessors. Pins the
18959        // composite-projection invariant on the per-`:contratos`
18960        // mesh-slot atom — every author-declared `(de, para)` pair must
18961        // round-trip verbatim through the substrate primitive's typed
18962        // dispatch, so the nine [`AplicacaoError`] diagnostic-
18963        // construction sites the accessor now feeds
18964        // ([`AplicacaoError::EmptyWit`],
18965        // [`AplicacaoError::ContratoEndpointEmpty`],
18966        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
18967        // [`AplicacaoError::ContratoEndpointInvalid`],
18968        // [`AplicacaoError::ContratoSubjectEmpty`],
18969        // [`AplicacaoError::ContratoSubjectInvalid`],
18970        // [`AplicacaoError::ContratoSlotEmpty`],
18971        // [`AplicacaoError::ContratoSlotInvalid`],
18972        // [`AplicacaoError::ContratoDuplicate`]) all read the same
18973        // `(de, para)` label pair every author sees at the source
18974        // `caixa.lisp`. Pins against a future silent detour that swapped
18975        // the `.0` / `.1` arms (an accidental `(destination(),
18976        // source())` re-order in the body would silently invert every
18977        // downstream diagnostic's `de:` / `para:` label pair, silently
18978        // reversing the direction of every operator-facing typed error
18979        // arrow), a fresh-allocation shape drift (an accidental
18980        // `.to_string()` on one arm but not the other would leave the
18981        // owned/borrowed pair mismatched vs. the sibling `source()` /
18982        // `destination()` returns), or an M4 per-cluster caller/callee-
18983        // alias rewrite that landed on `source()` without reaching
18984        // `destination()` (or vice versa). Peer of the sibling per-
18985        // `:contratos` `(source, destination, world_ref)` triple
18986        // pin above on the mesh-slot-atom scalar-value axes, extended
18987        // to the owned-form pair-projection axis.
18988        for (de, para, wit, endpoint, subject, slot) in [
18989            (
18990                "cart",
18991                "catalog",
18992                "wasi:http/proxy",
18993                Some("/lookup"),
18994                None,
18995                None,
18996            ),
18997            (
18998                "checkout",
18999                "orders",
19000                "nats:pub-sub",
19001                None,
19002                Some("orders.paid"),
19003                None,
19004            ),
19005            (
19006                "cart",
19007                "kv",
19008                "wasi:keyvalue/store",
19009                None,
19010                None,
19011                Some("carts/{cart_id}"),
19012            ),
19013            (
19014                "orders-v2",
19015                "inventory-v3",
19016                "http:proxy",
19017                Some("/reserve"),
19018                None,
19019                None,
19020            ),
19021        ] {
19022            let c = WitContract {
19023                de: de.into(),
19024                para: para.into(),
19025                wit: wit.into(),
19026                endpoint: endpoint.map(str::to_string),
19027                subject: subject.map(str::to_string),
19028                slot: slot.map(str::to_string),
19029            };
19030            assert_eq!(
19031                c.edge_pair(),
19032                (de.to_string(), para.to_string()),
19033                "WitContract::edge_pair must return (:contratos :de, \
19034                 :contratos :para) as an owned tuple verbatim (got {:?}, \
19035                 expected ({de:?}, {para:?}))",
19036                c.edge_pair(),
19037            );
19038        }
19039    }
19040
19041    #[test]
19042    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
19043        // The composition pin: [`WitContract::edge_pair`] must return
19044        // exactly `(source().to_string(), destination().to_string())` —
19045        // the owned form of the sibling accessor pair — so any future
19046        // refactor that silently re-authored the caller-arm / callee-arm
19047        // projection to bypass the lifted scalar accessors (an accidental
19048        // `(self.de.clone(), self.para.clone())` regression back to the
19049        // raw field-access shape, an M4-typed-caller-enum `Display`
19050        // re-canonicalization on `source()` that didn't reach
19051        // `edge_pair()`, a per-cluster alias rewrite the operator lands
19052        // on `destination()` without reaching this composite projection)
19053        // trips at caixa-core build time. Pins the "typed dispatch
19054        // composes with typed dispatch, not with raw field access"
19055        // discipline every downstream diagnostic-construction site now
19056        // routes through — a `de:` / `para:` label pair whose
19057        // projection silently drifted off the substrate primitive's
19058        // scalar accessors would silently split the diagnostic's self-
19059        // locating signal from the source `caixa.lisp` author's view.
19060        // Peer of the sibling per-`:politicas` `is_empty` /
19061        // `validate_politicas` accessor-routing-pin family on the M3
19062        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
19063        let c = WitContract {
19064            de: "cart".into(),
19065            para: "catalog".into(),
19066            wit: "wasi:http/proxy".into(),
19067            endpoint: Some("/lookup".into()),
19068            subject: None,
19069            slot: None,
19070        };
19071        assert_eq!(
19072            c.edge_pair(),
19073            (c.source().to_string(), c.destination().to_string()),
19074            "WitContract::edge_pair must compose exactly \
19075             (source().to_string(), destination().to_string()) — a \
19076             bypass of either sibling accessor here would silently \
19077             decouple the composite-projection axis from the \
19078             substrate-primitive scalar accessors every downstream \
19079             consumer routes through",
19080        );
19081    }
19082
19083    #[test]
19084    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
19085     {
19086        // The canonical per-`:contratos` owned-form
19087        // caller-callee-world-ref-triple pin:
19088        // [`WitContract::edge_triple`] must return the
19089        // `(source(), destination(), world_ref())` tuple in owned form
19090        // byte-for-byte, projected through the lifted
19091        // [`WitContract::source`] / [`WitContract::destination`] /
19092        // [`WitContract::world_ref`] scalar accessors. Pins the
19093        // composite-projection invariant on the per-`:contratos`
19094        // mesh-slot atom — every author-declared `(de, para, wit)`
19095        // triple must round-trip verbatim through the substrate
19096        // primitive's typed dispatch, so the nine
19097        // [`AplicacaoError`] diagnostic-construction sites the
19098        // accessor now feeds (the [`WitTarget`]-dispatch's eight
19099        // wrong-target / missing-target / invalid-wit / capability-
19100        // with-payload arms in [`WitContract::target`], plus the
19101        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
19102        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
19103        // read the same `(de, para, wit)` triple every author sees at
19104        // the source `caixa.lisp`. Pins against a future silent
19105        // detour that swapped any two arms (an accidental `(destination(),
19106        // source(), world_ref())` re-order in the body would silently
19107        // invert every downstream diagnostic's `de:` / `para:` label
19108        // pair, silently reversing the direction of every operator-
19109        // facing typed error arrow), a fresh-allocation shape drift
19110        // (an accidental `.to_string()` skipped on one arm would leave
19111        // the owned/borrowed triple mismatched vs. the sibling
19112        // `source()` / `destination()` / `world_ref()` returns), or an
19113        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
19114        // canonicalization pass that landed on one accessor without
19115        // reaching the peers. Peer of the sibling per-`:contratos`
19116        // caller-callee-pair
19117        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
19118        // pin on the mesh-slot-atom composite-projection axis,
19119        // extended to the triple-projection axis.
19120        for (de, para, wit, endpoint, subject, slot) in [
19121            (
19122                "cart",
19123                "catalog",
19124                "wasi:http/proxy",
19125                Some("/lookup"),
19126                None,
19127                None,
19128            ),
19129            (
19130                "checkout",
19131                "orders",
19132                "nats:pub-sub",
19133                None,
19134                Some("orders.paid"),
19135                None,
19136            ),
19137            (
19138                "cart",
19139                "kv",
19140                "wasi:keyvalue/store",
19141                None,
19142                None,
19143                Some("carts/{cart_id}"),
19144            ),
19145            (
19146                "orders-v2",
19147                "inventory-v3",
19148                "http:proxy",
19149                Some("/reserve"),
19150                None,
19151                None,
19152            ),
19153        ] {
19154            let c = WitContract {
19155                de: de.into(),
19156                para: para.into(),
19157                wit: wit.into(),
19158                endpoint: endpoint.map(str::to_string),
19159                subject: subject.map(str::to_string),
19160                slot: slot.map(str::to_string),
19161            };
19162            assert_eq!(
19163                c.edge_triple(),
19164                (de.to_string(), para.to_string(), wit.to_string()),
19165                "WitContract::edge_triple must return (:contratos :de, \
19166                 :contratos :para, :contratos :wit) as an owned triple \
19167                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
19168                c.edge_triple(),
19169            );
19170        }
19171    }
19172
19173    #[test]
19174    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
19175        // The composition pin: [`WitContract::edge_triple`] must return
19176        // exactly `(source().to_string(), destination().to_string(),
19177        // world_ref().to_string())` — the owned form of the sibling
19178        // scalar-accessor triple — so any future refactor that silently
19179        // re-authored one arm's projection to bypass the lifted scalar
19180        // accessors (an accidental `(self.de.clone(), self.para.clone(),
19181        // self.wit.clone())` regression back to the raw field-access
19182        // shape the internal `edge` closure and the ContratoDuplicate
19183        // diagnostic both carried before this lift landed, an
19184        // M4-typed-caller-enum `Display` re-canonicalization on
19185        // `source()` that didn't reach `edge_triple()`, a per-cluster
19186        // alias rewrite the operator lands on `destination()` /
19187        // `world_ref()` without reaching this composite projection)
19188        // trips at caixa-core build time. Pins the "typed dispatch
19189        // composes with typed dispatch, not with raw field access"
19190        // discipline every downstream diagnostic-construction site now
19191        // routes through — a `de:` / `para:` / `wit:` triple whose
19192        // projection silently drifted off the substrate primitive's
19193        // scalar accessors would silently split the diagnostic's self-
19194        // locating signal from the source `caixa.lisp` author's view.
19195        // Peer of the sibling per-`:contratos` edge_pair composition-
19196        // pin above on the mesh-slot-atom composite-projection axis.
19197        let c = WitContract {
19198            de: "cart".into(),
19199            para: "catalog".into(),
19200            wit: "wasi:http/proxy".into(),
19201            endpoint: Some("/lookup".into()),
19202            subject: None,
19203            slot: None,
19204        };
19205        assert_eq!(
19206            c.edge_triple(),
19207            (
19208                c.source().to_string(),
19209                c.destination().to_string(),
19210                c.world_ref().to_string(),
19211            ),
19212            "WitContract::edge_triple must compose exactly \
19213             (source().to_string(), destination().to_string(), \
19214             world_ref().to_string()) — a bypass of any sibling accessor \
19215             here would silently decouple the composite-projection axis \
19216             from the substrate-primitive scalar accessors every \
19217             downstream consumer routes through",
19218        );
19219    }
19220
19221    #[test]
19222    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
19223        // The canonical semantics-pin: [`WitContract::edge_triple`] must
19224        // project the full `(de, para, wit)` identity of a `:contratos`
19225        // edge — the sub-triple every triple-carrying
19226        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
19227        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
19228        // missing-target, capability-with-payload, invalid-wit, and the
19229        // duplicate-gate). Rejects a drift in shape (an accidental
19230        // silent detour that returned a `(de, para)` pair or added an
19231        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
19232        // would trip here because the return type would no longer
19233        // pattern-match the eight `let (de, para, wit) = edge();`
19234        // destructures the [`WitContract::target`] dispatch feeds off
19235        // + the paired duplicate-gate `let (de, para, wit) =
19236        // c.edge_triple();` destructure in
19237        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
19238        // `:contratos` caller-callee-pair pin above extended to the
19239        // triple projection surface: closes the "one composite
19240        // accessor per typed diagnostic-construction sub-tuple"
19241        // discipline on the per-`:contratos` mesh-slot-atom axis.
19242        let c = WitContract {
19243            de: "checkout".into(),
19244            para: "orders".into(),
19245            wit: "nats:pub-sub".into(),
19246            endpoint: None,
19247            subject: Some("orders.paid".into()),
19248            slot: None,
19249        };
19250        let (de, para, wit) = c.edge_triple();
19251        assert_eq!(de, "checkout");
19252        assert_eq!(para, "orders");
19253        assert_eq!(wit, "nats:pub-sub");
19254    }
19255
19256    #[test]
19257    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
19258     {
19259        // The composition pin: [`WitContract::identity`] must return
19260        // exactly `(source(), destination(), world_ref(), endpoint(),
19261        // subject(), slot())` — the borrowed form of the six-scalar-
19262        // accessor identity axis. Any future refactor that silently
19263        // re-authored one arm's projection to bypass a scalar accessor
19264        // (a `self.de.as_str()` regression back to raw field access on
19265        // any of the three required arms, a `self.endpoint.as_deref()`
19266        // regression on any of the three optional arms, an M4 per-
19267        // cluster caller/callee-alias rewrite the operator lands on
19268        // `source()` / `destination()` without reaching this composite
19269        // projection) trips at caixa-core build time. Sweeps four
19270        // permutations of the WIT-shape × payload lattice — HTTP with
19271        // endpoint, pub-sub with subject, store with slot, payload-less
19272        // capability — so every payload arm is exercised. Peer of the
19273        // sibling per-`:contratos`
19274        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
19275        // composition pin on the mesh-slot-atom composite-projection
19276        // axis; extends the discipline from the (de, para, wit) prefix
19277        // onto the full-identity axis carrying the three payload arms.
19278        for (de, para, wit, endpoint, subject, slot) in [
19279            (
19280                "cart",
19281                "catalog",
19282                "wasi:http/proxy",
19283                Some("/lookup"),
19284                None,
19285                None,
19286            ),
19287            (
19288                "checkout",
19289                "orders",
19290                "nats:pub-sub",
19291                None,
19292                Some("orders.paid"),
19293                None,
19294            ),
19295            (
19296                "cart",
19297                "kv",
19298                "wasi:keyvalue/store",
19299                None,
19300                None,
19301                Some("carts/{cart_id}"),
19302            ),
19303            ("audit", "sink", "wasi:logging", None, None, None),
19304        ] {
19305            let c = WitContract {
19306                de: de.into(),
19307                para: para.into(),
19308                wit: wit.into(),
19309                endpoint: endpoint.map(str::to_owned),
19310                subject: subject.map(str::to_owned),
19311                slot: slot.map(str::to_owned),
19312            };
19313            assert_eq!(
19314                c.identity(),
19315                (
19316                    c.source(),
19317                    c.destination(),
19318                    c.world_ref(),
19319                    c.endpoint(),
19320                    c.subject(),
19321                    c.slot(),
19322                ),
19323                "WitContract::identity must compose exactly \
19324                 (source(), destination(), world_ref(), endpoint(), \
19325                 subject(), slot()) — a bypass of any sibling accessor \
19326                 here would silently decouple the identity-projection \
19327                 axis from the substrate-primitive scalar accessors \
19328                 every dedup-key consumer routes through",
19329            );
19330        }
19331    }
19332
19333    #[test]
19334    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
19335        // The canonical semantics-pin: [`WitContract::identity`] must
19336        // project the six-axis (de, para, wit, endpoint, subject, slot)
19337        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19338        // gate keys off — two `WitContract`s that agree on all six axes
19339        // are the same typed edge declared twice, the graph-edge
19340        // analogue of duplicate `:membros` / `:placement :clusters` /
19341        // `:entrada :paths` entries. Rejects a shape drift (an
19342        // accidental silent detour that returned a prefix tuple or
19343        // added an extra field) by pattern-matching the six-arm shape.
19344        // Peer of the sibling per-`:contratos`
19345        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
19346        // pin extended from the (de, para, wit) prefix onto the full
19347        // six-axis identity that the dedup key rides.
19348        let c = WitContract {
19349            de: "cart".into(),
19350            para: "catalog".into(),
19351            wit: "wasi:http/proxy".into(),
19352            endpoint: Some("/products/:id".into()),
19353            subject: None,
19354            slot: None,
19355        };
19356        let (de, para, wit, endpoint, subject, slot) = c.identity();
19357        assert_eq!(de, "cart");
19358        assert_eq!(para, "catalog");
19359        assert_eq!(wit, "wasi:http/proxy");
19360        assert_eq!(endpoint, Some("/products/:id"));
19361        assert_eq!(subject, None);
19362        assert_eq!(slot, None);
19363
19364        // Two byte-identical contracts must produce equal identities —
19365        // the dedup key's foundational invariant.
19366        let c2 = c.clone();
19367        assert_eq!(c.identity(), c2.identity());
19368
19369        // Any change on any of the six axes must break the identity —
19370        // sweeps by mutating one axis at a time.
19371        let mut mutated = c.clone();
19372        mutated.de = "search".into();
19373        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
19374        let mut mutated = c.clone();
19375        mutated.para = "warehouse".into();
19376        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
19377        let mut mutated = c.clone();
19378        mutated.wit = "http:legacy".into();
19379        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
19380        let mut mutated = c.clone();
19381        mutated.endpoint = Some("/search".into());
19382        assert_ne!(
19383            c.identity(),
19384            mutated.identity(),
19385            "endpoint axis must partition"
19386        );
19387        let mut mutated = c.clone();
19388        mutated.subject = Some("orders.paid".into());
19389        assert_ne!(
19390            c.identity(),
19391            mutated.identity(),
19392            "subject axis must partition"
19393        );
19394        let mut mutated = c;
19395        mutated.slot = Some("carts/{id}".into());
19396        assert_ne!(mutated.identity().5, None, "slot axis must partition");
19397    }
19398
19399    #[test]
19400    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
19401        // The canonical per-`:contratos` structural-self-edge pin:
19402        // [`WitContract::is_self_loop`] must return `true` when the
19403        // `:de` and `:para` fields agree byte-for-byte, across every
19404        // WIT-shape variant the per-edge shape family carries. Pins
19405        // the shape-agnostic identity-space partition the
19406        // [`AplicacaoSpec::validate`] self-edge gate at
19407        // caixa-core/src/aplicacao.rs:5559 fires against — all four
19408        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
19409        // under the same one predicate. Four permutations sweep the
19410        // accept-set: HTTP with endpoint, pub-sub with subject, KV
19411        // store with slot, and payload-less capability.
19412        for (nome, wit, endpoint, subject, slot) in [
19413            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
19414            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
19415            (
19416                "kv",
19417                "wasi:keyvalue/store",
19418                None,
19419                None,
19420                Some("carts/{cart_id}"),
19421            ),
19422            ("audit", "wasi:logging", None, None, None),
19423        ] {
19424            let c = WitContract {
19425                de: nome.into(),
19426                para: nome.into(),
19427                wit: wit.into(),
19428                endpoint: endpoint.map(str::to_string),
19429                subject: subject.map(str::to_string),
19430                slot: slot.map(str::to_string),
19431            };
19432            assert!(
19433                c.is_self_loop(),
19434                "WitContract::is_self_loop must return true when \
19435                 :contratos :de == :contratos :para (got false on \
19436                 {nome:?} under {wit:?})",
19437            );
19438        }
19439    }
19440
19441    #[test]
19442    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
19443        // The complement pin: [`WitContract::is_self_loop`] must return
19444        // `false` on every well-shaped inter-Servico contract (the
19445        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
19446        // names — "Servico A calls Servico B" between two distinct
19447        // graph nodes). Pins against a future silent detour that
19448        // inverted the predicate (an accidental `!= ` swap for `==`
19449        // would silently reject every legitimate inter-Servico edge
19450        // and admit every self-edge — the exact inversion of the
19451        // author-intended shape). Four permutations sweep the same
19452        // WIT-shape accept-set the sibling positive-arm test carries.
19453        for (de, para, wit, endpoint, subject, slot) in [
19454            (
19455                "cart",
19456                "catalog",
19457                "wasi:http/proxy",
19458                Some("/lookup"),
19459                None,
19460                None,
19461            ),
19462            (
19463                "checkout",
19464                "orders",
19465                "nats:pub-sub",
19466                None,
19467                Some("orders.paid"),
19468                None,
19469            ),
19470            (
19471                "cart",
19472                "kv",
19473                "wasi:keyvalue/store",
19474                None,
19475                None,
19476                Some("carts/{cart_id}"),
19477            ),
19478            ("audit", "sink", "wasi:logging", None, None, None),
19479        ] {
19480            let c = WitContract {
19481                de: de.into(),
19482                para: para.into(),
19483                wit: wit.into(),
19484                endpoint: endpoint.map(str::to_string),
19485                subject: subject.map(str::to_string),
19486                slot: slot.map(str::to_string),
19487            };
19488            assert!(
19489                !c.is_self_loop(),
19490                "WitContract::is_self_loop must return false when \
19491                 :contratos :de differs from :contratos :para (got true \
19492                 on {de:?} → {para:?} under {wit:?})",
19493            );
19494        }
19495    }
19496
19497    #[test]
19498    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
19499        // The composition pin: [`WitContract::is_self_loop`] must
19500        // resolve to exactly `self.source() == self.destination()` —
19501        // the equality probe of the sibling scalar-accessor pair — so
19502        // any future refactor that silently re-authored the predicate
19503        // to bypass the lifted scalar accessors (an accidental
19504        // `self.de == self.para` regression back to the raw field-
19505        // access shape, an M4-typed-caller-enum identity-comparison
19506        // rule that landed on `source()` without reaching
19507        // `destination()`, a per-cluster alias rewrite the operator
19508        // pins on `destination()` without reaching this predicate)
19509        // trips at caixa-core build time. Pins the "typed dispatch
19510        // composes with typed dispatch, not with raw field access"
19511        // discipline the sibling [`WitContract::edge_pair`] /
19512        // [`WitContract::edge_triple`] composite-projection accessors
19513        // already carry, extended onto the per-edge endpoint-equality
19514        // predicate axis. Positive and complement arms both fire.
19515        let self_edge = WitContract {
19516            de: "cart".into(),
19517            para: "cart".into(),
19518            wit: "wasi:http/proxy".into(),
19519            endpoint: Some("/lookup".into()),
19520            subject: None,
19521            slot: None,
19522        };
19523        assert_eq!(
19524            self_edge.is_self_loop(),
19525            self_edge.source() == self_edge.destination(),
19526            "WitContract::is_self_loop must compose exactly \
19527             `source() == destination()` — a bypass of either sibling \
19528             accessor here would silently decouple the endpoint-\
19529             equality predicate from the substrate-primitive scalar \
19530             accessors every downstream consumer routes through",
19531        );
19532        let inter_edge = WitContract {
19533            de: "cart".into(),
19534            para: "catalog".into(),
19535            wit: "wasi:http/proxy".into(),
19536            endpoint: Some("/lookup".into()),
19537            subject: None,
19538            slot: None,
19539        };
19540        assert_eq!(
19541            inter_edge.is_self_loop(),
19542            inter_edge.source() == inter_edge.destination(),
19543            "WitContract::is_self_loop must compose exactly \
19544             `source() == destination()` on the complement arm too",
19545        );
19546    }
19547
19548    #[test]
19549    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
19550        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
19551        // pin: [`WitContract::endpoint`] must return the `:contratos
19552        // :endpoint` field byte-for-byte, borrowed from the typed slot's
19553        // own `Option<String>` storage. Peer of the sibling
19554        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
19555        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
19556        // mesh-slot `Option<String>` optional-scalar axes — same "the
19557        // substrate-primitive accessor must byte-equal the raw field
19558        // access verbatim across every author-declared value" discipline
19559        // extended to the per-`:contratos` HTTP-payload-carrier arm.
19560        // Pins against a future silent detour that re-canonicalized the
19561        // endpoint (an accidental percent-encoding pass that didn't
19562        // reach the peer field-access site at the dedup key, a per-CR
19563        // fully-qualified prefix rewrite the operator authors on one
19564        // consumer without the other, or an M4 typed-path-template
19565        // `Display` re-canonicalization that silently drifted the
19566        // printer output from the source `caixa.lisp`). Four values
19567        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
19568        // gate upstream admits (short root-path, dashed, param-shaped,
19569        // deep-hierarchy).
19570        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
19571            let c = WitContract {
19572                de: "cart".into(),
19573                para: "catalog".into(),
19574                wit: "wasi:http/proxy".into(),
19575                endpoint: Some(endpoint.into()),
19576                subject: None,
19577                slot: None,
19578            };
19579            assert_eq!(
19580                c.endpoint(),
19581                Some(endpoint),
19582                "WitContract::endpoint must return :contratos :endpoint \
19583                 verbatim (got {:?}, expected Some({endpoint:?}))",
19584                c.endpoint(),
19585            );
19586            assert_eq!(
19587                c.endpoint(),
19588                c.endpoint.as_deref(),
19589                "WitContract::endpoint must byte-equal the .endpoint \
19590                 field's `.as_deref()` projection",
19591            );
19592        }
19593    }
19594
19595    #[test]
19596    fn wit_contract_endpoint_none_when_field_is_none() {
19597        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
19598        // payload-carrier accessor pin: when the typed slot is absent —
19599        // the canonical shape under a non-HTTP `:wit` world per the
19600        // [`WitContract::target`]-enforced shape ↔ target partition
19601        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
19602        // carries `:slot`, [`WitTarget::Capability`] carries none) —
19603        // [`WitContract::endpoint`] must return `None`. Pins against a
19604        // future silent detour that projected the absent slot to a
19605        // `Some("")` empty-string default (the canonical `Option<String>`
19606        // → `String` collapse footgun the sibling M2
19607        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19608        // emptiness predicates already guard on the peer M2 typed-slot
19609        // surfaces), a `Some("None")` stringified-None round-trip, or a
19610        // `Some` arm whose contents were derived from a sibling slot (an
19611        // accidental fallback to the `:subject` / `:slot` payload that
19612        // read the pub-sub / store payload into the endpoint axis).
19613        // Three contracts sweep the accept-set every non-HTTP `:wit`
19614        // world lands on — pub-sub NATS, key/value, and payload-less
19615        // capability.
19616        for (wit, subject, slot) in [
19617            ("nats:pub-sub", Some("orders.paid"), None),
19618            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
19619            ("wasi:cli/environment", None, None),
19620        ] {
19621            let c = WitContract {
19622                de: "cart".into(),
19623                para: "downstream".into(),
19624                wit: wit.into(),
19625                endpoint: None,
19626                subject: subject.map(str::to_string),
19627                slot: slot.map(str::to_string),
19628            };
19629            assert!(
19630                c.endpoint().is_none(),
19631                "WitContract::endpoint must return None when the typed \
19632                 slot is absent under :wit {wit:?} (got {:?})",
19633                c.endpoint(),
19634            );
19635            assert_eq!(
19636                c.endpoint(),
19637                c.endpoint.as_deref(),
19638                "WitContract::endpoint must byte-equal the .endpoint \
19639                 field's `.as_deref()` projection in the absent arm",
19640            );
19641        }
19642    }
19643
19644    #[test]
19645    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
19646        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
19647        // an `Option<&str>` whose `Some` arm borrows from the typed
19648        // slot's own [`String`] storage — same-address invariant with
19649        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
19650        // detour that allocated a fresh `String`
19651        // (`self.endpoint.clone().map(...)` in the body would type-check
19652        // but silently drop the borrow, and every downstream consumer
19653        // that assumed the returned slice outlives `&self` would break
19654        // on a stale-reference use-after-free — the [`WitContract::target`]
19655        // Http-arm payload extraction rebinds the returned `Option<&str>`
19656        // through `.ok_or_else(...)` and threads the `&str` payload into
19657        // [`WitTarget::Http { endpoint: &'a str }`], the
19658        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
19659        // [`ContratoIdentity`] dedup key threads the returned
19660        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
19661        // from the WitContract's own storage and each would silently
19662        // misbehave if this accessor produced a detached copy). Peer of
19663        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
19664        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
19665        // shaped optional-scalar axes — first extension of the
19666        // `Option<&str>` borrow-not-copy discipline onto the
19667        // per-`:contratos` HTTP-shaped payload-carrier axis.
19668        let c = WitContract {
19669            de: "cart".into(),
19670            para: "catalog".into(),
19671            wit: "wasi:http/proxy".into(),
19672            endpoint: Some("/lookup".into()),
19673            subject: None,
19674            slot: None,
19675        };
19676        let ep = c.endpoint().expect("Some arm");
19677        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
19678        assert_eq!(
19679            ep.as_ptr(),
19680            storage_slice.as_ptr(),
19681            "WitContract::endpoint must borrow from the .endpoint \
19682             String's backing storage — a fresh allocation here means \
19683             the accessor no longer names the substrate-primitive typed \
19684             dispatch and every downstream consumer would silently \
19685             carry a detached copy",
19686        );
19687        assert_eq!(
19688            ep.len(),
19689            storage_slice.len(),
19690            "WitContract::endpoint and .endpoint.as_deref() must byte-\
19691             equal in length as well as in address",
19692        );
19693    }
19694
19695    #[test]
19696    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
19697        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
19698        // pin: [`WitContract::subject`] must return the `:contratos
19699        // :subject` field byte-for-byte, borrowed from the typed slot's
19700        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
19701        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
19702        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
19703        // optional-scalar axis — same "the substrate-primitive accessor
19704        // must byte-equal the raw field access verbatim across every
19705        // author-declared value" discipline extended to the pub-sub arm.
19706        // Pins against a future silent detour that re-canonicalized the
19707        // subject (an accidental `.to_lowercase()` normalization that
19708        // didn't reach the peer field-access site at the dedup key, a
19709        // per-CR fully-qualified prefix rewrite the operator authors on
19710        // one consumer without the other, or an M4 typed-subject-template
19711        // `Display` re-canonicalization that silently drifted the printer
19712        // output from the source `caixa.lisp`). Four values sweep the
19713        // NATS accept-set every pub-sub author-declared subject lands on
19714        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
19715        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
19716            let c = WitContract {
19717                de: "cart".into(),
19718                para: "notifier".into(),
19719                wit: "nats:pub-sub".into(),
19720                endpoint: None,
19721                subject: Some(subject.into()),
19722                slot: None,
19723            };
19724            assert_eq!(
19725                c.subject(),
19726                Some(subject),
19727                "WitContract::subject must return :contratos :subject \
19728                 verbatim (got {:?}, expected Some({subject:?}))",
19729                c.subject(),
19730            );
19731            assert_eq!(
19732                c.subject(),
19733                c.subject.as_deref(),
19734                "WitContract::subject must byte-equal the .subject \
19735                 field's `.as_deref()` projection",
19736            );
19737        }
19738    }
19739
19740    #[test]
19741    fn wit_contract_subject_none_when_field_is_none() {
19742        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
19743        // shaped payload-carrier accessor pin: when the typed slot is
19744        // absent — the canonical shape under a non-pub-sub `:wit` world
19745        // per the [`WitContract::target`]-enforced shape ↔ target
19746        // partition ([`WitTarget::Http`] carries `:endpoint`,
19747        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
19748        // carries none) — [`WitContract::subject`] must return `None`.
19749        // Pins against a future silent detour that projected the absent
19750        // slot to a `Some("")` empty-string default (the canonical
19751        // `Option<String>` → `String` collapse footgun the sibling M2
19752        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19753        // emptiness predicates already guard on the peer M2 typed-slot
19754        // surfaces), a `Some("None")` stringified-None round-trip, or a
19755        // `Some` arm whose contents were derived from a sibling slot (an
19756        // accidental fallback to the `:endpoint` / `:slot` payload that
19757        // read the HTTP / store payload into the subject axis). Three
19758        // contracts sweep the accept-set every non-pub-sub `:wit` world
19759        // lands on — HTTP proxy, key/value store, and payload-less
19760        // capability.
19761        for (wit, endpoint, slot) in [
19762            ("wasi:http/proxy", Some("/lookup"), None),
19763            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
19764            ("wasi:cli/environment", None, None),
19765        ] {
19766            let c = WitContract {
19767                de: "cart".into(),
19768                para: "downstream".into(),
19769                wit: wit.into(),
19770                endpoint: endpoint.map(str::to_string),
19771                subject: None,
19772                slot: slot.map(str::to_string),
19773            };
19774            assert!(
19775                c.subject().is_none(),
19776                "WitContract::subject must return None when the typed \
19777                 slot is absent under :wit {wit:?} (got {:?})",
19778                c.subject(),
19779            );
19780            assert_eq!(
19781                c.subject(),
19782                c.subject.as_deref(),
19783                "WitContract::subject must byte-equal the .subject \
19784                 field's `.as_deref()` projection in the absent arm",
19785            );
19786        }
19787    }
19788
19789    #[test]
19790    fn wit_contract_subject_borrows_from_subject_storage() {
19791        // The borrow-not-copy pin: [`WitContract::subject`] must return
19792        // an `Option<&str>` whose `Some` arm borrows from the typed
19793        // slot's own [`String`] storage — same-address invariant with
19794        // `c.subject.as_deref().unwrap()`. Pins against a future silent
19795        // detour that allocated a fresh `String`
19796        // (`self.subject.clone().map(...)` in the body would type-check
19797        // but silently drop the borrow, and every downstream consumer
19798        // that assumed the returned slice outlives `&self` would break
19799        // on a stale-reference use-after-free — the [`WitContract::target`]
19800        // PubSub-arm payload extraction rebinds the returned
19801        // `Option<&str>` through `.ok_or_else(...)` and threads the
19802        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
19803        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19804        // [`ContratoIdentity`] dedup key threads the returned
19805        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
19806        // from the WitContract's own storage and each would silently
19807        // misbehave if this accessor produced a detached copy). Peer of
19808        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
19809        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
19810        // shaped optional-scalar axis — second extension of the
19811        // `Option<&str>` borrow-not-copy discipline onto the
19812        // per-`:contratos` payload-carrier family, this time on the
19813        // pub-sub arm.
19814        let c = WitContract {
19815            de: "cart".into(),
19816            para: "notifier".into(),
19817            wit: "nats:pub-sub".into(),
19818            endpoint: None,
19819            subject: Some("orders.paid".into()),
19820            slot: None,
19821        };
19822        let sub = c.subject().expect("Some arm");
19823        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
19824        assert_eq!(
19825            sub.as_ptr(),
19826            storage_slice.as_ptr(),
19827            "WitContract::subject must borrow from the .subject \
19828             String's backing storage — a fresh allocation here means \
19829             the accessor no longer names the substrate-primitive typed \
19830             dispatch and every downstream consumer would silently \
19831             carry a detached copy",
19832        );
19833        assert_eq!(
19834            sub.len(),
19835            storage_slice.len(),
19836            "WitContract::subject and .subject.as_deref() must byte-\
19837             equal in length as well as in address",
19838        );
19839    }
19840
19841    #[test]
19842    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
19843        // The canonical per-`:contratos` key/value-store-shaped
19844        // `:slot`-scalar pin: [`WitContract::slot`] must return the
19845        // `:contratos :slot` field byte-for-byte, borrowed from the
19846        // typed slot's own `Option<String>` storage. Peer of the
19847        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
19848        // [`WitContract::subject`] (90de675) accessor pins on the M3
19849        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
19850        // optional-scalar axis — same "the substrate-primitive
19851        // accessor must byte-equal the raw field access verbatim
19852        // across every author-declared value" discipline extended to
19853        // the store arm. Pins against a future silent detour that
19854        // re-canonicalized the slot template (an accidental
19855        // `.to_lowercase()` bucket-prefix normalization that didn't
19856        // reach the peer field-access site at the dedup key, a per-CR
19857        // fully-qualified prefix rewrite the operator authors on one
19858        // consumer without the other, or an M4 typed-key-template
19859        // `Display` re-canonicalization that silently drifted the
19860        // printer output from the source `caixa.lisp`). Four values
19861        // sweep the wasi:keyvalue accept-set every store-shaped
19862        // author-declared slot lands on (flat bucket, single-param
19863        // template, multi-param template, nested-hierarchy template).
19864        for slot in [
19865            "sessions",
19866            "carts/{cart_id}",
19867            "orders/{tenant}/{order_id}",
19868            "cache/tenant-a/orders/{id}",
19869        ] {
19870            let c = WitContract {
19871                de: "cart".into(),
19872                para: "kv".into(),
19873                wit: "wasi:keyvalue/store".into(),
19874                endpoint: None,
19875                subject: None,
19876                slot: Some(slot.into()),
19877            };
19878            assert_eq!(
19879                c.slot(),
19880                Some(slot),
19881                "WitContract::slot must return :contratos :slot \
19882                 verbatim (got {:?}, expected Some({slot:?}))",
19883                c.slot(),
19884            );
19885            assert_eq!(
19886                c.slot(),
19887                c.slot.as_deref(),
19888                "WitContract::slot must byte-equal the .slot field's \
19889                 `.as_deref()` projection",
19890            );
19891        }
19892    }
19893
19894    #[test]
19895    fn wit_contract_slot_none_when_field_is_none() {
19896        // The absent-`:slot` arm of the per-`:contratos` store-shaped
19897        // payload-carrier accessor pin: when the typed slot is absent —
19898        // the canonical shape under a non-store `:wit` world per the
19899        // [`WitContract::target`]-enforced shape ↔ target partition
19900        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
19901        // carries `:subject`, [`WitTarget::Capability`] carries none) —
19902        // [`WitContract::slot`] must return `None`. Pins against a
19903        // future silent detour that projected the absent slot to a
19904        // `Some("")` empty-string default (the canonical
19905        // `Option<String>` → `String` collapse footgun the sibling M2
19906        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19907        // emptiness predicates already guard on the peer M2 typed-slot
19908        // surfaces), a `Some("None")` stringified-None round-trip, or
19909        // a `Some` arm whose contents were derived from a sibling
19910        // slot (an accidental fallback to the `:endpoint` / `:subject`
19911        // payload that read the HTTP / pub-sub payload into the store
19912        // axis). Three contracts sweep the accept-set every non-store
19913        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
19914        // payload-less capability.
19915        for (wit, endpoint, subject) in [
19916            ("wasi:http/proxy", Some("/lookup"), None),
19917            ("nats:pub-sub", None, Some("orders.paid")),
19918            ("wasi:cli/environment", None, None),
19919        ] {
19920            let c = WitContract {
19921                de: "cart".into(),
19922                para: "downstream".into(),
19923                wit: wit.into(),
19924                endpoint: endpoint.map(str::to_string),
19925                subject: subject.map(str::to_string),
19926                slot: None,
19927            };
19928            assert!(
19929                c.slot().is_none(),
19930                "WitContract::slot must return None when the typed \
19931                 slot is absent under :wit {wit:?} (got {:?})",
19932                c.slot(),
19933            );
19934            assert_eq!(
19935                c.slot(),
19936                c.slot.as_deref(),
19937                "WitContract::slot must byte-equal the .slot field's \
19938                 `.as_deref()` projection in the absent arm",
19939            );
19940        }
19941    }
19942
19943    #[test]
19944    fn wit_contract_slot_borrows_from_slot_storage() {
19945        // The borrow-not-copy pin: [`WitContract::slot`] must return
19946        // an `Option<&str>` whose `Some` arm borrows from the typed
19947        // slot's own [`String`] storage — same-address invariant with
19948        // `c.slot.as_deref().unwrap()`. Pins against a future silent
19949        // detour that allocated a fresh `String`
19950        // (`self.slot.clone().map(...)` in the body would type-check
19951        // but silently drop the borrow, and every downstream consumer
19952        // that assumed the returned slice outlives `&self` would
19953        // break on a stale-reference use-after-free — the
19954        // [`WitContract::target`] Store-arm payload extraction rebinds
19955        // the returned `Option<&str>` through `.ok_or_else(...)` and
19956        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
19957        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19958        // [`ContratoIdentity`] dedup key threads the returned
19959        // `Option<&str>` into the six-tuple's store arm — each borrow
19960        // from the WitContract's own storage and each would silently
19961        // misbehave if this accessor produced a detached copy). Peer
19962        // of the sibling per-`:contratos` [`WitContract::endpoint`]
19963        // (7020470) / [`WitContract::subject`] (90de675)
19964        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
19965        // shaped optional-scalar axis — third and final extension of
19966        // the `Option<&str>` borrow-not-copy discipline onto the
19967        // per-`:contratos` payload-carrier family, this time on the
19968        // store arm.
19969        let c = WitContract {
19970            de: "cart".into(),
19971            para: "kv".into(),
19972            wit: "wasi:keyvalue/store".into(),
19973            endpoint: None,
19974            subject: None,
19975            slot: Some("carts/{cart_id}".into()),
19976        };
19977        let slot = c.slot().expect("Some arm");
19978        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
19979        assert_eq!(
19980            slot.as_ptr(),
19981            storage_slice.as_ptr(),
19982            "WitContract::slot must borrow from the .slot String's \
19983             backing storage — a fresh allocation here means the \
19984             accessor no longer names the substrate-primitive typed \
19985             dispatch and every downstream consumer would silently \
19986             carry a detached copy",
19987        );
19988        assert_eq!(
19989            slot.len(),
19990            storage_slice.len(),
19991            "WitContract::slot and .slot.as_deref() must byte-equal \
19992             in length as well as in address",
19993        );
19994    }
19995
19996    #[test]
19997    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
19998        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
19999        // [`Membro::nome`] must return the `:membros :caixa` field
20000        // byte-for-byte, borrowed from the typed slot's own [`String`]
20001        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
20002        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
20003        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
20004        // slot-atom scalar-value axes — same "the substrate-primitive
20005        // accessor must byte-equal the raw field access verbatim across
20006        // every author-declared value" discipline extended to the
20007        // per-`:membros` member-identity arm. Pins against a future
20008        // silent detour that re-normalized the member identity (an
20009        // accidental `.to_lowercase()` — every `:membros :caixa` is
20010        // validated as a DNS-1123 label upstream via
20011        // [`validate_membro_caixa`], so any re-normalization is
20012        // redundant + a drift surface between the validator and the
20013        // accessor), a namespace-prefix rewrite (an accidental
20014        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
20015        // rewrite that didn't land on the peer axes), or a per-cluster
20016        // alias stamp the operator authors on one consumer without the
20017        // other. Four values sweep the accept-set the DNS-1123 gate
20018        // upstream admits (short single-word / dashed / v-suffixed
20019        // member names).
20020        for name in ["cart", "checkout", "catalog", "orders-v2"] {
20021            let m = Membro {
20022                caixa: name.into(),
20023                versao: "^0.1".into(),
20024            };
20025            assert_eq!(
20026                m.nome(),
20027                name,
20028                "Membro::nome must return :membros :caixa verbatim \
20029                 (got {:?}, expected {name:?})",
20030                m.nome(),
20031            );
20032            assert_eq!(
20033                m.nome(),
20034                m.caixa.as_str(),
20035                "Membro::nome must byte-equal the .caixa field access",
20036            );
20037        }
20038    }
20039
20040    #[test]
20041    fn membro_nome_borrows_from_caixa_storage() {
20042        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
20043        // slice that borrows from the typed slot's own [`String`]
20044        // storage — same-address invariant with `m.caixa.as_str()`. Pins
20045        // against a future silent detour that allocated a fresh `String`
20046        // (`self.caixa.clone()` in the body would type-check but
20047        // silently drop the borrow, and every downstream consumer that
20048        // assumed the returned slice outlives `&self` would break on a
20049        // stale-reference use-after-free — the `HashSet<&str>` collector
20050        // at [`AplicacaoSpec::validate`]'s `names` seed, the
20051        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
20052        // [`AplicacaoSpec::detect_sync_cycles`], the
20053        // [`crate::render::insert_first_seen`] dedup key at
20054        // [`AplicacaoSpec::validate_membros`] — each borrow from the
20055        // Membro's own storage and each would silently misbehave if
20056        // this accessor produced a detached copy). Peer of the sibling
20057        // per-`:contratos` [`WitContract::source`] /
20058        // [`WitContract::destination`] and per-`:entrada`
20059        // [`Entrada::destination`] borrow-invariant pins on the mesh-
20060        // slot-atom scalar-value axes.
20061        let m = Membro {
20062            caixa: "checkout".into(),
20063            versao: "^0.1".into(),
20064        };
20065        let name = m.nome();
20066        let caixa_slice = m.caixa.as_str();
20067        assert_eq!(
20068            name.as_ptr(),
20069            caixa_slice.as_ptr(),
20070            "Membro::nome must borrow from the .caixa String's backing \
20071             storage — a fresh allocation here means the accessor no \
20072             longer names the substrate-primitive typed dispatch and \
20073             every downstream consumer would silently carry a detached \
20074             copy",
20075        );
20076        assert_eq!(
20077            name.len(),
20078            caixa_slice.len(),
20079            "Membro::nome and .caixa.as_str() must byte-equal in length \
20080             as well as in address",
20081        );
20082    }
20083
20084    #[test]
20085    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
20086        // The canonical per-`:membros` member-`:versao`-scalar pin:
20087        // [`Membro::versao_requirement`] must return the
20088        // `:membros :versao` field byte-for-byte, borrowed from the typed
20089        // slot's own [`String`] storage. Sibling of the peer
20090        // `membro_nome_returns_caixa_byte_equal_across_permutations`
20091        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
20092        // — same "the substrate-primitive accessor must byte-equal the
20093        // raw field access verbatim across every author-declared value"
20094        // discipline extended to the per-`:membros` member-`:versao`
20095        // requirement-string arm. Pins against a future silent detour
20096        // that re-canonicalized the requirement (an accidental
20097        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
20098        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
20099        // drifted the printer output away from the source `caixa.lisp`,
20100        // an accidental whitespace trim on `"^ 0.1"` that no consumer
20101        // ever produced from the field-access side, an accidental
20102        // per-cluster lacre-projected concrete-version rewrite that
20103        // didn't land on the peer field-access sites). Five values sweep
20104        // the accept-set the shared
20105        // [`crate::render::require_valid_versao_requirement`] gate
20106        // admits (caret / tilde / exact / wildcard / bare-major).
20107        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
20108            let m = Membro {
20109                caixa: "cart".into(),
20110                versao: req.into(),
20111            };
20112            assert_eq!(
20113                m.versao_requirement(),
20114                req,
20115                "Membro::versao_requirement must return :membros :versao \
20116                 verbatim (got {:?}, expected {req:?})",
20117                m.versao_requirement(),
20118            );
20119            assert_eq!(
20120                m.versao_requirement(),
20121                m.versao.as_str(),
20122                "Membro::versao_requirement must byte-equal the .versao \
20123                 field access",
20124            );
20125        }
20126    }
20127
20128    #[test]
20129    fn membro_versao_requirement_borrows_from_versao_storage() {
20130        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
20131        // return a `&str` slice that borrows from the typed slot's own
20132        // [`String`] storage — same-address invariant with
20133        // `m.versao.as_str()`. Pins against a future silent detour that
20134        // allocated a fresh `String` (`self.versao.clone()` in the body
20135        // would type-check but silently drop the borrow, and every
20136        // downstream consumer that assumed the returned slice outlives
20137        // `&self` would break on a stale-reference use-after-free). Peer
20138        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
20139        // per-`:contratos` [`WitContract::source`] /
20140        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
20141        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
20142        // the mesh-slot-atom scalar-value axes.
20143        let m = Membro {
20144            caixa: "checkout".into(),
20145            versao: "^0.1".into(),
20146        };
20147        let req = m.versao_requirement();
20148        let versao_slice = m.versao.as_str();
20149        assert_eq!(
20150            req.as_ptr(),
20151            versao_slice.as_ptr(),
20152            "Membro::versao_requirement must borrow from the .versao \
20153             String's backing storage — a fresh allocation here means \
20154             the accessor no longer names the substrate-primitive typed \
20155             dispatch and every downstream consumer would silently carry \
20156             a detached copy",
20157        );
20158        assert_eq!(
20159            req.len(),
20160            versao_slice.len(),
20161            "Membro::versao_requirement and .versao.as_str() must byte-\
20162             equal in length as well as in address",
20163        );
20164    }
20165
20166    #[test]
20167    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
20168        // Sibling-pair invariant pin composing both per-`:membros`
20169        // substrate-primitive typed dispatches — [`Membro::nome`]
20170        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
20171        // `(nome(), versao_requirement())` call shape every renderer
20172        // that fans on per-member identity + version pin keys off. The
20173        // invariant, evaluated per-member:
20174        //
20175        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
20176        //
20177        // Closes the last unlifted per-`:membros` scalar axis — every
20178        // downstream consumer that reads the pair now routes through
20179        // exactly two typed dispatches on the substrate primitive, not
20180        // one typed + one open-coded field access. A future refactor
20181        // that silently split either accessor's projection (an
20182        // accidental `nome()` namespace-prefix rewrite that didn't
20183        // reach the peer, an accidental `versao_requirement()` lacre-
20184        // projected concrete-version rewrite that didn't land on the
20185        // `nome()` peer) surfaces at caixa-core build time. Peer of the
20186        // sibling per-`:entrada` `(hostname(), destination())` and
20187        // per-`:contratos` `(source(), destination())` pair invariants
20188        // on the mesh-slot-atom scalar-value axes.
20189        for (caixa, versao) in [
20190            ("cart", "^0.1"),
20191            ("checkout", "~0.1.2"),
20192            ("catalog", "0.1.0"),
20193            ("orders-v2", "*"),
20194        ] {
20195            let m = Membro {
20196                caixa: caixa.into(),
20197                versao: versao.into(),
20198            };
20199            assert_eq!(
20200                (m.nome(), m.versao_requirement()),
20201                (m.caixa.as_str(), m.versao.as_str()),
20202                "(Membro::nome, Membro::versao_requirement) must project \
20203                 (.caixa, .versao) verbatim across every author-declared \
20204                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
20205                m.nome(),
20206                m.versao_requirement(),
20207            );
20208        }
20209    }
20210
20211    #[test]
20212    fn validate_membros_empty_gate_routes_through_nome_accessor() {
20213        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
20214        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
20215        // not the raw `.caixa` field access. Structurally: setting
20216        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
20217        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
20218        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
20219        // (i.e. the empty string) — so the emptiness predicate the
20220        // refusal arm reaches under is the accessor-projected value,
20221        // not a peer field that would silently drift under a future
20222        // accessor-side rewrite.
20223        //
20224        // Pins against a future silent detour that (a) re-derived the
20225        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
20226        // instead of `self.nome().is_empty()`, silently disagreeing with
20227        // every peer consumer (the `validate_membro_caixa(m.nome())`
20228        // call one line below, the dedup-key `insert_first_seen(&mut
20229        // seen, m.nome(), …)` two lines below, the emit-side per-
20230        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
20231        // (b) accessor-side introduced a per-tenant alias arm the
20232        // caller was unaware of, silently rewriting an author-declared
20233        // `:caixa "checkout"` to `""` — the raw-field-access gate
20234        // would fail-open while the accessor-routed peer consumers
20235        // would fail-closed, splitting the diagnostic from the actual
20236        // failure surface.
20237        //
20238        // Peer of the sibling
20239        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
20240        // (c0110f1) composition pin — same "the shape-gate predicate
20241        // must route through the substrate-primitive typed dispatch"
20242        // discipline extended onto the per-`:membros` empty-`:caixa`
20243        // refusal-arm axis. Closes the last unlifted `.caixa` production-
20244        // code read site on `Membro` — after this converge every
20245        // caixa-core `.caixa` field access outside the accessor's own
20246        // body is either a test-side field-setter (in-module tests
20247        // constructing invalid-shape inputs) or a doc-comment reference.
20248        let mut s = three_member_spec();
20249        s.membros[1].caixa = String::new();
20250        assert!(
20251            s.membros[1].nome().is_empty(),
20252            "Membro::nome must byte-equal the .caixa field access — an \
20253             accessor-side detour that no longer projects the raw field \
20254             would silently split this drift-detection test from the \
20255             validate() refusal arm",
20256        );
20257        assert_eq!(
20258            s.membros[1].nome(),
20259            s.membros[1].caixa.as_str(),
20260            "Membro::nome and .caixa.as_str() must byte-equal on an \
20261             empty-`:caixa` entry — the emptiness gate keys off the \
20262             accessor by construction",
20263        );
20264        assert_eq!(
20265            s.validate().unwrap_err(),
20266            AplicacaoError::MembroCaixaEmpty,
20267            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
20268             on an entry whose accessor-projected `nome()` is empty",
20269        );
20270    }
20271
20272    #[test]
20273    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
20274        // The canonical per-`:placement` Akka-cluster-sharding
20275        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
20276        // the `:placement :shard-key` field byte-for-byte, borrowed
20277        // from the typed slot's own `Option<String>` storage. Peer of
20278        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
20279        // per-`:contratos` [`WitContract::source`] /
20280        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
20281        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
20282        // slot-atom scalar-value axes — same "the substrate-primitive
20283        // accessor must byte-equal the raw field access verbatim across
20284        // every author-declared value" discipline extended to the
20285        // per-`:placement` Akka-cluster-sharding key extractor arm.
20286        // Pins against a future silent detour that re-normalized the
20287        // key (an accidental `.to_lowercase()` — every non-empty
20288        // `:shard-key` is validated as a printable-ASCII single-token
20289        // reference upstream via [`validate_placement_shard_key`], so
20290        // any re-normalization is redundant + a drift surface between
20291        // the validator and the accessor), a per-cluster alias rewrite
20292        // the operator authors on one consumer without the other, or an
20293        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
20294        // that didn't land on the peer field-access sites. Four values
20295        // sweep the accept-set the shape gate admits — bare identifier,
20296        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
20297        // the four canonical Akka-style entity-id extractor shapes the
20298        // future M4 cluster-sharding reconciler hashes.
20299        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
20300            let p = Placement {
20301                estrategia: PlacementStrategy::Sharded,
20302                clusters: vec!["rio".into()],
20303                affinity: None,
20304                shard_key: Some(key.into()),
20305            };
20306            assert_eq!(
20307                p.shard_key(),
20308                Some(key),
20309                "Placement::shard_key must return :placement :shard-key \
20310                 verbatim (got {:?}, expected Some({key:?}))",
20311                p.shard_key(),
20312            );
20313            assert_eq!(
20314                p.shard_key(),
20315                p.shard_key.as_deref(),
20316                "Placement::shard_key must byte-equal the .shard_key \
20317                 field's `.as_deref()` projection",
20318            );
20319        }
20320    }
20321
20322    #[test]
20323    fn placement_shard_key_none_when_field_is_none() {
20324        // The absent-`:shard-key` arm of the per-`:placement`
20325        // Akka-cluster-sharding accessor pin: when the typed slot is
20326        // absent — the canonical shape under `:estrategia Replicated` /
20327        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
20328        // enforced `shard_key.is_some() == matches!(estrategia,
20329        // Sharded)` partition — [`Placement::shard_key`] must return
20330        // `None`. Pins against a future silent detour that projected
20331        // the absent slot to a `Some("")` empty-string default (the
20332        // canonical `Option<String>` → `String` collapse footgun the
20333        // sibling M2 [`crate::LimitsSpec::is_empty`] /
20334        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
20335        // already guard on the peer M2 typed-slot surfaces), a
20336        // `Some("None")` stringified-None round-trip, or a `Some` arm
20337        // whose contents were derived from a sibling slot (an
20338        // accidental fallback to `estrategia.as_str()` that read the
20339        // strategy discriminator into the key axis). Two placements
20340        // sweep the accept-set every `validate`-passing non-`Sharded`
20341        // shape lands on — `Replicated` (Erlang/OTP distributed-app
20342        // takeover) and `SingleNode` (single-node hosting).
20343        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
20344            let p = Placement {
20345                estrategia,
20346                clusters: vec!["rio".into()],
20347                affinity: None,
20348                shard_key: None,
20349            };
20350            assert!(
20351                p.shard_key().is_none(),
20352                "Placement::shard_key must return None when the typed \
20353                 slot is absent under :estrategia {estrategia:?} (got {:?})",
20354                p.shard_key(),
20355            );
20356            assert_eq!(
20357                p.shard_key(),
20358                p.shard_key.as_deref(),
20359                "Placement::shard_key must byte-equal the .shard_key \
20360                 field's `.as_deref()` projection in the absent arm",
20361            );
20362        }
20363    }
20364
20365    #[test]
20366    fn placement_shard_key_borrows_from_shard_key_storage() {
20367        // The borrow-not-copy pin: [`Placement::shard_key`] must return
20368        // an `Option<&str>` whose `Some` arm borrows from the typed
20369        // slot's own [`String`] storage — same-address invariant with
20370        // `p.shard_key.as_deref().unwrap()`. Pins against a future
20371        // silent detour that allocated a fresh `String`
20372        // (`self.shard_key.clone().map(...)` in the body would type-
20373        // check but silently drop the borrow, and every downstream
20374        // consumer that assumed the returned slice outlives `&self`
20375        // would break on a stale-reference use-after-free — the
20376        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
20377        // gate's `Some(k)`-bound match arm reads `k: &str` under the
20378        // accessor's return type and would silently misbehave if this
20379        // accessor produced a detached copy). Peer of the sibling
20380        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
20381        // [`WitContract::source`] / [`WitContract::destination`]
20382        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
20383        // (6db982c) borrow-invariant pins on the mesh-slot-atom
20384        // scalar-value axes — first extension of the discipline onto
20385        // an `Option<String>`-shaped optional-scalar axis.
20386        let p = Placement {
20387            estrategia: PlacementStrategy::Sharded,
20388            clusters: vec!["rio".into()],
20389            affinity: None,
20390            shard_key: Some("tenantId".into()),
20391        };
20392        let key = p.shard_key().expect("Some arm");
20393        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
20394        assert_eq!(
20395            key.as_ptr(),
20396            storage_slice.as_ptr(),
20397            "Placement::shard_key must borrow from the .shard_key \
20398             String's backing storage — a fresh allocation here means \
20399             the accessor no longer names the substrate-primitive typed \
20400             dispatch and every downstream consumer would silently \
20401             carry a detached copy",
20402        );
20403        assert_eq!(
20404            key.len(),
20405            storage_slice.len(),
20406            "Placement::shard_key and .shard_key.as_deref() must byte-\
20407             equal in length as well as in address",
20408        );
20409    }
20410
20411    #[test]
20412    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
20413        // The canonical per-`:placement` M3-Adaptive-compression-hint
20414        // scalar pin: [`Placement::affinity`] must return the
20415        // `:placement :affinity` field byte-for-byte, borrowed from the
20416        // typed slot's own `Option<String>` storage. Peer of the sibling
20417        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
20418        // pin on the sibling `Option<&str>` optional-scalar axis — same
20419        // "the substrate-primitive accessor must byte-equal the raw
20420        // field access verbatim across every author-declared value"
20421        // discipline extended to the peer per-`:placement` M3-Adaptive-
20422        // compression-hint arm. Pins against a future silent detour
20423        // that re-normalized the hint (an accidental `.to_lowercase()`
20424        // — every `:affinity` is already validated as a DNS-1123 label
20425        // upstream via [`validate_placement_affinity`], so any re-
20426        // normalization is redundant + a drift surface between the
20427        // validator and the accessor), a per-cluster alias rewrite the
20428        // operator authors on one consumer without the other, or an
20429        // accidental hint-family collapse (`low-latency` → `latency`
20430        // that dropped the qualifier prefix). Four values sweep the
20431        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
20432        // canonical adaptive-compression-weight biases the future M4
20433        // placement engine reads.
20434        for hint in [
20435            "data-locality",
20436            "low-latency",
20437            "high-throughput",
20438            "cost-optimized",
20439        ] {
20440            let p = Placement {
20441                estrategia: PlacementStrategy::Replicated,
20442                clusters: vec!["rio".into()],
20443                affinity: Some(hint.into()),
20444                shard_key: None,
20445            };
20446            assert_eq!(
20447                p.affinity(),
20448                Some(hint),
20449                "Placement::affinity must return :placement :affinity \
20450                 verbatim (got {:?}, expected Some({hint:?}))",
20451                p.affinity(),
20452            );
20453            assert_eq!(
20454                p.affinity(),
20455                p.affinity.as_deref(),
20456                "Placement::affinity must byte-equal the .affinity \
20457                 field's `.as_deref()` projection",
20458            );
20459        }
20460    }
20461
20462    #[test]
20463    fn placement_affinity_none_when_field_is_none() {
20464        // The absent-`:affinity` arm of the per-`:placement`
20465        // M3-Adaptive-compression-hint accessor pin: when the typed
20466        // slot is absent — the canonical shape of an Aplicacao that
20467        // leaves the compression weighting up to the placement engine's
20468        // cluster-default arm — [`Placement::affinity`] must return
20469        // `None`. Pins against a future silent detour that projected
20470        // the absent slot to a `Some("")` empty-string default (the
20471        // canonical `Option<String>` → `String` collapse footgun the
20472        // sibling M2 [`crate::LimitsSpec::is_empty`] /
20473        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
20474        // already guard on the peer M2 typed-slot surfaces), a
20475        // `Some("None")` stringified-None round-trip, a `Some` arm
20476        // whose contents were derived from a sibling slot (an
20477        // accidental fallback to `estrategia.as_str()` that read the
20478        // strategy discriminator into the hint axis), or a
20479        // `Some("default")` implicit-default that would silently biases
20480        // the routing without the author having written one. Three
20481        // placements sweep the accept-set every `validate`-passing
20482        // `:affinity None` shape lands on — one per PlacementStrategy
20483        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
20484        // with a shard-key), since `:affinity` is orthogonal to
20485        // `:estrategia` in the typed grammar.
20486        for (estrategia, shard_key) in [
20487            (PlacementStrategy::SingleNode, None),
20488            (PlacementStrategy::Replicated, None),
20489            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
20490        ] {
20491            let p = Placement {
20492                estrategia,
20493                clusters: vec!["rio".into()],
20494                affinity: None,
20495                shard_key,
20496            };
20497            assert!(
20498                p.affinity().is_none(),
20499                "Placement::affinity must return None when the typed \
20500                 slot is absent under :estrategia {estrategia:?} (got {:?})",
20501                p.affinity(),
20502            );
20503            assert_eq!(
20504                p.affinity(),
20505                p.affinity.as_deref(),
20506                "Placement::affinity must byte-equal the .affinity \
20507                 field's `.as_deref()` projection in the absent arm",
20508            );
20509        }
20510    }
20511
20512    #[test]
20513    fn placement_affinity_borrows_from_affinity_storage() {
20514        // The borrow-not-copy pin: [`Placement::affinity`] must return
20515        // an `Option<&str>` whose `Some` arm borrows from the typed
20516        // slot's own [`String`] storage — same-address invariant with
20517        // `p.affinity.as_deref().unwrap()`. Pins against a future
20518        // silent detour that allocated a fresh `String`
20519        // (`self.affinity.clone().map(...)` in the body would type-
20520        // check but silently drop the borrow, and every downstream
20521        // consumer that assumed the returned slice outlives `&self`
20522        // would break on a stale-reference use-after-free — the
20523        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
20524        // gate reads the accessor's `&str` return through the
20525        // [`validate_placement_affinity`] `&str` parameter and would
20526        // silently misbehave if this accessor produced a detached
20527        // copy). Peer of the sibling per-`:placement`
20528        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
20529        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
20530        // extends the discipline onto the sibling per-`:placement`
20531        // M3-Adaptive-compression-hint arm.
20532        let p = Placement {
20533            estrategia: PlacementStrategy::Replicated,
20534            clusters: vec!["rio".into()],
20535            affinity: Some("data-locality".into()),
20536            shard_key: None,
20537        };
20538        let hint = p.affinity().expect("Some arm");
20539        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
20540        assert_eq!(
20541            hint.as_ptr(),
20542            storage_slice.as_ptr(),
20543            "Placement::affinity must borrow from the .affinity \
20544             String's backing storage — a fresh allocation here means \
20545             the accessor no longer names the substrate-primitive typed \
20546             dispatch and every downstream consumer would silently \
20547             carry a detached copy",
20548        );
20549        assert_eq!(
20550            hint.len(),
20551            storage_slice.len(),
20552            "Placement::affinity and .affinity.as_deref() must byte-\
20553             equal in length as well as in address",
20554        );
20555    }
20556
20557    #[test]
20558    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
20559        // The canonical per-`:placement` distribution-strategy-scalar
20560        // pin: [`Placement::estrategia`] must return the `:placement
20561        // :estrategia` field verbatim as a [`PlacementStrategy`],
20562        // `Copy`-projected from the typed slot's own `PlacementStrategy`
20563        // storage across every variant in the closed accept-set
20564        // (`SingleNode` — Erlang/OTP distributed-app takeover;
20565        // `Replicated` — active-active across every named cluster;
20566        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
20567        // against a future silent detour that re-derived the strategy
20568        // from a peer axis (an accidental fallback to
20569        // `if shard_key.is_some() { Sharded } else { Replicated }`
20570        // collapse that read the shard-key axis into the strategy
20571        // discriminator), a variant remap the operator authors on one
20572        // consumer without the other, or a stale-derive detour that
20573        // substituted [`PlacementStrategy::default`] when the field
20574        // held any explicit variant (which would silently collapse the
20575        // distinction between "author explicitly declared `:estrategia
20576        // Replicated`" and "author omitted the slot and inherited the
20577        // default" the future per-cluster override slot depends on).
20578        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
20579        // pin on the `Copy`-return `u16` scalar axis — same "the
20580        // substrate-primitive accessor must byte-equal the raw field
20581        // access verbatim across every author-declared value" discipline
20582        // extended onto the per-`:placement` distribution-strategy
20583        // `Copy`-composite-enum scalar axis.
20584        for estrategia in [
20585            PlacementStrategy::SingleNode,
20586            PlacementStrategy::Replicated,
20587            PlacementStrategy::Sharded,
20588        ] {
20589            let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
20590            let p = Placement {
20591                estrategia,
20592                clusters: vec!["rio".into()],
20593                affinity: None,
20594                shard_key,
20595            };
20596            assert_eq!(
20597                p.estrategia(),
20598                estrategia,
20599                "Placement::estrategia must return :placement :estrategia \
20600                 verbatim (got {:?}, expected {estrategia:?})",
20601                p.estrategia(),
20602            );
20603            assert_eq!(
20604                p.estrategia(),
20605                p.estrategia,
20606                "Placement::estrategia accessor and .estrategia field \
20607                 access must byte-equal — the accessor is the substrate-\
20608                 primitive typed dispatch every downstream distribution-\
20609                 strategy consumer must route through",
20610            );
20611        }
20612    }
20613
20614    #[test]
20615    fn validate_placement_reads_through_lifted_estrategia_accessor() {
20616        // Three-consumer coherence pin: the
20617        // [`AplicacaoSpec::validate_placement`]
20618        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
20619        // `estrategia:` field (which reads through
20620        // [`Placement::estrategia`] to name the strategy the empty
20621        // `:clusters` list was declared against), the same method's
20622        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
20623        // reads through [`Placement::estrategia`] to fan across the
20624        // shape-gate cascades), and the non-`Sharded`-arm
20625        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
20626        // `estrategia:` field (which reads through
20627        // [`Placement::estrategia`] to name the strategy the declared-
20628        // but-inert `:shard-key` was authored under) must all key off
20629        // the lifted accessor, so any future rebrand on the typed
20630        // slot's reader shape lands at exactly one place. Pins the
20631        // three-site coherence by exercising each error surface end-
20632        // to-end and asserting the surfaced `estrategia:` field byte-
20633        // equals the accessor's return. Peer of the sibling per-
20634        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
20635        // pin on the M3 mesh-slot `Copy`-return scalar axis.
20636
20637        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
20638        // whose `estrategia:` field must byte-equal the accessor's return
20639        // for every variant in the closed accept-set.
20640        for estrategia in [
20641            PlacementStrategy::SingleNode,
20642            PlacementStrategy::Replicated,
20643            PlacementStrategy::Sharded,
20644        ] {
20645            let mut spec = three_member_spec();
20646            spec.placement.estrategia = estrategia;
20647            spec.placement.clusters = Vec::new();
20648            spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
20649            let err = spec.validate().unwrap_err();
20650            match err {
20651                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
20652                    assert_eq!(
20653                        e,
20654                        spec.placement.estrategia(),
20655                        "PlacementWithoutClusters.estrategia must byte-equal \
20656                         Placement::estrategia() — the error carrier reads \
20657                         through the lifted accessor",
20658                    );
20659                }
20660                other => panic!(
20661                    "expected PlacementWithoutClusters, got {other:?} for \
20662                     estrategia={estrategia:?}"
20663                ),
20664            }
20665        }
20666
20667        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
20668        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
20669        // must byte-equal the accessor's return for both non-`Sharded`
20670        // strategies.
20671        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
20672            let mut spec = three_member_spec();
20673            spec.placement.estrategia = estrategia;
20674            spec.placement.shard_key = Some("tenantId".into());
20675            let err = spec.validate().unwrap_err();
20676            match err {
20677                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
20678                    assert_eq!(
20679                        e,
20680                        spec.placement.estrategia(),
20681                        "ShardKeyOnNonSharded.estrategia must byte-equal \
20682                         Placement::estrategia() — the non-Sharded-arm \
20683                         refusal reads through the lifted accessor",
20684                    );
20685                }
20686                other => panic!(
20687                    "expected ShardKeyOnNonSharded, got {other:?} for \
20688                     estrategia={estrategia:?}"
20689                ),
20690            }
20691        }
20692    }
20693
20694    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
20695    //
20696    // The [`Placement::clusters`] accessor lift is the second slice-return
20697    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
20698    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
20699    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
20700    // below cover (1) the accessor's byte-equal projection against the raw
20701    // field access across the empty / singleton / cohort fixtures the
20702    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
20703    // and the per-cluster validate loop fan between, and (2) the two-
20704    // consumer coherence of the paired pre-flight refusal probe and the
20705    // per-cluster validate loop routing through the accessor on both arms.
20706
20707    #[test]
20708    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
20709        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
20710        // [`Placement::clusters`] must return the `:placement :clusters`
20711        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
20712        // the same backing buffer the raw `self.clusters.as_slice()`
20713        // field access borrows from, byte-equal across every
20714        // representative fixture in the accept-set — the empty slice
20715        // (the pre-validation sentinel every
20716        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
20717        // the singleton slice (the minimal `SingleNode`-shape cohort),
20718        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
20719        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
20720        //
20721        // Pins against a future silent detour that returned
20722        // `&Vec<String>` (which would type-check but leak the storage-
20723        // side `Vec`'s grow/push/reserve surface no consumer of the
20724        // typed view reaches for), a fresh-allocated `Vec<String>` copy
20725        // (which would type-check via a coercion but silently break
20726        // every downstream caller that relied on the slice sharing the
20727        // backing buffer's identity), or an out-of-order or length-
20728        // drifted projection (which would silently split the paired
20729        // pre-flight `.is_empty()` refusal probe's input from the per-
20730        // cluster validate loop's traversal input).
20731        //
20732        // Peer of the sibling M2
20733        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20734        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20735        // `:supervisor` static-child-list axis, extended onto the M3
20736        // per-`:placement` distribution-target-list `Vec`-carry axis.
20737        let fixtures: Vec<Vec<String>> = vec![
20738            Vec::new(),
20739            vec!["rio".into()],
20740            vec!["rio".into(), "mar".into()],
20741            vec!["rio".into(), "mar".into(), "plo".into()],
20742        ];
20743        for clusters in fixtures {
20744            let p = Placement {
20745                clusters: clusters.clone(),
20746                ..Placement::default()
20747            };
20748            assert_eq!(
20749                p.clusters(),
20750                clusters.as_slice(),
20751                "Placement::clusters must return :placement :clusters \
20752                 verbatim (got {:?}, expected {:?})",
20753                p.clusters(),
20754                clusters.as_slice(),
20755            );
20756            assert_eq!(
20757                p.clusters(),
20758                p.clusters.as_slice(),
20759                "Placement::clusters accessor and .clusters.as_slice() \
20760                 field access must byte-equal — the accessor is the \
20761                 substrate-primitive typed dispatch every downstream \
20762                 cluster-pool consumer must route through",
20763            );
20764            assert_eq!(
20765                p.clusters().len(),
20766                p.clusters.len(),
20767                "Placement::clusters().len() must byte-equal \
20768                 self.clusters.len() — a length-drift would silently \
20769                 split the paired pre-flight `.is_empty()` refusal \
20770                 probe input from the per-cluster validate loop's \
20771                 traversal input",
20772            );
20773        }
20774    }
20775
20776    #[test]
20777    fn validate_placement_reads_through_lifted_clusters_accessor() {
20778        // Two-consumer coherence pin: the
20779        // [`AplicacaoSpec::validate_placement`] pre-flight
20780        // `self.placement.clusters().is_empty()` refusal probe (which
20781        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
20782        // the accessor projects the empty slice) and the per-cluster
20783        // validate loop's `for c in self.placement.clusters()`
20784        // traversal (which must reach every entry in the same order
20785        // the accessor projects, so both the per-entry value-shape
20786        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
20787        // and the duplicate-detection HashSet insert that trips
20788        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
20789        // accessor's projection) must both key off the lifted
20790        // accessor, so any future rebrand on the typed slot's reader
20791        // shape lands at exactly one place. Pins the two-site
20792        // coherence by exercising each production consumer end-to-end:
20793        // (1) the `PlacementWithoutClusters` refusal under the empty
20794        // slice, (2) the `PlacementClusterInvalid` refusal fires on
20795        // the second entry of a two-cluster cohort whose head is
20796        // valid but tail is not (which requires the loop to reach the
20797        // second entry through the accessor), and (3) the
20798        // `PlacementClusterDuplicate` refusal fires on the second
20799        // entry of a two-cluster cohort that shares a name (which
20800        // requires the loop to reach both entries — a first-entry-only
20801        // projection would silently pass since the dedup HashSet has
20802        // room for the first insert).
20803        //
20804        // Peer of the sibling M2
20805        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20806        // (bc92bce) coherence pin on the per-`:supervisor` static-
20807        // child-list axis, extended onto the M3 per-`:placement`
20808        // distribution-target-list `Vec`-carry axis.
20809
20810        // (1) Pre-flight `.is_empty()` probe: the empty slice must
20811        // trip `PlacementWithoutClusters`.
20812        let mut spec = three_member_spec();
20813        spec.placement.clusters = Vec::new();
20814        match spec.validate().unwrap_err() {
20815            AplicacaoError::PlacementWithoutClusters { .. } => {}
20816            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
20817        }
20818        assert!(
20819            spec.placement.clusters().is_empty(),
20820            "the pre-flight refusal input must be the empty slice per \
20821             the accessor's projection",
20822        );
20823
20824        // (2) Per-cluster validate loop: a two-cluster cohort with an
20825        // invalid tail entry must trip `PlacementClusterInvalid` on
20826        // the tail — the loop must reach the second entry through
20827        // the accessor.
20828        let mut spec = three_member_spec();
20829        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
20830        match spec.validate().unwrap_err() {
20831            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
20832                assert_eq!(
20833                    cluster, "BAD_CLUSTER",
20834                    "PlacementClusterInvalid.cluster must carry the \
20835                     tail entry the loop reached through the accessor",
20836                );
20837            }
20838            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
20839        }
20840        assert_eq!(
20841            spec.placement.clusters().len(),
20842            2,
20843            "the per-cluster validate loop's traversal input must be \
20844             a two-element slice per the accessor's projection",
20845        );
20846
20847        // (3) Per-cluster validate loop: a two-cluster cohort that
20848        // shares a name must trip `PlacementClusterDuplicate` on the
20849        // second entry — the loop must reach both entries through the
20850        // accessor for the dedup HashSet's second insert to collide.
20851        let mut spec = three_member_spec();
20852        spec.placement.clusters = vec!["rio".into(), "rio".into()];
20853        match spec.validate().unwrap_err() {
20854            AplicacaoError::PlacementClusterDuplicate { cluster } => {
20855                assert_eq!(
20856                    cluster, "rio",
20857                    "PlacementClusterDuplicate.cluster must carry the \
20858                     shared cluster name verbatim",
20859                );
20860            }
20861            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
20862        }
20863        assert_eq!(
20864            spec.placement.clusters().len(),
20865            2,
20866            "the per-cluster validate loop's traversal input must be \
20867             a two-element slice per the accessor's projection",
20868        );
20869    }
20870
20871    #[test]
20872    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
20873        // The canonical per-`:membros` member-list-slice-shape pin:
20874        // [`AplicacaoSpec::membros`] must return the `:membros` typed
20875        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
20876        // same backing buffer the raw `self.membros.as_slice()` field
20877        // access borrows from, byte-equal across every representative
20878        // fixture in the accept-set — the empty slice (the pre-
20879        // validation sentinel every [`AplicacaoError::NoMembros`]
20880        // refusal keys off), the singleton slice (the minimal one-
20881        // Servico Aplicacao shape), and multi-entry cohorts (the peer
20882        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
20883        // load-bearing identity of the application graph).
20884        //
20885        // Pins against a future silent detour that returned
20886        // `&Vec<Membro>` (which would type-check but leak the storage-
20887        // side `Vec`'s grow/push/reserve surface no consumer of the
20888        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
20889        // (which would type-check via a coercion but silently break
20890        // every downstream caller that relied on the slice sharing the
20891        // backing buffer's identity), or an out-of-order or length-
20892        // drifted projection (which would silently split the paired
20893        // `HashSet<&str>` name-set seed's collect input from the
20894        // pre-flight `.is_empty()` refusal probe's input from the per-
20895        // member validate loop's traversal input from the
20896        // programs.yaml emitter's per-entry fan-out loop's input from
20897        // the `feira app graph` per-member print traversal's input).
20898        //
20899        // Peer of the sibling M2
20900        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20901        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20902        // `:supervisor` static-child-list axis and the sibling M3
20903        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20904        // (a6e18d7) `&[String]` byte-equal pin on the per-
20905        // `:placement` distribution-target-list axis — extends the
20906        // slice-return-accessor byte-equal-projection discipline onto
20907        // the outermost M3 mesh-slot type's per-Aplicacao member-list
20908        // `Vec`-carry axis.
20909        let fixtures: Vec<Vec<Membro>> = vec![
20910            Vec::new(),
20911            vec![membro("catalog", "^0.1")],
20912            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20913            vec![
20914                membro("catalog", "^0.1"),
20915                membro("cart", "^0.1"),
20916                membro("payment", "^0.2"),
20917            ],
20918        ];
20919        for membros in fixtures {
20920            let s = AplicacaoSpec {
20921                membros: membros.clone(),
20922                contratos: Vec::new(),
20923                politicas: MeshPolicy::default(),
20924                placement: Placement::default(),
20925                entrada: None,
20926            };
20927            assert_eq!(
20928                s.membros(),
20929                membros.as_slice(),
20930                "AplicacaoSpec::membros must return :membros verbatim \
20931                 (got {:?}, expected {:?})",
20932                s.membros(),
20933                membros.as_slice(),
20934            );
20935            assert_eq!(
20936                s.membros(),
20937                s.membros.as_slice(),
20938                "AplicacaoSpec::membros accessor and .membros.as_slice() \
20939                 field access must byte-equal — the accessor is the \
20940                 substrate-primitive typed dispatch every downstream \
20941                 member-list consumer must route through",
20942            );
20943            assert_eq!(
20944                s.membros().len(),
20945                s.membros.len(),
20946                "AplicacaoSpec::membros().len() must byte-equal \
20947                 self.membros.len() — a length-drift would silently \
20948                 split the paired `HashSet<&str>` name-set seed's \
20949                 collect input from the pre-flight `.is_empty()` \
20950                 refusal probe input from the per-member validate \
20951                 loop's traversal input",
20952            );
20953        }
20954    }
20955
20956    #[test]
20957    fn validate_reads_through_lifted_membros_accessor() {
20958        // Three-consumer coherence pin: the
20959        // [`AplicacaoSpec::validate_membros`] pre-flight
20960        // `self.membros().is_empty()` refusal probe (which must trip
20961        // [`AplicacaoError::NoMembros`] when the accessor projects the
20962        // empty slice), the same method's per-member validate loop's
20963        // `for m in self.membros()` traversal (which must reach every
20964        // entry in the same order the accessor projects, so both the
20965        // per-entry empty-`:caixa` gate that trips
20966        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
20967        // detection `insert_first_seen` that trips
20968        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
20969        // projection), and the peer [`AplicacaoSpec::validate`]'s
20970        // `HashSet<&str>` name-set seed's
20971        // `self.membros().iter().map(Membro::nome).collect()` collect
20972        // input (which every `:contratos` `:de` / `:para` membership
20973        // lookup rejects an unknown name against) must all three key
20974        // off the lifted accessor, so any future rebrand on the typed
20975        // slot's reader shape lands at exactly one place. Pins the
20976        // three-site coherence by exercising each production consumer
20977        // end-to-end: (1) the `NoMembros` refusal under the empty
20978        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
20979        // second entry of a two-member cohort whose head is valid but
20980        // tail has an empty `:caixa` (which requires the loop to
20981        // reach the second entry through the accessor), and (3) the
20982        // `MembroDuplicate` refusal fires on the second entry of a
20983        // two-member cohort that shares a `:caixa` name (which
20984        // requires the loop to reach both entries through the
20985        // accessor for the dedup HashSet's second insert to collide).
20986        //
20987        // Peer of the sibling M2
20988        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20989        // (bc92bce) coherence pin on the per-`:supervisor` static-
20990        // child-list axis and the sibling M3
20991        // `validate_placement_reads_through_lifted_clusters_accessor`
20992        // (a6e18d7) coherence pin on the per-`:placement` distribution-
20993        // target-list axis — extends the slice-return-accessor
20994        // multi-consumer coherence discipline onto the outermost M3
20995        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
20996
20997        // (1) Pre-flight `.is_empty()` probe: the empty slice must
20998        // trip `NoMembros`.
20999        let mut spec = three_member_spec();
21000        spec.membros = Vec::new();
21001        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
21002        assert!(
21003            spec.membros().is_empty(),
21004            "the pre-flight refusal input must be the empty slice per \
21005             the accessor's projection",
21006        );
21007
21008        // (2) Per-member validate loop: a two-member cohort with an
21009        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
21010        // the tail — the loop must reach the second entry through
21011        // the accessor.
21012        let mut spec = three_member_spec();
21013        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
21014        assert_eq!(
21015            spec.validate().unwrap_err(),
21016            AplicacaoError::MembroCaixaEmpty,
21017        );
21018        assert_eq!(
21019            spec.membros().len(),
21020            2,
21021            "the per-member validate loop's traversal input must be \
21022             a two-element slice per the accessor's projection",
21023        );
21024
21025        // (3) Per-member validate loop: a two-member cohort that
21026        // shares a `:caixa` name must trip `MembroDuplicate` on the
21027        // second entry — the loop must reach both entries through the
21028        // accessor for the dedup HashSet's second insert to collide.
21029        let mut spec = three_member_spec();
21030        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
21031        match spec.validate().unwrap_err() {
21032            AplicacaoError::MembroDuplicate { caixa } => {
21033                assert_eq!(
21034                    caixa, "catalog",
21035                    "MembroDuplicate.caixa must carry the shared \
21036                     member name verbatim",
21037                );
21038            }
21039            other => panic!("expected MembroDuplicate, got {other:?}"),
21040        }
21041        assert_eq!(
21042            spec.membros().len(),
21043            2,
21044            "the per-member validate loop's traversal input must be \
21045             a two-element slice per the accessor's projection",
21046        );
21047    }
21048
21049    #[test]
21050    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
21051        // The canonical per-`:contratos` contract-list-slice-shape pin:
21052        // [`AplicacaoSpec::contratos`] must return the `:contratos`
21053        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
21054        // slice-view over the same backing buffer the raw
21055        // `self.contratos.as_slice()` field access borrows from, byte-
21056        // equal across every representative fixture in the accept-set —
21057        // the empty slice (the pre-validation "internal-only mesh" shape
21058        // an Aplicacao whose members exchange no typed edges renders
21059        // through), the singleton slice (the minimal one-edge Aplicacao
21060        // shape), and multi-entry cohorts (the peer multi-edge shapes
21061        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
21062        // of the application graph).
21063        //
21064        // Pins against a future silent detour that returned
21065        // `&Vec<WitContract>` (which would type-check but leak the
21066        // storage-side `Vec`'s grow/push/reserve surface no consumer of
21067        // the typed view reaches for), a fresh-allocated
21068        // `Vec<WitContract>` copy (which would type-check via a coercion
21069        // but silently break every downstream caller that relied on the
21070        // slice sharing the backing buffer's identity), or an out-of-
21071        // order or length-drifted projection (which would silently split
21072        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
21073        // seed's traversal input from the `detect_sync_cycles` per-edge
21074        // adjacency-list seed's traversal input from the
21075        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
21076        // BTreeMap grouping loop's traversal input from the
21077        // `feira app graph` per-contract print traversal's input).
21078        //
21079        // Peer of the immediately-adjacent sibling M3
21080        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
21081        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
21082        // node-list axis, the sibling M3
21083        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
21084        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
21085        // distribution-target-list axis, and the sibling M2
21086        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
21087        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
21088        // `:supervisor` static-child-list axis — extends the slice-
21089        // return-accessor byte-equal-projection discipline onto the
21090        // outermost M3 mesh-slot type's per-Aplicacao contract-list
21091        // `Vec`-carry axis, closing the last unlifted per-
21092        // `AplicacaoSpec` `Vec`-carry axis.
21093        let fixtures: Vec<Vec<WitContract>> = vec![
21094            Vec::new(),
21095            vec![contract_http("cart", "catalog", "/products/:id")],
21096            vec![
21097                contract_http("cart", "catalog", "/products/:id"),
21098                contract_http("cart", "payment", "/charge"),
21099            ],
21100            vec![
21101                contract_http("cart", "catalog", "/products/:id"),
21102                contract_http("cart", "payment", "/charge"),
21103                contract_http("payment", "catalog", "/audit"),
21104            ],
21105        ];
21106        for contratos in fixtures {
21107            let s = AplicacaoSpec {
21108                membros: vec![
21109                    membro("catalog", "^0.1"),
21110                    membro("cart", "^0.1"),
21111                    membro("payment", "^0.2"),
21112                ],
21113                contratos: contratos.clone(),
21114                politicas: MeshPolicy::default(),
21115                placement: Placement::default(),
21116                entrada: None,
21117            };
21118            assert_eq!(
21119                s.contratos(),
21120                contratos.as_slice(),
21121                "AplicacaoSpec::contratos must return :contratos verbatim \
21122                 (got {:?}, expected {:?})",
21123                s.contratos(),
21124                contratos.as_slice(),
21125            );
21126            assert_eq!(
21127                s.contratos(),
21128                s.contratos.as_slice(),
21129                "AplicacaoSpec::contratos accessor and \
21130                 .contratos.as_slice() field access must byte-equal — \
21131                 the accessor is the substrate-primitive typed dispatch \
21132                 every downstream contract-list consumer must route \
21133                 through",
21134            );
21135            assert_eq!(
21136                s.contratos().len(),
21137                s.contratos.len(),
21138                "AplicacaoSpec::contratos().len() must byte-equal \
21139                 self.contratos.len() — a length-drift would silently \
21140                 split the paired per-edge validate-loop's traversal \
21141                 input from the sync-cycle adjacency-list seed's \
21142                 traversal input from the cilium_network_policies \
21143                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
21144                 input from the `feira app graph` per-contract print \
21145                 traversal's input",
21146            );
21147        }
21148    }
21149
21150    #[test]
21151    fn validate_reads_through_lifted_contratos_accessor() {
21152        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
21153        // per-`:contratos` validate-loop's `for c in self.contratos()`
21154        // traversal (which must reach every entry in the same order the
21155        // accessor projects, so both the per-entry
21156        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
21157        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
21158        // dedup `HashSet` insert key off the accessor's projection),
21159        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
21160        // `for c in self.contratos()` adjacency-list seed (which drives
21161        // the sync-subgraph deadlock-detection gate via
21162        // [`AplicacaoError::SyncCycle`]), and the peer
21163        // [`caixa_mesh::cilium_network_policies`]'s
21164        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
21165        // grouping loop (which drives the per-CNP fan-out) must all
21166        // three key off the lifted accessor, so any future rebrand on
21167        // the typed slot's reader shape lands at exactly one place. Pins
21168        // the three-site coherence by exercising the two caixa-core
21169        // production consumers end-to-end: (1) the empty-`:contratos`
21170        // slice must validate without a per-edge diagnostic (the
21171        // per-edge loop is a no-op under the empty projection), (2) the
21172        // `ContratoMemberMissing` refusal fires on the second entry of a
21173        // two-edge cohort whose head references a valid member but tail
21174        // references a phantom name (which requires the loop to reach
21175        // the second entry through the accessor), and (3) the
21176        // `SyncCycle` refusal fires on a self-referential two-edge
21177        // cohort through the sync-cycle detector's peer projection
21178        // (which requires the detector to iterate the accessor's
21179        // projection to add the back-edge to its adjacency list).
21180        //
21181        // Peer of the sibling M3
21182        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
21183        // three-consumer coherence pin on the per-`:membros` node-list
21184        // axis and the sibling M3
21185        // `validate_placement_reads_through_lifted_clusters_accessor`
21186        // (a6e18d7) coherence pin on the per-`:placement` distribution-
21187        // target-list axis — extends the slice-return-accessor multi-
21188        // consumer coherence discipline onto the outermost M3 mesh-slot
21189        // type's per-Aplicacao contract-list `Vec`-carry axis.
21190
21191        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
21192        // and no per-edge diagnostic surfaces. Validate succeeds on
21193        // the well-formed `:membros` head.
21194        let mut spec = three_member_spec();
21195        spec.contratos = Vec::new();
21196        assert!(
21197            spec.validate().is_ok(),
21198            "empty :contratos must validate — the per-edge loop is a \
21199             no-op under the accessor's empty projection",
21200        );
21201        assert!(
21202            spec.contratos().is_empty(),
21203            "the per-edge validate loop's traversal input must be the \
21204             empty slice per the accessor's projection",
21205        );
21206
21207        // (2) Per-edge validate loop: a two-edge cohort whose tail
21208        // references a phantom `:para` member must trip
21209        // `ContratoMemberMissing` on the tail — the loop must reach
21210        // the second entry through the accessor for the membership
21211        // lookup to fail on the phantom name.
21212        let mut spec = three_member_spec();
21213        spec.contratos = vec![
21214            contract_http("cart", "catalog", "/products/:id"),
21215            contract_http("cart", "phantom", "/x"),
21216        ];
21217        let err = spec.validate().unwrap_err();
21218        assert!(
21219            matches!(
21220                err,
21221                AplicacaoError::ContratoMemberMissing { ref caixa }
21222                    if caixa == "phantom"
21223            ),
21224            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
21225        );
21226        assert_eq!(
21227            spec.contratos().len(),
21228            2,
21229            "the per-edge validate loop's traversal input must be \
21230             a two-element slice per the accessor's projection",
21231        );
21232
21233        // (3) Sync-cycle detector: a two-edge synchronous cohort
21234        // whose second edge closes the sync-subgraph back onto the
21235        // first must trip [`AplicacaoError::ContratoCycle`] — the
21236        // detector must iterate the accessor's projection to add
21237        // both edges to its adjacency list, so a length-drift on
21238        // the accessor's projection would silently disagree with
21239        // the sync-cycle detector on which edge closes the loop.
21240        // Peer projection to the `validate` per-edge loop above:
21241        // the sync-cycle detector routes through the same lifted
21242        // accessor, so a rebrand of the reader shape lands at one
21243        // place. Uses a two-edge cohort (cart → catalog → cart)
21244        // because the per-edge `ContratoSelfLoop` gate fires before
21245        // the sync-cycle detector on a single self-referential edge
21246        // (`cart → cart`) — the cycle-detector's input must be a
21247        // multi-edge cohort for its per-edge traversal input to be
21248        // observably wider than the per-edge validate loop's input.
21249        let mut spec = three_member_spec();
21250        spec.contratos = vec![
21251            contract_http("cart", "catalog", "/products/:id"),
21252            contract_http("catalog", "cart", "/callback"),
21253        ];
21254        let err = spec.validate().unwrap_err();
21255        assert!(
21256            matches!(err, AplicacaoError::ContratoCycle { .. }),
21257            "expected ContratoCycle from the sync-cycle detector on a \
21258             two-edge back-edge cohort, got {err:?}",
21259        );
21260        assert_eq!(
21261            spec.contratos().len(),
21262            2,
21263            "the sync-cycle detector's traversal input must be a \
21264             two-element slice per the accessor's projection",
21265        );
21266    }
21267
21268    #[test]
21269    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
21270        // The canonical per-`:politicas` outer-composite-reference-shape
21271        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
21272        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
21273        // the same backing storage the raw `&self.politicas` field
21274        // access borrows from, byte-equal across every representative
21275        // fixture in the accept-set — the default `MeshPolicy` (the
21276        // author-empty "no policy on any axis" shape whose
21277        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
21278        // shapes carrying one axis at a time
21279        // (`{mtls_required, timeout, retries, circuit_breaker,
21280        // rate_limit}` — the minimal five-axis fan-out over the
21281        // per-axis lifted accessor family every downstream mesh-artifact
21282        // emitter dispatches on), and the multi-axis composite (the
21283        // canonical `three_member_spec` fixture's `{timeout, retries,
21284        // mtls_required}` triple — the load-bearing shape every
21285        // Aplicacao-scoped fixture in this suite constructs).
21286        //
21287        // Pins against a future silent detour that returned a fresh-
21288        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
21289        // impl but silently break every downstream caller that relied
21290        // on the reference sharing the composite's backing identity), a
21291        // reference to an operator-resolved overlay (the future
21292        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
21293        // acknowledges — its resolution must land at exactly this
21294        // accessor body, not silently divert the raw slot away from a
21295        // second consumer), or an axis-shuffled projection (a future
21296        // detour that swapped `timeout` and `retries` through the
21297        // accessor would silently split the paired `validate_politicas`
21298        // per-axis bracket-dispatch's traversal input from the peer
21299        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
21300        // emitter's fan-out input from the peer
21301        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
21302        // overlay emitter's fan-out input).
21303        //
21304        // Peer of the sibling M3
21305        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
21306        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
21307        // node-list `Vec`-carry axis and the sibling M3
21308        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
21309        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
21310        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
21311        // accessor byte-equal-projection discipline onto the outermost
21312        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
21313        // reference axis, the first `&Composite`-return accessor on the
21314        // outer [`AplicacaoSpec`] type.
21315        let fixtures: Vec<MeshPolicy> = vec![
21316            MeshPolicy::default(),
21317            MeshPolicy {
21318                mtls_required: Some(true),
21319                ..MeshPolicy::default()
21320            },
21321            MeshPolicy {
21322                mtls_required: Some(false),
21323                ..MeshPolicy::default()
21324            },
21325            MeshPolicy {
21326                timeout: Some(Duration::from_secs(30)),
21327                ..MeshPolicy::default()
21328            },
21329            MeshPolicy {
21330                retries: Some(3),
21331                ..MeshPolicy::default()
21332            },
21333            MeshPolicy {
21334                circuit_breaker: Some(CircuitBreaker {
21335                    max_failures: 5,
21336                    window: Duration::from_secs(30),
21337                }),
21338                ..MeshPolicy::default()
21339            },
21340            MeshPolicy {
21341                rate_limit: Some(RateLimit {
21342                    rate: 100,
21343                    window: Duration::from_secs(1),
21344                }),
21345                ..MeshPolicy::default()
21346            },
21347            MeshPolicy {
21348                timeout: Some(Duration::from_secs(30)),
21349                retries: Some(3),
21350                mtls_required: Some(true),
21351                ..MeshPolicy::default()
21352            },
21353        ];
21354        for politicas in fixtures {
21355            let s = AplicacaoSpec {
21356                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21357                contratos: Vec::new(),
21358                politicas: politicas.clone(),
21359                placement: Placement::default(),
21360                entrada: None,
21361            };
21362            assert_eq!(
21363                *s.politicas(),
21364                politicas,
21365                "AplicacaoSpec::politicas must return :politicas verbatim \
21366                 (got {:?}, expected {:?})",
21367                s.politicas(),
21368                politicas,
21369            );
21370            assert!(
21371                std::ptr::eq(s.politicas(), &s.politicas),
21372                "AplicacaoSpec::politicas accessor and &self.politicas \
21373                 field access must borrow the same backing storage — \
21374                 the accessor is the substrate-primitive typed dispatch \
21375                 every downstream mesh-policy composite consumer must \
21376                 route through, and a reference-identity split would \
21377                 silently break every consumer that relied on the \
21378                 borrow sharing the composite's storage",
21379            );
21380            assert_eq!(
21381                s.politicas().is_empty(),
21382                s.politicas.is_empty(),
21383                "AplicacaoSpec::politicas().is_empty() must byte-equal \
21384                 self.politicas.is_empty() — an emptiness-drift would \
21385                 silently split the paired `validate_politicas` \
21386                 per-axis bracket-dispatch's seed from the peer \
21387                 caixa-mesh CNP mTLS-overlay emitter's key from the \
21388                 peer caixa-mesh HTTPRoute timeout+retry overlay \
21389                 emitter's key",
21390            );
21391        }
21392    }
21393
21394    #[test]
21395    fn validate_politicas_reads_through_lifted_politicas_accessor() {
21396        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
21397        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
21398        // followed by the per-axis fan-out `p.timeout()` /
21399        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
21400        // the lifted axis-level accessor family) must key off the
21401        // lifted outer accessor, so any future rebrand on the typed
21402        // slot's outer-composite reader shape lands at exactly one
21403        // place. Pins the multi-axis coherence by exercising each
21404        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
21405        // a `Some(Duration::ZERO)` timeout under the outer accessor's
21406        // reference projection, (2) `PolicyRetriesZero` fires on a
21407        // `Some(0)` retries under the same projection, and (3) an
21408        // empty [`MeshPolicy::default`] passes `validate_politicas` —
21409        // the outer accessor's reference-projection reaches every
21410        // per-axis branch without silently short-circuiting any.
21411        //
21412        // Peer of the sibling M3
21413        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
21414        // three-consumer coherence pin on the per-`:membros` node-list
21415        // axis and the sibling M3
21416        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
21417        // three-consumer coherence pin on the per-`:contratos`
21418        // edge-list axis — extends the multi-consumer coherence
21419        // discipline onto the outermost M3 mesh-slot type's per-
21420        // Aplicacao mesh-policy composite-reference axis, the first
21421        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
21422        // type.
21423
21424        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
21425        // reference projection: a `Some(Duration::ZERO)` timeout must
21426        // trip the zero-floor gate. The bracket-dispatch's first arm
21427        // reads `p.timeout()` on the reference returned by the outer
21428        // accessor.
21429        let mut spec = three_member_spec();
21430        spec.politicas.timeout = Some(Duration::ZERO);
21431        spec.politicas.retries = None;
21432        spec.politicas.circuit_breaker = None;
21433        spec.politicas.rate_limit = None;
21434        assert_eq!(
21435            spec.validate().unwrap_err(),
21436            AplicacaoError::PolicyTimeoutZero,
21437        );
21438        assert!(
21439            std::ptr::eq(spec.politicas(), &spec.politicas),
21440            "the `validate_politicas` per-axis bracket-dispatch's \
21441             traversal input must be the same backing composite the \
21442             accessor's reference projection borrows from",
21443        );
21444
21445        // (2) `PolicyRetriesZero` refusal under the outer accessor's
21446        // reference projection: a `Some(0)` retries must trip the
21447        // zero-floor gate. The bracket-dispatch's second arm reads
21448        // `p.retries()` on the reference returned by the outer accessor.
21449        let mut spec = three_member_spec();
21450        spec.politicas.timeout = None;
21451        spec.politicas.retries = Some(0);
21452        spec.politicas.circuit_breaker = None;
21453        spec.politicas.rate_limit = None;
21454        assert_eq!(
21455            spec.validate().unwrap_err(),
21456            AplicacaoError::PolicyRetriesZero,
21457        );
21458
21459        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
21460        // — every per-axis arm short-circuits on `None`, so the outer
21461        // accessor's reference projection reaches the fall-through
21462        // `Ok(())` without any per-axis refusal firing.
21463        let mut spec = three_member_spec();
21464        spec.politicas = MeshPolicy::default();
21465        assert!(
21466            spec.validate().is_ok(),
21467            "an empty `MeshPolicy` must pass `validate_politicas` — \
21468             every per-axis arm short-circuits on `None` under the \
21469             outer accessor's reference projection",
21470        );
21471        assert!(
21472            spec.politicas().is_empty(),
21473            "the outer accessor's reference projection must be the \
21474             empty composite per the `MeshPolicy::default()` fixture",
21475        );
21476    }
21477
21478    #[test]
21479    #[allow(clippy::too_many_lines)]
21480    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
21481        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
21482        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
21483        // must both key off the lifted axis-level accessors
21484        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
21485        // the peer `:circuit-breaker` / `:rate-limit` arms already
21486        // routing through [`MeshPolicy::circuit_breaker`] /
21487        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
21488        // per axis on the substrate primitive" shape at the fan-out
21489        // (four axes, four accessors, no raw-field-access site
21490        // anywhere on the bracket-dispatch). Pins the per-axis
21491        // coherence at the accept-set boundaries the bracket carves:
21492        //   1. accessor byte-equal to raw field on every representative
21493        //      accept-set value (`None`, sub-cap, at-cap, past-cap
21494        //      sentinel) — a future accessor drift that no longer
21495        //      shipped the raw slot verbatim would surface here,
21496        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
21497        //      routed through the accessor's projection, proving the
21498        //      first arm reads through the accessor rather than a
21499        //      silent-detour peer-axis field access,
21500        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
21501        //      through the accessor's projection, proving the second
21502        //      arm reads through the accessor,
21503        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
21504        //      passes validate under the accessor projection (paired
21505        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
21506        //      sibling axis), pinning the upper-boundary accept-arm
21507        //      also routes through the accessor.
21508        //
21509        // Peer of the sibling M3
21510        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21511        // outer-composite-reference coherence pin (which asserts the
21512        // `let p = self.politicas()` seed); extends the discipline onto
21513        // the per-axis fan-out layer that consumes the seed's
21514        // reference. Same shape as
21515        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
21516        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
21517        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
21518        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
21519
21520        // (1) Accessor byte-equal to raw field on the `:timeout` axis
21521        // across the accept-set boundaries the bracket dispatch's
21522        // three-arm gate carves out
21523        // ([`crate::render::require_positive_canonical_bounded_duration`]
21524        // — zero-floor + canonical-form + upper-cap).
21525        for timeout in [
21526            None,
21527            Some(Duration::ZERO),
21528            Some(Duration::from_millis(1)),
21529            Some(POLICY_TIMEOUT_MAX),
21530        ] {
21531            let p = MeshPolicy {
21532                timeout,
21533                ..MeshPolicy::default()
21534            };
21535            assert_eq!(
21536                p.timeout(),
21537                p.timeout,
21538                "MeshPolicy::timeout accessor must byte-equal the raw \
21539                 .timeout field across every accept-set boundary the \
21540                 validate_politicas :timeout arm carves out — a drift \
21541                 here would silently split the validate bracket's arm \
21542                 from the peer caixa-mesh HTTPRoute timeout-overlay \
21543                 emitter's read",
21544            );
21545        }
21546
21547        // (2) Accessor byte-equal to raw field on the `:retries` axis
21548        // across the accept-set boundaries the bracket dispatch's
21549        // two-arm gate carves out
21550        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
21551        // + upper-cap).
21552        for retries in [
21553            None,
21554            Some(0u32),
21555            Some(1u32),
21556            Some(POLICY_RETRIES_MAX),
21557            Some(POLICY_RETRIES_MAX + 1),
21558            Some(u32::MAX),
21559        ] {
21560            let p = MeshPolicy {
21561                retries,
21562                ..MeshPolicy::default()
21563            };
21564            assert_eq!(
21565                p.retries(),
21566                p.retries,
21567                "MeshPolicy::retries accessor must byte-equal the raw \
21568                 .retries field across every accept-set boundary the \
21569                 validate_politicas :retries arm carves out — a drift \
21570                 here would silently split the validate bracket's arm \
21571                 from the peer caixa-mesh HTTPRoute retry-overlay \
21572                 emitter's read",
21573            );
21574        }
21575
21576        // (3) `PolicyTimeoutZero` fires on the accessor-projected
21577        // zero-floor boundary. A silent detour that no longer read
21578        // through `p.timeout()` (a peer-axis field read, an accidental
21579        // Option::and-then chain that collapsed the None arm to Some,
21580        // an accessor rebrand that clamped the return through the
21581        // upper cap) would fail to refuse here.
21582        let mut spec = three_member_spec();
21583        spec.politicas.timeout = Some(Duration::ZERO);
21584        spec.politicas.retries = None;
21585        spec.politicas.circuit_breaker = None;
21586        spec.politicas.rate_limit = None;
21587        assert_eq!(
21588            spec.politicas().timeout(),
21589            Some(Duration::ZERO),
21590            "the accessor projection must reflect the fixture's \
21591             `Some(Duration::ZERO)` :timeout verbatim",
21592        );
21593        assert_eq!(
21594            spec.validate().unwrap_err(),
21595            AplicacaoError::PolicyTimeoutZero,
21596            "the validate_politicas :timeout zero-floor arm must fire \
21597             through the lifted accessor's projection — a silent \
21598             detour to a peer-axis field would fail to refuse",
21599        );
21600
21601        // (4) `PolicyRetriesZero` fires on the accessor-projected
21602        // zero-floor boundary on the sibling `:retries` axis.
21603        let mut spec = three_member_spec();
21604        spec.politicas.timeout = None;
21605        spec.politicas.retries = Some(0);
21606        spec.politicas.circuit_breaker = None;
21607        spec.politicas.rate_limit = None;
21608        assert_eq!(
21609            spec.politicas().retries(),
21610            Some(0),
21611            "the accessor projection must reflect the fixture's \
21612             `Some(0)` :retries verbatim",
21613        );
21614        assert_eq!(
21615            spec.validate().unwrap_err(),
21616            AplicacaoError::PolicyRetriesZero,
21617            "the validate_politicas :retries zero-floor arm must fire \
21618             through the lifted accessor's projection — a silent \
21619             detour to a peer-axis field would fail to refuse",
21620        );
21621
21622        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
21623        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
21624        // must pass validate under the accessor projection — pins the
21625        // upper-boundary accept-arm also routes through the lifted
21626        // accessor (a drift that clamped or short-circuited at the
21627        // upper boundary would fail the whole-spec validate here).
21628        let mut spec = three_member_spec();
21629        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
21630        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
21631        spec.politicas.circuit_breaker = None;
21632        spec.politicas.rate_limit = None;
21633        assert_eq!(
21634            spec.politicas().timeout(),
21635            Some(POLICY_TIMEOUT_MAX),
21636            "the accessor projection must reflect the fixture's \
21637             at-cap :timeout verbatim",
21638        );
21639        assert_eq!(
21640            spec.politicas().retries(),
21641            Some(POLICY_RETRIES_MAX),
21642            "the accessor projection must reflect the fixture's \
21643             at-cap :retries verbatim",
21644        );
21645        assert!(
21646            spec.validate().is_ok(),
21647            "at-cap :timeout + :retries must pass validate under the \
21648             accessor projection — the upper-boundary accept-arm on \
21649             both axes routes through the lifted accessor",
21650        );
21651    }
21652
21653    #[test]
21654    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
21655        // The canonical per-`:placement` outer-composite-reference-shape
21656        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
21657        // typed `Placement` verbatim as a `&Placement` reference over the
21658        // same backing storage the raw `&self.placement` field access
21659        // borrows from, byte-equal across every representative fixture in
21660        // the accept-set — the default `Placement` (the substrate seed
21661        // shape whose [`PlacementStrategy::default`] evaluates to
21662        // `SingleNode` with an empty `:clusters` pool and both
21663        // optional-scalar axes `None`), and every canonical strategy /
21664        // cluster-pool / optional-scalar combination the
21665        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
21666        // three [`PlacementStrategy`] variants — `SingleNode`,
21667        // `Replicated`, `Sharded` — cross-projected with a non-empty
21668        // `:clusters` pool and, on the `Sharded` arm, a non-empty
21669        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
21670        // canonical `three_member_spec` `Replicated` fixture's
21671        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
21672        //
21673        // Pins against a future silent detour that returned a fresh-
21674        // cloned `Placement` copy (which would type-check via a `Clone`
21675        // impl but silently break every downstream caller that relied on
21676        // the reference sharing the composite's backing identity), a
21677        // reference to an operator-resolved overlay (the future per-
21678        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
21679        // acknowledges — its resolution must land at exactly this
21680        // accessor body, not silently divert the raw slot away from a
21681        // second consumer), or an axis-shuffled projection (a future
21682        // detour that swapped `clusters` and `affinity` through the
21683        // accessor would silently split the paired `validate_placement`
21684        // per-axis bracket-dispatch's traversal input from the peer
21685        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
21686        // programs.yaml distribution-annotation emitter's fan-out input
21687        // from the peer `feira app graph` per-Aplicacao print line's
21688        // input).
21689        //
21690        // Peer of the sibling M3
21691        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21692        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
21693        // outer mesh-policy composite-reference axis, and of the sibling
21694        // slice-return `aplicacao_spec_membros_returns_membros_slice_
21695        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
21696        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
21697        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
21698        // the outer-accessor byte-equal-projection discipline onto the
21699        // outermost M3 mesh-slot type's per-Aplicacao distribution
21700        // composite-reference axis, the second `&Composite`-return
21701        // accessor on the outer [`AplicacaoSpec`] type.
21702        let fixtures: Vec<Placement> = vec![
21703            Placement::default(),
21704            Placement {
21705                estrategia: PlacementStrategy::SingleNode,
21706                clusters: vec!["rio".into()],
21707                affinity: None,
21708                shard_key: None,
21709            },
21710            Placement {
21711                estrategia: PlacementStrategy::Replicated,
21712                clusters: vec!["rio".into(), "mar".into()],
21713                affinity: None,
21714                shard_key: None,
21715            },
21716            Placement {
21717                estrategia: PlacementStrategy::Replicated,
21718                clusters: vec!["rio".into(), "mar".into()],
21719                affinity: Some("data-locality".into()),
21720                shard_key: None,
21721            },
21722            Placement {
21723                estrategia: PlacementStrategy::Sharded,
21724                clusters: vec!["rio".into(), "mar".into()],
21725                affinity: None,
21726                shard_key: Some("tenantId".into()),
21727            },
21728            Placement {
21729                estrategia: PlacementStrategy::Sharded,
21730                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
21731                affinity: Some("low-latency".into()),
21732                shard_key: Some("metadata.tenantId".into()),
21733            },
21734        ];
21735        for placement in fixtures {
21736            let s = AplicacaoSpec {
21737                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21738                contratos: Vec::new(),
21739                politicas: MeshPolicy::default(),
21740                placement: placement.clone(),
21741                entrada: None,
21742            };
21743            assert_eq!(
21744                *s.placement(),
21745                placement,
21746                "AplicacaoSpec::placement must return :placement verbatim \
21747                 (got {:?}, expected {:?})",
21748                s.placement(),
21749                placement,
21750            );
21751            assert!(
21752                std::ptr::eq(s.placement(), &s.placement),
21753                "AplicacaoSpec::placement accessor and &self.placement \
21754                 field access must borrow the same backing storage — the \
21755                 accessor is the substrate-primitive typed dispatch every \
21756                 downstream distribution-composite consumer must route \
21757                 through, and a reference-identity split would silently \
21758                 break every consumer that relied on the borrow sharing \
21759                 the composite's storage",
21760            );
21761            assert_eq!(
21762                s.placement().estrategia(),
21763                s.placement.estrategia,
21764                "AplicacaoSpec::placement().estrategia() must byte-equal \
21765                 self.placement.estrategia — a strategy-drift would \
21766                 silently split the paired `validate_placement` \
21767                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
21768                 peer caixa-mesh programs.yaml `placement.estrategia` \
21769                 emitter's key from the peer `feira app graph` printer's \
21770                 strategy label",
21771            );
21772            assert_eq!(
21773                s.placement().clusters(),
21774                s.placement.clusters.as_slice(),
21775                "AplicacaoSpec::placement().clusters() must byte-equal \
21776                 self.placement.clusters — a cluster-pool drift would \
21777                 silently split the paired `validate_placement` \
21778                 pre-flight `.is_empty()` refusal probe's traversal from \
21779                 the peer caixa-mesh programs.yaml `placement.clusters` \
21780                 emitter's fan-out from the peer `feira app graph` \
21781                 printer's cluster list",
21782            );
21783        }
21784    }
21785
21786    #[test]
21787    fn validate_placement_reads_through_lifted_placement_accessor() {
21788        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
21789        // per-axis bracket-dispatch seed (`let p = self.placement();`,
21790        // followed by the per-axis fan-out `p.clusters()` /
21791        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
21792        // lifted axis-level accessor family) must key off the lifted
21793        // outer accessor, so any future rebrand on the typed slot's
21794        // outer-composite reader shape lands at exactly one place. Pins
21795        // the multi-axis coherence by exercising each per-axis refusal
21796        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
21797        // `:clusters` pool under the outer accessor's reference
21798        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
21799        // strategy with a `None` `:shard-key` under the same projection,
21800        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
21801        // with a `Some` `:shard-key` under the same projection, and
21802        // (4) the canonical `three_member_spec` `Replicated` fixture
21803        // passes `validate_placement` under the outer accessor's
21804        // reference projection — the accessor's reference-projection
21805        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
21806        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
21807        // without silently short-circuiting any.
21808        //
21809        // Peer of the sibling M3
21810        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21811        // (534dc21) multi-axis coherence pin on the per-`:politicas`
21812        // outer mesh-policy composite-reference axis — extends the
21813        // multi-consumer coherence discipline onto the outermost M3
21814        // mesh-slot type's per-Aplicacao distribution composite-
21815        // reference axis, the second `&Composite`-return accessor on
21816        // the outer [`AplicacaoSpec`] type.
21817
21818        // (1) `PlacementWithoutClusters` refusal under the outer
21819        // accessor's reference projection: an empty `:clusters` pool
21820        // must trip the pre-flight refusal probe. The bracket-dispatch's
21821        // first arm reads `p.clusters()` on the reference returned by
21822        // the outer accessor.
21823        let mut spec = three_member_spec();
21824        spec.placement.clusters = Vec::new();
21825        assert_eq!(
21826            spec.validate().unwrap_err(),
21827            AplicacaoError::PlacementWithoutClusters {
21828                estrategia: PlacementStrategy::Replicated,
21829            },
21830        );
21831        assert!(
21832            std::ptr::eq(spec.placement(), &spec.placement),
21833            "the `validate_placement` per-axis bracket-dispatch's \
21834             traversal input must be the same backing composite the \
21835             accessor's reference projection borrows from",
21836        );
21837
21838        // (2) `ShardedWithoutKey` refusal under the outer accessor's
21839        // reference projection: a `Sharded` strategy with a `None`
21840        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
21841        // The bracket-dispatch's third arm reads `p.estrategia()` for
21842        // the match scrutinee then `p.shard_key()` for the cascade
21843        // scrutinee, both on the reference returned by the outer
21844        // accessor.
21845        let mut spec = three_member_spec();
21846        spec.placement.estrategia = PlacementStrategy::Sharded;
21847        spec.placement.shard_key = None;
21848        assert_eq!(
21849            spec.validate().unwrap_err(),
21850            AplicacaoError::ShardedWithoutKey,
21851        );
21852
21853        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
21854        // reference projection: a non-`Sharded` strategy with a `Some`
21855        // `:shard-key` must trip the declared-but-inert refusal. The
21856        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
21857        // + `p.estrategia()` for the diagnostic on the reference
21858        // returned by the outer accessor.
21859        let mut spec = three_member_spec();
21860        spec.placement.estrategia = PlacementStrategy::Replicated;
21861        spec.placement.shard_key = Some("tenantId".into());
21862        assert_eq!(
21863            spec.validate().unwrap_err(),
21864            AplicacaoError::ShardKeyOnNonSharded {
21865                estrategia: PlacementStrategy::Replicated,
21866                shard_key: "tenantId".into(),
21867            },
21868        );
21869
21870        // (4) Canonical `three_member_spec` `Replicated` fixture passes
21871        // `validate_placement` — every per-axis arm reaches the fall-
21872        // through `Ok(())` without any per-axis refusal firing under the
21873        // outer accessor's reference projection.
21874        let spec = three_member_spec();
21875        assert!(
21876            spec.validate().is_ok(),
21877            "the canonical Replicated placement fixture must pass \
21878             `validate_placement` — every per-axis arm short-circuits on \
21879             valid input under the outer accessor's reference projection",
21880        );
21881        assert_eq!(
21882            spec.placement().estrategia(),
21883            PlacementStrategy::Replicated,
21884            "the outer accessor's reference projection must be the \
21885             canonical Replicated fixture's strategy",
21886        );
21887        assert_eq!(
21888            spec.placement().clusters(),
21889            &["rio", "mar"],
21890            "the outer accessor's reference projection must be the \
21891             canonical Replicated fixture's cluster pool",
21892        );
21893    }
21894
21895    #[test]
21896    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
21897        // The canonical per-`:entrada` outer-composite-optional-
21898        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
21899        // the `:entrada` typed `Option<Entrada>` verbatim as an
21900        // `Option<&Entrada>` reference over the same backing storage
21901        // the raw `self.entrada.as_ref()` field access borrows from,
21902        // byte-equal across every representative fixture in the
21903        // accept-set — the author-omitted `None` shape (the
21904        // "internal-only mesh" partition every downstream external-
21905        // gateway emitter treats as "emit nothing"), the minimal
21906        // singleton `:entrada` composite (host + destination + empty
21907        // paths + default port), the paths-carrying composite (the
21908        // canonical `three_member_spec` fixture's ["/api" "/health"]
21909        // path-list shape every HTTPRoute per-rule fan-out emitter
21910        // reads), and the non-default port composite (the canonical
21911        // custom-port shape the port-fallback resolver reads).
21912        //
21913        // Pins against a future silent detour that returned a fresh-
21914        // cloned `Entrada` copy (which would type-check via a `Clone`
21915        // impl but silently break every downstream caller that
21916        // relied on the reference sharing the composite's backing
21917        // identity), a reference to an operator-resolved overlay
21918        // (the future per-cluster `:entrada-overrides` slot the
21919        // MESH-COMPOSITION §V federation roadmap acknowledges — its
21920        // resolution must land at exactly this accessor body, not
21921        // silently divert the raw slot away from a second consumer),
21922        // a `None` → `Some(Entrada::default)` cluster-default
21923        // projection (which would collapse the load-bearing
21924        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
21925        // the peer `gateway_routes` early-return + `feira app graph`
21926        // internal-only-mesh partition both read), or an axis-
21927        // shuffled projection (a future detour that swapped
21928        // `host` and `para` through the accessor would silently
21929        // split the paired `validate` per-`:entrada` shape-and-
21930        // membership gate's traversal input from the peer
21931        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
21932        // fan-out input from the peer `feira app graph` external-
21933        // gateway summary line).
21934        //
21935        // Peer of the sibling M3
21936        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21937        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
21938        // `:politicas` outer mesh-policy composite-reference axis
21939        // and of the sibling M3
21940        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
21941        // (9abb8f0) `&Placement` byte-equal pin on the per-
21942        // `:placement` outer distribution-composite composite-
21943        // reference axis — extends the outer-accessor byte-equal-
21944        // projection discipline onto the last unlifted outermost M3
21945        // mesh-slot type's per-Aplicacao external-gateway composite-
21946        // reference axis, the third and final `&Composite`-return
21947        // accessor on the outer [`AplicacaoSpec`] type.
21948        let fixtures: Vec<Option<Entrada>> = vec![
21949            None,
21950            Some(Entrada {
21951                host: "checkout.quero.cloud".into(),
21952                para: "cart".into(),
21953                paths: Vec::new(),
21954                port: DEFAULT_SERVICO_PORT,
21955            }),
21956            Some(Entrada {
21957                host: "checkout.quero.cloud".into(),
21958                para: "cart".into(),
21959                paths: vec!["/api".into(), "/health".into()],
21960                port: DEFAULT_SERVICO_PORT,
21961            }),
21962            Some(Entrada {
21963                host: "checkout.quero.cloud".into(),
21964                para: "cart".into(),
21965                paths: vec!["/api".into()],
21966                port: 9443,
21967            }),
21968        ];
21969        for entrada in fixtures {
21970            let s = AplicacaoSpec {
21971                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21972                contratos: Vec::new(),
21973                politicas: MeshPolicy::default(),
21974                placement: Placement::default(),
21975                entrada: entrada.clone(),
21976            };
21977            assert_eq!(
21978                s.entrada(),
21979                entrada.as_ref(),
21980                "AplicacaoSpec::entrada must return :entrada verbatim \
21981                 (got {:?}, expected {:?})",
21982                s.entrada(),
21983                entrada.as_ref(),
21984            );
21985            match (s.entrada(), s.entrada.as_ref()) {
21986                (Some(a), Some(b)) => assert!(
21987                    std::ptr::eq(a, b),
21988                    "AplicacaoSpec::entrada accessor and \
21989                     self.entrada.as_ref() field access must borrow \
21990                     the same backing storage — the accessor is the \
21991                     substrate-primitive typed dispatch every \
21992                     downstream external-gateway composite consumer \
21993                     must route through, and a reference-identity \
21994                     split would silently break every consumer that \
21995                     relied on the borrow sharing the composite's \
21996                     storage",
21997                ),
21998                (None, None) => {}
21999                _ => panic!(
22000                    "AplicacaoSpec::entrada presence bit must byte-\
22001                     equal self.entrada.is_some() — a presence-bit \
22002                     drift would silently split the paired `validate` \
22003                     per-`:entrada` shape-and-membership gate's \
22004                     traversal head from the peer \
22005                     caixa-mesh gateway_routes early-return partition \
22006                     from the peer `feira app graph` internal-only-\
22007                     mesh partition",
22008                ),
22009            }
22010            assert_eq!(
22011                s.entrada().is_some(),
22012                s.entrada.is_some(),
22013                "AplicacaoSpec::entrada().is_some() must byte-equal \
22014                 self.entrada.is_some() — a presence-bit drift would \
22015                 silently split every downstream `Option<&Entrada>` \
22016                 consumer's partition on the internal-only-mesh arm",
22017            );
22018        }
22019    }
22020
22021    #[test]
22022    fn validate_reads_through_lifted_entrada_accessor() {
22023        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
22024        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
22025        // self.entrada() { … }`, followed by the per-axis fan-out
22026        // `validate_entrada_para(&e.para)` /
22027        // `EntradaMemberMissing` membership lookup /
22028        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
22029        // per-`e.paths` `validate_entrada_path` traversal) must key
22030        // off the lifted outer accessor, so any future rebrand on
22031        // the typed slot's outer-composite reader shape lands at
22032        // exactly one place. Pins the multi-axis coherence by
22033        // exercising each per-axis refusal end-to-end: (1) the
22034        // author-omitted `None` shape short-circuits past every
22035        // per-`:entrada` refusal (the internal-only mesh partition
22036        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
22037        // fires on a well-shaped but phantom `:para` under the outer
22038        // accessor's reference projection, and (3) the canonical
22039        // `three_member_spec` `:entrada` fixture passes `validate`
22040        // under the outer accessor's reference projection.
22041        //
22042        // Peer of the sibling M3
22043        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
22044        // (534dc21) multi-axis coherence pin on the per-`:politicas`
22045        // outer mesh-policy composite-reference axis and the sibling
22046        // M3
22047        // [`validate_placement_reads_through_lifted_placement_accessor`]
22048        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
22049        // outer distribution-composite composite-reference axis —
22050        // extends the multi-consumer coherence discipline onto the
22051        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
22052        // external-gateway composite-reference axis, the third and
22053        // final `&Composite`-return accessor on the outer
22054        // [`AplicacaoSpec`] type.
22055
22056        // (1) `None` :entrada — the internal-only-mesh partition
22057        // short-circuits past every per-`:entrada` refusal. The outer
22058        // accessor's reference projection reaches the fall-through
22059        // `Ok(())` on the `None` arm without any per-axis refusal
22060        // firing.
22061        let mut spec = three_member_spec();
22062        spec.entrada = None;
22063        assert!(
22064            spec.validate().is_ok(),
22065            "an author-omitted `:entrada` must pass `validate` — the \
22066             internal-only-mesh partition short-circuits past every \
22067             per-`:entrada` refusal under the outer accessor's \
22068             reference projection",
22069        );
22070        assert!(
22071            spec.entrada().is_none(),
22072            "the outer accessor's reference projection must name the \
22073             internal-only-mesh partition per the `None` fixture",
22074        );
22075
22076        // (2) `EntradaMemberMissing` refusal under the outer accessor's
22077        // reference projection: a well-shaped but phantom `:para` must
22078        // trip the membership-lookup refusal. The gate's second arm
22079        // reads `e.para` on the reference returned by the outer
22080        // accessor.
22081        let mut spec = three_member_spec();
22082        if let Some(e) = spec.entrada.as_mut() {
22083            e.para = "phantom".into();
22084        }
22085        assert_eq!(
22086            spec.validate().unwrap_err(),
22087            AplicacaoError::EntradaMemberMissing {
22088                para: "phantom".into(),
22089            },
22090        );
22091        match (spec.entrada(), spec.entrada.as_ref()) {
22092            (Some(a), Some(b)) => assert!(
22093                std::ptr::eq(a, b),
22094                "the `validate` per-`:entrada` gate's traversal head \
22095                 must be the same backing composite the accessor's \
22096                 reference projection borrows from",
22097            ),
22098            _ => panic!("fixture must carry Some(:entrada)"),
22099        }
22100
22101        // (3) Canonical `three_member_spec` `:entrada` fixture passes
22102        // `validate` — every per-axis arm reaches the fall-through
22103        // `Ok(())` without any per-axis refusal firing under the
22104        // outer accessor's reference projection.
22105        let spec = three_member_spec();
22106        assert!(
22107            spec.validate().is_ok(),
22108            "the canonical `:entrada` fixture must pass `validate` — \
22109             every per-axis arm short-circuits on valid input under \
22110             the outer accessor's reference projection",
22111        );
22112        assert!(
22113            spec.entrada().is_some(),
22114            "the outer accessor's reference projection must be the \
22115             canonical `:entrada` fixture's composite",
22116        );
22117    }
22118
22119    #[test]
22120    fn port_for_destination_reads_through_lifted_entrada_accessor() {
22121        // Peer coherence pin: the
22122        // [`AplicacaoSpec::port_for_destination`] per-destination
22123        // L4-port fallback resolver's composite-projection seed
22124        // (`self.entrada().filter(…).map_or(…)`) must key off the
22125        // lifted outer accessor. Pins the coherence by exercising
22126        // the resolver end-to-end: (1) the `None` `:entrada` shape
22127        // falls through to `DEFAULT_SERVICO_PORT` under the outer
22128        // accessor's reference projection, (2) a non-matching
22129        // destination falls through to `DEFAULT_SERVICO_PORT` under
22130        // the outer accessor's reference projection, and (3) the
22131        // matching destination resolves to the `:entrada :port`
22132        // value under the outer accessor's reference projection.
22133        //
22134        // Peer of the sibling
22135        // [`validate_reads_through_lifted_entrada_accessor`] multi-
22136        // consumer coherence pin on the same per-`:entrada` outer-
22137        // composite axis — extends the multi-consumer coherence
22138        // discipline onto the second per-`:entrada` production
22139        // consumer, the L4-port fallback resolver.
22140
22141        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
22142        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
22143        // arm under the outer accessor's reference projection.
22144        let mut spec = three_member_spec();
22145        spec.entrada = None;
22146        assert_eq!(
22147            spec.port_for_destination("cart"),
22148            DEFAULT_SERVICO_PORT,
22149            "the port-fallback resolver must fall through to \
22150             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
22151             under the outer accessor's reference projection",
22152        );
22153
22154        // (2) Non-matching destination — the resolver's `filter(…)`
22155        // arm rejects a mismatched destination and falls through
22156        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
22157        // reference projection.
22158        let mut spec = three_member_spec();
22159        if let Some(e) = spec.entrada.as_mut() {
22160            e.para = "cart".into();
22161            e.port = 9443;
22162        }
22163        assert_eq!(
22164            spec.port_for_destination("catalog"),
22165            DEFAULT_SERVICO_PORT,
22166            "the port-fallback resolver must fall through to \
22167             DEFAULT_SERVICO_PORT on a non-matching destination \
22168             under the outer accessor's reference projection",
22169        );
22170
22171        // (3) Matching destination — the resolver's `map_or(…)` arm
22172        // returns the `:entrada :port` value under the outer
22173        // accessor's reference projection.
22174        let mut spec = three_member_spec();
22175        if let Some(e) = spec.entrada.as_mut() {
22176            e.para = "cart".into();
22177            e.port = 9443;
22178        }
22179        assert_eq!(
22180            spec.port_for_destination("cart"),
22181            9443,
22182            "the port-fallback resolver must return the \
22183             `:entrada :port` value on a matching destination \
22184             under the outer accessor's reference projection",
22185        );
22186    }
22187
22188    #[test]
22189    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
22190        // The canonical per-`:politicas` `:mtls-required` mTLS-
22191        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
22192        // must return the `:politicas :mtls-required` typed bool
22193        // verbatim as an `Option<bool>`, byte-equal to the raw field
22194        // access across every value in the three-way accept-set —
22195        // `None` (cluster default applies), `Some(true)` (mTLS
22196        // handshake enforced — the sandboxing-by-default arm the
22197        // MeshPolicy's docstring names), `Some(false)` (handshake
22198        // skipped — the explicit debug-edge opt-out).
22199        //
22200        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
22201        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
22202        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
22203        // shape — first `Option<Copy-T>`-return accessor on the M3
22204        // mesh-slot family. Pins against a future silent detour that
22205        // re-derived the toggle from a peer axis (an accidental
22206        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
22207        // whenever a breaker is set), a `None` → `Some(false)` cluster-
22208        // default projection (the canonical `Option<bool>` → `bool`
22209        // collapse footgun the surrounding `is_empty()` predicate
22210        // guards on the peer emptiness axis), or a `Some(true)` /
22211        // `Some(false)` variant swap that landed on one consumer
22212        // without the other.
22213        for required in [None, Some(true), Some(false)] {
22214            let p = MeshPolicy {
22215                mtls_required: required,
22216                ..MeshPolicy::default()
22217            };
22218            assert_eq!(
22219                p.mtls_required(),
22220                required,
22221                "MeshPolicy::mtls_required must return :politicas \
22222                 :mtls-required verbatim (got {:?}, expected {required:?})",
22223                p.mtls_required(),
22224            );
22225            assert_eq!(
22226                p.mtls_required(),
22227                p.mtls_required,
22228                "MeshPolicy::mtls_required must byte-equal the raw \
22229                 .mtls_required field access across every value in the \
22230                 three-way accept-set",
22231            );
22232        }
22233    }
22234
22235    #[test]
22236    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
22237        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
22238        // arm must key off [`MeshPolicy::mtls_required`], not the raw
22239        // `.mtls_required` field access. Structurally: toggling ONLY
22240        // the `mtls_required` slot on an otherwise-default MeshPolicy
22241        // must flip `is_empty()` from `true` (all-`None`) to `false`
22242        // (one axis carries a value); the flip must be observed for
22243        // both `Some(true)` and `Some(false)` since the emptiness
22244        // semantic reads "any axis carries a value" — not "any axis
22245        // carries a truthy value" — the same non-collapsing shape the
22246        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22247        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
22248        // peer `Option<T>`-typed slot surfaces.
22249        //
22250        // Pins against a future silent detour that re-derived the
22251        // emptiness predicate off a peer axis (an accidental
22252        // `.rate_limit.is_none()`-only chain that dropped the
22253        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
22254        // collapse to a truthy-only check (which would silently
22255        // classify `Some(false)` as empty), or an accessor-side
22256        // detour that no longer names the substrate-primitive typed
22257        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
22258        // == false` fallback in the accessor that would silently
22259        // classify both `None` and `Some(false)` as the same value).
22260        //
22261        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
22262        // (7cd2a28) accessor-composition pin on the sibling optional-
22263        // scalar axis — same "the emptiness / shape-gate predicate
22264        // must route through the substrate-primitive typed dispatch"
22265        // discipline extended onto the peer per-`:politicas` emptiness
22266        // predicate.
22267        let empty = MeshPolicy::default();
22268        assert!(
22269            empty.is_empty(),
22270            "MeshPolicy::default() must be is_empty() — every axis \
22271             defaults to None",
22272        );
22273        for required in [Some(true), Some(false)] {
22274            let p = MeshPolicy {
22275                mtls_required: required,
22276                ..MeshPolicy::default()
22277            };
22278            assert!(
22279                !p.is_empty(),
22280                "MeshPolicy::is_empty must return false when \
22281                 :mtls-required is {required:?} — the emptiness \
22282                 predicate reads \"any axis carries a value\", not \
22283                 \"any axis carries a truthy value\"",
22284            );
22285            assert_eq!(
22286                p.mtls_required().is_none(),
22287                p.is_empty(),
22288                "when :mtls-required is the only set axis, \
22289                 is_empty() must equal mtls_required().is_none() — \
22290                 the accessor and the emptiness predicate must \
22291                 route through the same substrate-primitive typed \
22292                 dispatch on the :mtls-required arm",
22293            );
22294        }
22295    }
22296
22297    #[test]
22298    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
22299        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
22300        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
22301        // accessor must return by value, not by reference. Peer of the
22302        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22303        // borrow-invariant pin on the sibling `Option<String>` slot,
22304        // but extended onto the peer `Option<bool>` copy-invariant
22305        // shape — the accessor's returned `Option<bool>` must outlive
22306        // `&self` (multiple calls must return equal values from a
22307        // dropped-`&self` copy, since the returned Option carries no
22308        // borrow), and calling the accessor twice on the same
22309        // MeshPolicy must yield the same `Option<bool>` verbatim
22310        // (idempotent, no side effects on `&self`).
22311        //
22312        // Pins against a future silent detour that returned
22313        // `Option<&bool>` (which would type-check but silently break
22314        // every downstream caller — [`single_field_overlay`]'s first
22315        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
22316        // detached copy at the call site), an accidental
22317        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
22318        // would also type-check but return `Option<&bool>`), or a
22319        // one-arm-only accessor that reads `Some(*b)` in the Some arm
22320        // but reads a fresh Default::default() in the None arm.
22321        for required in [None, Some(true), Some(false)] {
22322            let p = MeshPolicy {
22323                mtls_required: required,
22324                ..MeshPolicy::default()
22325            };
22326            let first = p.mtls_required();
22327            let second = p.mtls_required();
22328            assert_eq!(
22329                first, second,
22330                "MeshPolicy::mtls_required must be idempotent — two \
22331                 successive calls on the same &self must return the \
22332                 same Option<bool>",
22333            );
22334            assert_eq!(
22335                first, required,
22336                "MeshPolicy::mtls_required must return :politicas \
22337                 :mtls-required verbatim by copy — got {first:?}, \
22338                 expected {required:?}",
22339            );
22340        }
22341    }
22342
22343    #[test]
22344    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
22345        // The canonical per-`:politicas` `:retries` transient-failure-
22346        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
22347        // the `:politicas :retries` typed `u32` verbatim as an
22348        // `Option<u32>`, byte-equal to the raw field access across every
22349        // representative value in the accept-set — `None` (cluster
22350        // default applies — typically "no retries beyond a single
22351        // dispatch attempt" the caixa-mesh `retry_overlay` builder
22352        // documents), `Some(1)` (the lower boundary of the
22353        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
22354        // `AplicacaoSpec::validate_politicas` gate carves out on the
22355        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
22356        // (the upper boundary the same gate carves out on the sibling
22357        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
22358        // past-the-guard sentinel that pins the accessor doesn't perform
22359        // a silent bounds-collapse at the return path).
22360        //
22361        // Sibling of the peer per-`:politicas`
22362        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
22363        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
22364        // peer per-`:politicas` `Option<u32>` shape — second
22365        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
22366        // Pins against a future silent detour that re-derived the retry
22367        // cap from a peer axis (an accidental `.circuit_breaker
22368        // .as_ref().map(|b| b.max_failures)` collapse that read the
22369        // breaker's max-failure count as a retry budget), a
22370        // `None → Some(0)` cluster-default projection (which would
22371        // silently re-introduce the `PolicyRetriesZero` refusal case at
22372        // the emit boundary), or a bounds-collapsing accessor that
22373        // clamped the return through `POLICY_RETRIES_MAX` (the
22374        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22375        // must ship the raw slot verbatim so a validate-time gate
22376        // regression surfaces at the emit boundary rather than being
22377        // silently absorbed).
22378        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
22379            let p = MeshPolicy {
22380                retries,
22381                ..MeshPolicy::default()
22382            };
22383            assert_eq!(
22384                p.retries(),
22385                retries,
22386                "MeshPolicy::retries must return :politicas :retries \
22387                 verbatim (got {:?}, expected {retries:?})",
22388                p.retries(),
22389            );
22390            assert_eq!(
22391                p.retries(),
22392                p.retries,
22393                "MeshPolicy::retries must byte-equal the raw .retries \
22394                 field access across every value in the accept-set",
22395            );
22396        }
22397    }
22398
22399    #[test]
22400    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
22401        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
22402        // must key off [`MeshPolicy::retries`], not the raw `.retries`
22403        // field access. Structurally: toggling ONLY the `retries` slot
22404        // on an otherwise-default MeshPolicy must flip `is_empty()`
22405        // from `true` (all-`None`) to `false` (one axis carries a
22406        // value); the flip must be observed for every value in the
22407        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
22408        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
22409        // the emptiness semantic reads "any axis carries a value" —
22410        // not "any axis carries a value the validate gate accepts" —
22411        // the same non-collapsing shape the peer M2
22412        // [`crate::LimitsSpec::is_empty`] /
22413        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22414        //
22415        // Pins against a future silent detour that re-derived the
22416        // emptiness predicate off a peer axis (an accidental
22417        // `.rate_limit.is_none()`-only chain that dropped the
22418        // `retries` arm entirely), a `retries == Some(_)` collapse
22419        // that key-off a validate-gate-clamped bounds check (which
22420        // would silently classify a past-the-guard `Some(u32::MAX)`
22421        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
22422        // check), or an accessor-side detour that no longer names the
22423        // substrate-primitive typed dispatch.
22424        //
22425        // Sibling of the peer per-`:politicas`
22426        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
22427        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
22428        // same "the emptiness predicate must route through the
22429        // substrate-primitive typed dispatch" discipline extended onto
22430        // the peer per-`:politicas` `Option<u32>` axis.
22431        let empty = MeshPolicy::default();
22432        assert!(
22433            empty.is_empty(),
22434            "MeshPolicy::default() must be is_empty() — every axis \
22435             defaults to None",
22436        );
22437        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
22438            let p = MeshPolicy {
22439                retries,
22440                ..MeshPolicy::default()
22441            };
22442            assert!(
22443                !p.is_empty(),
22444                "MeshPolicy::is_empty must return false when \
22445                 :retries is {retries:?} — the emptiness \
22446                 predicate reads \"any axis carries a value\", not \
22447                 \"any axis carries a value the validate gate \
22448                 accepts\"",
22449            );
22450            assert_eq!(
22451                p.retries().is_none(),
22452                p.is_empty(),
22453                "when :retries is the only set axis, is_empty() \
22454                 must equal retries().is_none() — the accessor and \
22455                 the emptiness predicate must route through the same \
22456                 substrate-primitive typed dispatch on the :retries \
22457                 arm",
22458            );
22459        }
22460    }
22461
22462    #[test]
22463    fn mesh_policy_retries_projects_option_u32_by_copy() {
22464        // The by-copy pin: [`MeshPolicy::retries`] returns
22465        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
22466        // accessor must return by value, not by reference. Sibling of
22467        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
22468        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
22469        // extended onto the sibling `Option<u32>` copy-invariant
22470        // shape — the accessor's returned `Option<u32>` must outlive
22471        // `&self` (multiple calls must return equal values from a
22472        // dropped-`&self` copy, since the returned Option carries no
22473        // borrow), and calling the accessor twice on the same
22474        // MeshPolicy must yield the same `Option<u32>` verbatim
22475        // (idempotent, no side effects on `&self`).
22476        //
22477        // Pins against a future silent detour that returned
22478        // `Option<&u32>` (which would type-check but silently break
22479        // every downstream caller — [`crate::render::single_field_overlay`]'s
22480        // first parameter is `Option<T: Clone>`, and `&u32` would
22481        // fold to a detached copy at the call site), an accidental
22482        // `Option::as_ref()` projection (`self.retries.as_ref()` would
22483        // also type-check but return `Option<&u32>`), or a one-arm-
22484        // only accessor that reads `Some(*n)` in the Some arm but
22485        // reads a fresh `Default::default()` (`0_u32`) in the None
22486        // arm.
22487        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
22488            let p = MeshPolicy {
22489                retries,
22490                ..MeshPolicy::default()
22491            };
22492            let first = p.retries();
22493            let second = p.retries();
22494            assert_eq!(
22495                first, second,
22496                "MeshPolicy::retries must be idempotent — two \
22497                 successive calls on the same &self must return the \
22498                 same Option<u32>",
22499            );
22500            assert_eq!(
22501                first, retries,
22502                "MeshPolicy::retries must return :politicas :retries \
22503                 verbatim by copy — got {first:?}, expected {retries:?}",
22504            );
22505        }
22506    }
22507
22508    #[test]
22509    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
22510        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
22511        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
22512        // return the `:politicas :timeout` typed [`Duration`] verbatim
22513        // as an `Option<Duration>`, byte-equal to the raw field access
22514        // across every representative value in the accept-set — `None`
22515        // (cluster default applies — typically the gateway class's
22516        // implementation-side per-request wall-clock cap the caixa-mesh
22517        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
22518        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
22519        // set the surrounding `AplicacaoSpec::validate_politicas` gate
22520        // carves out on the sibling `PolicyTimeoutZero` /
22521        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
22522        // (the upper boundary the same gate carves out on the sibling
22523        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
22524        // (a past-the-guard sentinel that pins the accessor doesn't
22525        // perform a silent bounds-collapse into `None` on the zero-
22526        // Duration arm — validate rejects zero but the accessor must
22527        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
22528        // past-the-guard sentinel that pins the accessor doesn't
22529        // perform a silent bounds-collapse at the return path).
22530        //
22531        // Sibling of the peer per-`:politicas`
22532        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
22533        // `Option<u32>` optional-scalar axis and the peer per-
22534        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
22535        // pin on the sibling `Option<bool>` optional-scalar axis,
22536        // extended onto the peer per-`:politicas` `Option<Duration>`
22537        // shape — third `Option<Copy-T>`-return accessor on the M3
22538        // mesh-slot family. Pins against a future silent detour that
22539        // re-derived the per-call cap from a peer axis (an accidental
22540        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
22541        // read the breaker's rolling-window duration as a per-call
22542        // deadline), a `None → Some(Duration::MAX)` cluster-default
22543        // projection (which would silently re-introduce the
22544        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
22545        // blocking" arm at the emit boundary), or a bounds-collapsing
22546        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
22547        // (the `AplicacaoSpec::validate` gate owns the bounds; the
22548        // accessor must ship the raw slot verbatim so a validate-time
22549        // gate regression surfaces at the emit boundary rather than
22550        // being silently absorbed).
22551        for timeout in [
22552            None,
22553            Some(Duration::from_millis(1)),
22554            Some(POLICY_TIMEOUT_MAX),
22555            Some(Duration::ZERO),
22556            Some(Duration::MAX),
22557        ] {
22558            let p = MeshPolicy {
22559                timeout,
22560                ..MeshPolicy::default()
22561            };
22562            assert_eq!(
22563                p.timeout(),
22564                timeout,
22565                "MeshPolicy::timeout must return :politicas :timeout \
22566                 verbatim (got {:?}, expected {timeout:?})",
22567                p.timeout(),
22568            );
22569            assert_eq!(
22570                p.timeout(),
22571                p.timeout,
22572                "MeshPolicy::timeout must byte-equal the raw .timeout \
22573                 field access across every value in the accept-set",
22574            );
22575        }
22576    }
22577
22578    #[test]
22579    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
22580        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
22581        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
22582        // field access. Structurally: toggling ONLY the `timeout` slot
22583        // on an otherwise-default MeshPolicy must flip `is_empty()`
22584        // from `true` (all-`None`) to `false` (one axis carries a
22585        // value); the flip must be observed for every value in the
22586        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
22587        // gate accepts (`Some(Duration::from_millis(1))`,
22588        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
22589        // reads "any axis carries a value" — not "any axis carries a
22590        // value the validate gate accepts" — the same non-collapsing
22591        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
22592        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22593        //
22594        // Pins against a future silent detour that re-derived the
22595        // emptiness predicate off a peer axis (an accidental
22596        // `.rate_limit.is_none()`-only chain that dropped the
22597        // `timeout` arm entirely), a `timeout == Some(_)` collapse
22598        // that key-off a validate-gate-clamped bounds check (which
22599        // would silently classify a past-the-guard `Some(Duration::MAX)`
22600        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
22601        // check), or an accessor-side detour that no longer names the
22602        // substrate-primitive typed dispatch.
22603        //
22604        // Sibling of the peer per-`:politicas`
22605        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
22606        // the sibling `Option<u32>` optional-scalar axis and the peer
22607        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
22608        // accessor-composition pin on the sibling `Option<bool>`
22609        // optional-scalar axis — same "the emptiness predicate must
22610        // route through the substrate-primitive typed dispatch"
22611        // discipline extended onto the peer per-`:politicas`
22612        // `Option<Duration>` axis.
22613        let empty = MeshPolicy::default();
22614        assert!(
22615            empty.is_empty(),
22616            "MeshPolicy::default() must be is_empty() — every axis \
22617             defaults to None",
22618        );
22619        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
22620            let p = MeshPolicy {
22621                timeout,
22622                ..MeshPolicy::default()
22623            };
22624            assert!(
22625                !p.is_empty(),
22626                "MeshPolicy::is_empty must return false when \
22627                 :timeout is {timeout:?} — the emptiness \
22628                 predicate reads \"any axis carries a value\", not \
22629                 \"any axis carries a value the validate gate \
22630                 accepts\"",
22631            );
22632            assert_eq!(
22633                p.timeout().is_none(),
22634                p.is_empty(),
22635                "when :timeout is the only set axis, is_empty() \
22636                 must equal timeout().is_none() — the accessor and \
22637                 the emptiness predicate must route through the same \
22638                 substrate-primitive typed dispatch on the :timeout \
22639                 arm",
22640            );
22641        }
22642    }
22643
22644    #[test]
22645    fn mesh_policy_timeout_projects_option_duration_by_copy() {
22646        // The by-copy pin: [`MeshPolicy::timeout`] returns
22647        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
22648        // and the accessor must return by value, not by reference.
22649        // Sibling of the peer per-`:politicas`
22650        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
22651        // sibling `Option<u32>` optional-scalar axis and the peer
22652        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
22653        // by-copy pin on the sibling `Option<bool>` optional-scalar
22654        // axis, extended onto the peer per-`:politicas`
22655        // `Option<Duration>` copy-invariant shape — the accessor's
22656        // returned `Option<Duration>` must outlive `&self` (multiple
22657        // calls must return equal values from a dropped-`&self`
22658        // copy, since the returned Option carries no borrow), and
22659        // calling the accessor twice on the same MeshPolicy must
22660        // yield the same `Option<Duration>` verbatim (idempotent, no
22661        // side effects on `&self`).
22662        //
22663        // Pins against a future silent detour that returned
22664        // `Option<&Duration>` (which would type-check but silently
22665        // break every downstream caller — [`crate::render::single_field_overlay`]'s
22666        // first parameter is `Option<T: Clone>`, and `&Duration`
22667        // would fold to a detached copy at the call site), an
22668        // accidental `Option::as_ref()` projection
22669        // (`self.timeout.as_ref()` would also type-check but return
22670        // `Option<&Duration>`), or a one-arm-only accessor that
22671        // reads `Some(*d)` in the Some arm but reads a fresh
22672        // `Default::default()` (`Duration::ZERO`) in the None arm
22673        // (which would silently re-classify every unset `:timeout`
22674        // as the `PolicyTimeoutZero`-refused zero-Duration value at
22675        // the accessor boundary).
22676        for timeout in [
22677            None,
22678            Some(Duration::from_millis(1)),
22679            Some(POLICY_TIMEOUT_MAX),
22680            Some(Duration::ZERO),
22681            Some(Duration::MAX),
22682        ] {
22683            let p = MeshPolicy {
22684                timeout,
22685                ..MeshPolicy::default()
22686            };
22687            let first = p.timeout();
22688            let second = p.timeout();
22689            assert_eq!(
22690                first, second,
22691                "MeshPolicy::timeout must be idempotent — two \
22692                 successive calls on the same &self must return the \
22693                 same Option<Duration>",
22694            );
22695            assert_eq!(
22696                first, timeout,
22697                "MeshPolicy::timeout must return :politicas :timeout \
22698                 verbatim by copy — got {first:?}, expected {timeout:?}",
22699            );
22700        }
22701    }
22702
22703    #[test]
22704    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
22705        // The canonical per-`:politicas` `:rate-limit` Envoy-
22706        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
22707        // [`MeshPolicy::rate_limit`] must return the `:politicas
22708        // :rate-limit` typed [`RateLimit`] verbatim as an
22709        // `Option<RateLimit>`, byte-equal to the raw field access
22710        // across every representative value in the accept-set — `None`
22711        // (cluster default applies — no per-Aplicacao rate declaration,
22712        // the gateway-class per-listener default arm the future caixa-
22713        // mesh `local_rate_limit_overlay` emitter documents),
22714        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
22715        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
22716        // accept-set the surrounding
22717        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22718        // sibling `PolicyRateLimitZero` refusal, paired with the
22719        // canonical-window "1 second" arm of the three-unit
22720        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
22721        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
22722        // (the upper boundary the same gate carves out on the sibling
22723        // `PolicyRateLimitExceedsCap` refusal, paired with the
22724        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
22725        // (a past-the-guard sentinel that pins the accessor doesn't
22726        // perform a silent bounds-collapse into `None` on the
22727        // zero-rate/zero-window arm — validate rejects zero but the
22728        // accessor must ship the raw slot verbatim so a validate-time
22729        // gate regression surfaces at the emit boundary rather than
22730        // being silently absorbed), and
22731        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
22732        // (a past-the-guard sentinel that pins the accessor doesn't
22733        // perform a silent bounds-collapse at the return path).
22734        //
22735        // First `Option<Copy-composite-T>`-return accessor pin on the
22736        // M3 mesh-slot family (peer of the sibling per-`:politicas`
22737        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
22738        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
22739        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
22740        // Copy accessor pins, extended onto the peer per-`:politicas`
22741        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
22742        // and the accessor returns by value). Pins against a future
22743        // silent detour that re-derived the rate declaration from a
22744        // peer axis (an accidental
22745        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
22746        // collapse that read the breaker's trip threshold + rolling
22747        // window as a rate declaration), a `None → Some(default())`
22748        // cluster-default projection (which would silently re-
22749        // introduce a "cluster default is 0/s" arm the emit boundary
22750        // would take as "declared but inert" — the canonical
22751        // declared-but-inert footgun the sibling
22752        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
22753        // amplification-shape axis), a bounds-collapsing accessor
22754        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
22755        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
22756        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
22757        // accessor must ship the raw slot verbatim), or a
22758        // by-reference detour (`Option<&RateLimit>`) that broke every
22759        // downstream consumer keying off `Option<RateLimit>` by-copy.
22760        for rl in [
22761            None,
22762            Some(RateLimit {
22763                rate: 1,
22764                window: Duration::from_secs(1),
22765            }),
22766            Some(RateLimit {
22767                rate: POLICY_RATE_LIMIT_MAX,
22768                window: Duration::from_secs(3600),
22769            }),
22770            Some(RateLimit {
22771                rate: 0,
22772                window: Duration::ZERO,
22773            }),
22774            Some(RateLimit {
22775                rate: u32::MAX,
22776                window: Duration::MAX,
22777            }),
22778        ] {
22779            let p = MeshPolicy {
22780                rate_limit: rl,
22781                ..MeshPolicy::default()
22782            };
22783            assert_eq!(
22784                p.rate_limit(),
22785                rl,
22786                "MeshPolicy::rate_limit must return :politicas :rate-limit \
22787                 verbatim (got {:?}, expected {rl:?})",
22788                p.rate_limit(),
22789            );
22790            assert_eq!(
22791                p.rate_limit(),
22792                p.rate_limit,
22793                "MeshPolicy::rate_limit must byte-equal the raw \
22794                 .rate_limit field access across every value in the \
22795                 accept-set",
22796            );
22797        }
22798    }
22799
22800    #[test]
22801    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
22802        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
22803        // must key off [`MeshPolicy::rate_limit`], not the raw
22804        // `.rate_limit` field access. Structurally: toggling ONLY the
22805        // `rate_limit` slot on an otherwise-default MeshPolicy must
22806        // flip `is_empty()` from `true` (all-`None`) to `false` (one
22807        // axis carries a value); the flip must be observed for every
22808        // representative value in the accept-set the surrounding
22809        // [`AplicacaoSpec::validate_politicas`] gate accepts
22810        // (`Some(RateLimit { rate: 1, window: 1s })`,
22811        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
22812        // since the emptiness semantic reads "any axis carries a
22813        // value" — not "any axis carries a value the validate gate
22814        // accepts" — the same non-collapsing shape the peer M2
22815        // [`crate::LimitsSpec::is_empty`] /
22816        // [`crate::BehaviorSpec::is_empty`] predicates carry.
22817        //
22818        // Pins against a future silent detour that re-derived the
22819        // emptiness predicate off a peer axis (an accidental
22820        // `.timeout.is_none()`-only chain that dropped the
22821        // `rate_limit` arm entirely — the last unlifted inline field
22822        // access on `is_empty` before this lift), a `rate_limit ==
22823        // Some(_)` collapse that key-off a validate-gate-clamped
22824        // bounds check (which would silently classify a past-the-
22825        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
22826        // because it fails the value-shape gate), or an accessor-
22827        // side detour that no longer names the substrate-primitive
22828        // typed dispatch.
22829        //
22830        // Fourth "the emptiness predicate must route through the
22831        // substrate-primitive typed dispatch" composition pin on the
22832        // M3 mesh-slot family — closes the last unlifted composition
22833        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22834        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22835        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22836        // 7073d0f is_empty-composition pins on the sibling primitive-
22837        // Copy axes, extended onto the peer per-`:politicas`
22838        // composite-Copy `Option<RateLimit>` axis).
22839        let empty = MeshPolicy::default();
22840        assert!(
22841            empty.is_empty(),
22842            "MeshPolicy::default() must be is_empty() — every axis \
22843             defaults to None",
22844        );
22845        for rl in [
22846            RateLimit {
22847                rate: 1,
22848                window: Duration::from_secs(1),
22849            },
22850            RateLimit {
22851                rate: POLICY_RATE_LIMIT_MAX,
22852                window: Duration::from_secs(3600),
22853            },
22854        ] {
22855            let p = MeshPolicy {
22856                rate_limit: Some(rl),
22857                ..MeshPolicy::default()
22858            };
22859            assert!(
22860                !p.is_empty(),
22861                "MeshPolicy::is_empty must return false when \
22862                 :rate-limit is {rl:?} — the emptiness predicate \
22863                 reads \"any axis carries a value\", not \"any axis \
22864                 carries a value the validate gate accepts\"",
22865            );
22866            assert_eq!(
22867                p.rate_limit().is_none(),
22868                p.is_empty(),
22869                "when :rate-limit is the only set axis, is_empty() \
22870                 must equal rate_limit().is_none() — the accessor \
22871                 and the emptiness predicate must route through the \
22872                 same substrate-primitive typed dispatch on the \
22873                 :rate-limit arm",
22874            );
22875        }
22876    }
22877
22878    #[test]
22879    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
22880        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22881        // `:rate-limit` value-shape gate must key off
22882        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
22883        // field bind. Structurally: a `MeshPolicy` whose only set
22884        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
22885        // the `PolicyRateLimitZero` refusal exactly, and the same
22886        // MeshPolicy with the rate at the canonical lower boundary
22887        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
22888        // The pair jointly pins the accessor + validate-gate
22889        // composition: any future silent detour that had the accessor
22890        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
22891        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
22892        // silently absorb the `PolicyRateLimitZero` refusal at the
22893        // accessor boundary — the composition pin catches that at
22894        // caixa-core build time.
22895        //
22896        // Sibling of the peer [`validate_politicas`]
22897        // `:mtls-required` / `:retries` / `:timeout` composition pins
22898        // on the sibling primitive-Copy optional-scalar axes — same
22899        // "the validate / shape-gate predicate must route through the
22900        // substrate-primitive typed dispatch" discipline extended
22901        // onto the peer per-`:politicas` composite-Copy
22902        // `Option<RateLimit>` axis. Second composition-with-accessor
22903        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
22904        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
22905        let mut spec = three_member_spec();
22906        spec.politicas = MeshPolicy {
22907            rate_limit: Some(RateLimit {
22908                rate: 0,
22909                window: Duration::from_secs(1),
22910            }),
22911            ..MeshPolicy::default()
22912        };
22913        assert!(
22914            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
22915            "validate_politicas must reject rate == 0 with \
22916             PolicyRateLimitZero — the accessor and the validate gate \
22917             must route through the same substrate-primitive typed \
22918             dispatch on the :rate-limit zero-floor arm",
22919        );
22920        spec.politicas = MeshPolicy {
22921            rate_limit: Some(RateLimit {
22922                rate: 1,
22923                window: Duration::from_secs(1),
22924            }),
22925            ..MeshPolicy::default()
22926        };
22927        assert!(
22928            spec.validate().is_ok(),
22929            "validate_politicas must accept rate == 1 (the canonical \
22930             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
22931             set) with a canonical 1s window",
22932        );
22933    }
22934
22935    #[test]
22936    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
22937        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
22938        // `outlier_detection`-mesh consecutive-failure-ejection scalar
22939        // pin: [`MeshPolicy::circuit_breaker`] must return the
22940        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
22941        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
22942        // raw field access across every representative value in the
22943        // accept-set — `None` (cluster default applies — no
22944        // per-Aplicacao breaker declaration, the gateway-class per-
22945        // listener default arm the future caixa-mesh
22946        // `outlier_detection_overlay` emitter documents),
22947        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
22948        // (the lower boundary of the accept-set the surrounding
22949        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22950        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
22951        // refusals),
22952        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
22953        // (the upper boundary the same gate carves out on the sibling
22954        // `PolicyBreakerMaxFailuresExceedsCap` /
22955        // `PolicyBreakerWindowExceedsCap` refusals),
22956        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
22957        // (a past-the-guard sentinel that pins the accessor doesn't
22958        // perform a silent bounds-collapse into `None` on the
22959        // zero-failures/zero-window arm — validate rejects zero but
22960        // the accessor must ship the raw slot verbatim so a validate-
22961        // time gate regression surfaces at the emit boundary rather
22962        // than being silently absorbed), and
22963        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
22964        // (a past-the-guard sentinel that pins the accessor doesn't
22965        // perform a silent bounds-collapse at the return path).
22966        //
22967        // Second `Option<Copy-composite-T>`-return accessor pin on the
22968        // M3 mesh-slot family (peer of the sibling per-`:politicas`
22969        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
22970        // composite-Copy accessor pin, and of the sibling per-
22971        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
22972        // [`MeshPolicy::retries`] bdfb399 /
22973        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
22974        // accessor pins). Pins against a future silent detour that
22975        // re-derived the breaker declaration from a peer axis (an
22976        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
22977        // collapse that read the rate-limit's bucket capacity + refill
22978        // period as a breaker declaration), a `None → Some(default())`
22979        // cluster-default projection (which would silently re-
22980        // introduce the `PolicyBreakerZeroFailures` /
22981        // `PolicyBreakerZeroWindow` refusal cases at the emit
22982        // boundary), a bounds-collapsing accessor that clamped
22983        // `cb.max_failures` through
22984        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
22985        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
22986        // [`AplicacaoSpec::validate`] gate owns the bounds; the
22987        // accessor must ship the raw slot verbatim), or a
22988        // by-reference detour (`Option<&CircuitBreaker>`) that broke
22989        // every downstream consumer keying off `Option<CircuitBreaker>`
22990        // by-copy.
22991        for cb in [
22992            None,
22993            Some(CircuitBreaker {
22994                max_failures: 1,
22995                window: Duration::from_millis(1),
22996            }),
22997            Some(CircuitBreaker {
22998                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22999                window: POLICY_BREAKER_WINDOW_MAX,
23000            }),
23001            Some(CircuitBreaker {
23002                max_failures: 0,
23003                window: Duration::ZERO,
23004            }),
23005            Some(CircuitBreaker {
23006                max_failures: u32::MAX,
23007                window: Duration::MAX,
23008            }),
23009        ] {
23010            let p = MeshPolicy {
23011                circuit_breaker: cb,
23012                ..MeshPolicy::default()
23013            };
23014            assert_eq!(
23015                p.circuit_breaker(),
23016                cb,
23017                "MeshPolicy::circuit_breaker must return :politicas \
23018                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
23019                p.circuit_breaker(),
23020            );
23021            assert_eq!(
23022                p.circuit_breaker(),
23023                p.circuit_breaker,
23024                "MeshPolicy::circuit_breaker must byte-equal the raw \
23025                 .circuit_breaker field access across every value in \
23026                 the accept-set",
23027            );
23028        }
23029    }
23030
23031    #[test]
23032    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
23033        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
23034        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
23035        // `.circuit_breaker` field access. Structurally: toggling ONLY
23036        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
23037        // must flip `is_empty()` from `true` (all-`None`) to `false`
23038        // (one axis carries a value); the flip must be observed for
23039        // every representative value in the accept-set the surrounding
23040        // [`AplicacaoSpec::validate_politicas`] gate accepts
23041        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
23042        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
23043        // since the emptiness semantic reads "any axis carries a
23044        // value" — not "any axis carries a value the validate gate
23045        // accepts" — the same non-collapsing shape the peer M2
23046        // [`crate::LimitsSpec::is_empty`] /
23047        // [`crate::BehaviorSpec::is_empty`] predicates carry.
23048        //
23049        // Pins against a future silent detour that re-derived the
23050        // emptiness predicate off a peer axis (an accidental
23051        // `.rate_limit.is_none()`-only chain that dropped the
23052        // `circuit_breaker` arm entirely — the last unlifted inline
23053        // field access on `is_empty` before this lift), a
23054        // `circuit_breaker == Some(_)` collapse that key-off a
23055        // validate-gate-clamped bounds check (which would silently
23056        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
23057        // 0, window: 0s })` as empty because it fails the value-shape
23058        // gate), or an accessor-side detour that no longer names the
23059        // substrate-primitive typed dispatch.
23060        //
23061        // Fifth "the emptiness predicate must route through the
23062        // substrate-primitive typed dispatch" composition pin on the
23063        // M3 mesh-slot family — closes the last unlifted composition
23064        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
23065        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
23066        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
23067        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
23068        // composition pins on the sibling primitive-Copy + composite-
23069        // Copy axes, extended onto the peer per-`:politicas`
23070        // composite-Copy `Option<CircuitBreaker>` axis).
23071        let empty = MeshPolicy::default();
23072        assert!(
23073            empty.is_empty(),
23074            "MeshPolicy::default() must be is_empty() — every axis \
23075             defaults to None",
23076        );
23077        for cb in [
23078            CircuitBreaker {
23079                max_failures: 1,
23080                window: Duration::from_millis(1),
23081            },
23082            CircuitBreaker {
23083                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
23084                window: POLICY_BREAKER_WINDOW_MAX,
23085            },
23086        ] {
23087            let p = MeshPolicy {
23088                circuit_breaker: Some(cb),
23089                ..MeshPolicy::default()
23090            };
23091            assert!(
23092                !p.is_empty(),
23093                "MeshPolicy::is_empty must return false when \
23094                 :circuit-breaker is {cb:?} — the emptiness predicate \
23095                 reads \"any axis carries a value\", not \"any axis \
23096                 carries a value the validate gate accepts\"",
23097            );
23098            assert_eq!(
23099                p.circuit_breaker().is_none(),
23100                p.is_empty(),
23101                "when :circuit-breaker is the only set axis, \
23102                 is_empty() must equal circuit_breaker().is_none() — \
23103                 the accessor and the emptiness predicate must route \
23104                 through the same substrate-primitive typed dispatch \
23105                 on the :circuit-breaker arm",
23106            );
23107        }
23108    }
23109
23110    #[test]
23111    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
23112        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23113        // `:circuit-breaker` value-shape gate must key off
23114        // [`MeshPolicy::circuit_breaker`], not the raw
23115        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
23116        // whose only set axis is a `Some(CircuitBreaker { max_failures:
23117        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
23118        // refusal exactly, and the same MeshPolicy with the breaker at
23119        // the canonical lower boundary
23120        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
23121        // pass validate. The pair jointly pins the accessor +
23122        // validate-gate composition: any future silent detour that had
23123        // the accessor omit the `Some(CircuitBreaker { max_failures:
23124        // 0, .. })` arm (a
23125        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
23126        // collapse) would silently absorb the
23127        // `PolicyBreakerZeroFailures` refusal at the accessor
23128        // boundary — the composition pin catches that at caixa-core
23129        // build time.
23130        //
23131        // Sibling of the peer [`validate_politicas`]
23132        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
23133        // composition pins on the sibling primitive-Copy + composite-
23134        // Copy optional-scalar axes — same "the validate / shape-gate
23135        // predicate must route through the substrate-primitive typed
23136        // dispatch" discipline extended onto the peer per-`:politicas`
23137        // composite-Copy `Option<CircuitBreaker>` axis. Second
23138        // composition-with-accessor pin on the M3 mesh-slot
23139        // `Option<CircuitBreaker>` arm alongside the
23140        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
23141        let mut spec = three_member_spec();
23142        spec.politicas = MeshPolicy {
23143            circuit_breaker: Some(CircuitBreaker {
23144                max_failures: 0,
23145                window: Duration::from_millis(1),
23146            }),
23147            ..MeshPolicy::default()
23148        };
23149        assert!(
23150            matches!(
23151                spec.validate(),
23152                Err(AplicacaoError::PolicyBreakerZeroFailures)
23153            ),
23154            "validate_politicas must reject max_failures == 0 with \
23155             PolicyBreakerZeroFailures — the accessor and the validate \
23156             gate must route through the same substrate-primitive \
23157             typed dispatch on the :circuit-breaker zero-floor arm",
23158        );
23159        spec.politicas = MeshPolicy {
23160            circuit_breaker: Some(CircuitBreaker {
23161                max_failures: 1,
23162                window: Duration::from_millis(1),
23163            }),
23164            ..MeshPolicy::default()
23165        };
23166        assert!(
23167            spec.validate().is_ok(),
23168            "validate_politicas must accept a CircuitBreaker at the \
23169             canonical lower boundary (max_failures = 1, window = \
23170             1ms) — the accessor and the validate gate must route \
23171             through the same substrate-primitive typed dispatch on \
23172             the :circuit-breaker arm",
23173        );
23174    }
23175
23176    #[test]
23177    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
23178        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
23179        // Envoy-outlier-detection trip-threshold scalar pin:
23180        // [`CircuitBreaker::max_failures`] must return the
23181        // `:politicas :circuit-breaker :max-failures` typed `u32`
23182        // verbatim, byte-equal to the raw field access across every
23183        // representative value in the accept-set — `1` (the lower
23184        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
23185        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
23186        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
23187        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
23188        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
23189        // refusal), `0` (a past-the-guard sentinel that pins the accessor
23190        // doesn't perform a silent bounds-collapse into `1` on the zero
23191        // arm — validate rejects zero but the accessor must ship the
23192        // raw slot verbatim so a validate-time gate regression surfaces
23193        // at the emit boundary rather than being silently absorbed),
23194        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
23195        // doesn't perform a silent bounds-collapse through
23196        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
23197        //
23198        // First sub-struct required-scalar accessor pin on the M3
23199        // mesh-slot family — sibling in shape to the peer per-`:membros`
23200        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
23201        // (a40b0e3) required-`String`-carry accessor pins and the peer
23202        // per-`:contratos` [`WitContract::source`] /
23203        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
23204        // accessor pins, extended onto the peer per-`CircuitBreaker`
23205        // required-`u32` scalar-value axis. Pins against a future silent
23206        // detour that re-derived the trip threshold from a peer axis (an
23207        // accidental `self.window.as_secs() as u32` collapse that read
23208        // the breaker's rolling-window duration as a failure count), a
23209        // `0 → 1` cluster-default projection (which would silently absorb
23210        // the `PolicyBreakerZeroFailures` refusal case at the accessor
23211        // boundary), or a bounds-collapsing accessor that clamped the
23212        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
23213        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
23214        // must ship the raw slot verbatim).
23215        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
23216            let cb = CircuitBreaker {
23217                max_failures,
23218                window: Duration::from_secs(60),
23219            };
23220            assert_eq!(
23221                cb.max_failures(),
23222                max_failures,
23223                "CircuitBreaker::max_failures must return :politicas \
23224                 :circuit-breaker :max-failures verbatim (got {}, \
23225                 expected {max_failures})",
23226                cb.max_failures(),
23227            );
23228            assert_eq!(
23229                cb.max_failures(),
23230                cb.max_failures,
23231                "CircuitBreaker::max_failures must byte-equal the raw \
23232                 .max_failures field access across every value in the \
23233                 u32 accept-set",
23234            );
23235        }
23236    }
23237
23238    #[test]
23239    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
23240        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23241        // `:circuit-breaker :max-failures` zero-floor arm must key off
23242        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
23243        // field access. Structurally: a `CircuitBreaker { max_failures:
23244        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
23245        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
23246        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
23247        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
23248        // pass validate. The pair jointly pins the accessor +
23249        // validate-gate composition: any future silent detour that had
23250        // the accessor return a fresh `1` on the zero arm (a
23251        // `.max_failures().max(1)` collapse) would silently absorb the
23252        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
23253        // and the validate gate would accept a struct-literal
23254        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
23255        // catches that at caixa-core build time.
23256        //
23257        // Peer of the sibling per-`:politicas`
23258        // [`MeshPolicy::mtls_required`] (c0110f1) /
23259        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
23260        // (7073d0f) accessor-composition pins on the sibling optional-
23261        // scalar axes — same "the validate / shape-gate predicate must
23262        // route through the substrate-primitive typed dispatch"
23263        // discipline extended onto the peer per-`CircuitBreaker`
23264        // required-scalar composition axis.
23265        let mut spec = three_member_spec();
23266        spec.politicas = MeshPolicy {
23267            circuit_breaker: Some(CircuitBreaker {
23268                max_failures: 0,
23269                window: Duration::from_secs(60),
23270            }),
23271            ..MeshPolicy::default()
23272        };
23273        assert!(
23274            matches!(
23275                spec.validate(),
23276                Err(AplicacaoError::PolicyBreakerZeroFailures)
23277            ),
23278            "validate_politicas must reject max_failures == 0 with \
23279             PolicyBreakerZeroFailures — the accessor and the validate \
23280             gate must route through the same substrate-primitive typed \
23281             dispatch on the :max-failures zero-floor arm",
23282        );
23283        spec.politicas = MeshPolicy {
23284            circuit_breaker: Some(CircuitBreaker {
23285                max_failures: 1,
23286                window: Duration::from_secs(60),
23287            }),
23288            ..MeshPolicy::default()
23289        };
23290        assert!(
23291            spec.validate().is_ok(),
23292            "validate_politicas must accept max_failures == 1 (the \
23293             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
23294             accept-set)",
23295        );
23296    }
23297
23298    #[test]
23299    fn circuit_breaker_max_failures_projects_u32_by_copy() {
23300        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
23301        // `u32` by copy — `u32` is `Copy` and the accessor must return
23302        // by value, not by reference. Peer of the sibling
23303        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
23304        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
23305        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
23306        // optional-scalar axes, extended onto the peer
23307        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
23308        // the accessor's returned `u32` must outlive `&self` (multiple
23309        // calls must return equal values from a dropped-`&self` copy,
23310        // since the returned scalar carries no borrow), and calling
23311        // the accessor twice on the same CircuitBreaker must yield the
23312        // same `u32` verbatim (idempotent, no side effects on `&self`).
23313        //
23314        // Pins against a future silent detour that returned `&u32`
23315        // (which would type-check but silently break every downstream
23316        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
23317        // first parameter is `u32`, and `&u32` would fold to a detached
23318        // copy at the call site with a `*` deref the sibling accessors
23319        // don't need), an accidental `.max_failures.wrapping_add(0)`
23320        // detour that returned a fresh copy through an arithmetic
23321        // no-op (breaking a future `const fn` regression), or a
23322        // one-arm-only accessor that returned a saturating value on
23323        // some sentinel input (breaking the pass-through invariant the
23324        // sibling required-scalar accessors carry).
23325        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
23326            let cb = CircuitBreaker {
23327                max_failures,
23328                window: Duration::from_secs(60),
23329            };
23330            let first = cb.max_failures();
23331            let second = cb.max_failures();
23332            assert_eq!(
23333                first, second,
23334                "CircuitBreaker::max_failures must be idempotent — two \
23335                 successive calls on the same &self must return the \
23336                 same u32",
23337            );
23338            assert_eq!(
23339                first, max_failures,
23340                "CircuitBreaker::max_failures must return :politicas \
23341                 :circuit-breaker :max-failures verbatim by copy — \
23342                 got {first}, expected {max_failures}",
23343            );
23344        }
23345    }
23346
23347    #[test]
23348    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
23349        // The canonical per-`:politicas :circuit-breaker` `:window`
23350        // Envoy-outlier-detection rolling-observation-interval scalar
23351        // pin: [`CircuitBreaker::window`] must return the
23352        // `:politicas :circuit-breaker :window` typed `Duration`
23353        // verbatim, byte-equal to the raw field access across every
23354        // representative value in the accept-set — `Duration::from_millis(1)`
23355        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
23356        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
23357        // gate carves out on the sibling `PolicyBreakerZeroWindow`
23358        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
23359        // same gate carves out on the sibling
23360        // `PolicyBreakerWindowExceedsCap` refusal),
23361        // `Duration::ZERO` (a past-the-guard sentinel that pins the
23362        // accessor doesn't perform a silent bounds-collapse into
23363        // `Duration::from_millis(1)` on the zero arm — validate rejects
23364        // zero but the accessor must ship the raw slot verbatim so a
23365        // validate-time gate regression surfaces at the emit boundary
23366        // rather than being silently absorbed),
23367        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
23368        // far above the 1h cap — that pins the accessor doesn't perform
23369        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
23370        // at the return path).
23371        //
23372        // Second sub-struct required-scalar accessor pin on the M3
23373        // mesh-slot family — sibling in shape to the just-landed
23374        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
23375        // (3a74062) required-`u32` accessor pin on the peer
23376        // per-`CircuitBreaker` required-axis, extended onto the
23377        // per-sub-struct required-`Duration` axis. Pins against a
23378        // future silent detour that re-derived the observation window
23379        // from a peer axis (an accidental
23380        // `Duration::from_secs(self.max_failures as u64)` collapse that
23381        // read the breaker's trip count as an observation-interval
23382        // duration), a `Duration::ZERO → Duration::from_millis(1)`
23383        // cluster-default projection (which would silently absorb the
23384        // `PolicyBreakerZeroWindow` refusal case at the accessor
23385        // boundary), or a bounds-collapsing accessor that clamped the
23386        // return through `POLICY_BREAKER_WINDOW_MAX` (the
23387        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
23388        // must ship the raw slot verbatim).
23389        for window in [
23390            Duration::from_millis(1),
23391            POLICY_BREAKER_WINDOW_MAX,
23392            Duration::ZERO,
23393            Duration::from_secs(86_400),
23394        ] {
23395            let cb = CircuitBreaker {
23396                max_failures: 5,
23397                window,
23398            };
23399            assert_eq!(
23400                cb.window(),
23401                window,
23402                "CircuitBreaker::window must return :politicas \
23403                 :circuit-breaker :window verbatim (got {:?}, \
23404                 expected {window:?})",
23405                cb.window(),
23406            );
23407            assert_eq!(
23408                cb.window(),
23409                cb.window,
23410                "CircuitBreaker::window must byte-equal the raw \
23411                 .window field access across every value in the \
23412                 Duration accept-set",
23413            );
23414        }
23415    }
23416
23417    #[test]
23418    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
23419        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23420        // `:circuit-breaker :window` zero-floor arm must key off
23421        // [`CircuitBreaker::window`], not the raw `.window` field
23422        // access. Structurally: a `CircuitBreaker { window:
23423        // Duration::ZERO, .. }` embedded in a
23424        // `:politicas :circuit-breaker` slot must surface the
23425        // `PolicyBreakerZeroWindow` refusal exactly, and a
23426        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
23427        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
23428        // accept-set) must pass validate. The pair jointly pins the
23429        // accessor + validate-gate composition: any future silent
23430        // detour that had the accessor return a fresh
23431        // `Duration::from_millis(1)` on the zero arm (a
23432        // `.window().max(Duration::from_millis(1))` collapse) would
23433        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
23434        // accessor boundary and the validate gate would accept a
23435        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
23436        // — the composition pin catches that at caixa-core build time.
23437        //
23438        // Peer of the sibling per-`CircuitBreaker`
23439        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
23440        // pin on the peer required-scalar `:max-failures` axis — same
23441        // "the validate / shape-gate predicate must route through the
23442        // substrate-primitive typed dispatch" discipline extended onto
23443        // the peer per-`CircuitBreaker` required-`Duration` composition
23444        // axis.
23445        let mut spec = three_member_spec();
23446        spec.politicas = MeshPolicy {
23447            circuit_breaker: Some(CircuitBreaker {
23448                max_failures: 5,
23449                window: Duration::ZERO,
23450            }),
23451            ..MeshPolicy::default()
23452        };
23453        assert!(
23454            matches!(
23455                spec.validate(),
23456                Err(AplicacaoError::PolicyBreakerZeroWindow)
23457            ),
23458            "validate_politicas must reject window == Duration::ZERO \
23459             with PolicyBreakerZeroWindow — the accessor and the \
23460             validate gate must route through the same substrate-\
23461             primitive typed dispatch on the :window zero-floor arm",
23462        );
23463        spec.politicas = MeshPolicy {
23464            circuit_breaker: Some(CircuitBreaker {
23465                max_failures: 5,
23466                window: Duration::from_millis(1),
23467            }),
23468            ..MeshPolicy::default()
23469        };
23470        assert!(
23471            spec.validate().is_ok(),
23472            "validate_politicas must accept window == \
23473             Duration::from_millis(1) (the lower boundary of the \
23474             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
23475        );
23476    }
23477
23478    #[test]
23479    fn circuit_breaker_window_projects_duration_by_copy() {
23480        // The by-copy pin: [`CircuitBreaker::window`] returns
23481        // `Duration` by copy — `Duration` is `Copy` and the accessor
23482        // must return by value, not by reference. Peer of the sibling
23483        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
23484        // (3a74062) by-copy pin on the peer required-scalar
23485        // `:max-failures` axis, extended onto the peer
23486        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
23487        // — the accessor's returned `Duration` must outlive `&self`
23488        // (multiple calls must return equal values from a
23489        // dropped-`&self` copy, since the returned scalar carries no
23490        // borrow), and calling the accessor twice on the same
23491        // CircuitBreaker must yield the same `Duration` verbatim
23492        // (idempotent, no side effects on `&self`).
23493        //
23494        // Pins against a future silent detour that returned
23495        // `&Duration` (which would type-check but silently break every
23496        // downstream `Duration`-by-value consumer —
23497        // [`crate::render::require_positive_canonical_bounded_duration`]'s
23498        // first parameter is `Duration`, and `&Duration` would fold to
23499        // a detached copy at the call site with a `*` deref the sibling
23500        // accessors don't need), an accidental `.window + Duration::ZERO`
23501        // detour that returned a fresh copy through an arithmetic
23502        // no-op (breaking a future `const fn` regression), or a
23503        // one-arm-only accessor that returned a saturating value on
23504        // some sentinel input (breaking the pass-through invariant the
23505        // sibling required-scalar accessors carry).
23506        for window in [
23507            Duration::from_millis(1),
23508            POLICY_BREAKER_WINDOW_MAX,
23509            Duration::ZERO,
23510            Duration::from_secs(86_400),
23511        ] {
23512            let cb = CircuitBreaker {
23513                max_failures: 5,
23514                window,
23515            };
23516            let first = cb.window();
23517            let second = cb.window();
23518            assert_eq!(
23519                first, second,
23520                "CircuitBreaker::window must be idempotent — two \
23521                 successive calls on the same &self must return the \
23522                 same Duration",
23523            );
23524            assert_eq!(
23525                first, window,
23526                "CircuitBreaker::window must return :politicas \
23527                 :circuit-breaker :window verbatim by copy — \
23528                 got {first:?}, expected {window:?}",
23529            );
23530        }
23531    }
23532
23533    #[test]
23534    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
23535        // Apex-identity pair-invariant pin composing both substrate-
23536        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
23537        // and [`WitContract::destination`] — at the emit-side call shape
23538        // every per-`(:de, :para)` CNP L4 port reader now takes. The
23539        // invariant, evaluated per-edge:
23540        //
23541        //   spec.port_for_destination(c.destination()) == expected_port
23542        //
23543        // where `expected_port` is `entrada.port` when
23544        // `c.destination() == entrada.destination()` and
23545        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
23546        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
23547        // pin on the per-`:entrada` axis — that pin encodes the apex
23548        // ingress L4 identity via `entrada.destination()`; this pin
23549        // encodes the per-edge L4 identity via `c.destination()`, and
23550        // both compose on the same substrate-primitive resolver so a
23551        // future refactor that silently split either accessor's apex
23552        // behavior surfaces at caixa-core build time.
23553        let mut spec = three_member_spec();
23554        if let Some(e) = spec.entrada.as_mut() {
23555            e.para = "cart".into();
23556            e.port = 8443;
23557        }
23558        let apex_contract = WitContract {
23559            de: "checkout".into(),
23560            para: "cart".into(),
23561            wit: "wasi:http/proxy".into(),
23562            endpoint: Some("/hello".into()),
23563            subject: None,
23564            slot: None,
23565        };
23566        assert_eq!(
23567            spec.port_for_destination(apex_contract.destination()),
23568            8443,
23569            "`spec.port_for_destination(c.destination())` must equal \
23570             `entrada.port` when the contract callee names the ingress \
23571             apex — the CNP per-edge L4 port and the HTTPRoute apex \
23572             backendRef port share this substrate-primitive resolver.",
23573        );
23574        let non_apex_contract = WitContract {
23575            de: "cart".into(),
23576            para: "payment".into(),
23577            wit: "wasi:http/proxy".into(),
23578            endpoint: Some("/charge".into()),
23579            subject: None,
23580            slot: None,
23581        };
23582        assert_eq!(
23583            spec.port_for_destination(non_apex_contract.destination()),
23584            DEFAULT_SERVICO_PORT,
23585            "`spec.port_for_destination(c.destination())` must fall back \
23586             to the substrate-canonical port floor when the contract \
23587             callee is not the ingress apex — the resolver's non-apex \
23588             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
23589        );
23590    }
23591
23592    #[test]
23593    fn membro_key_consts_are_lower_camel_case_shape() {
23594        // Shape-pin: every `MEMBRO_KEY_*` const must be a
23595        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23596        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23597        // leading capital, no whitespace / dots) — the canonical shape
23598        // the `#[serde(rename_all = "camelCase")]` derive produces on
23599        // [`Membro`]. A future flip to a non-camelCase attribute at
23600        // the derive surfaces both here (this test fails on the
23601        // stale-constant shape) and at
23602        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
23603        // fails on the mismatch between const and derive). Peer with
23604        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
23605        // on the sibling `SupervisorSpec` top-level axis.
23606        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
23607            assert!(
23608                !key.is_empty(),
23609                "MEMBRO_KEY_* must be non-empty (got {key:?})"
23610            );
23611            let first = key.chars().next().unwrap();
23612            assert!(
23613                first.is_ascii_lowercase(),
23614                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
23615                 (got {key:?}, leads with {first:?})",
23616            );
23617            assert!(
23618                key.chars().all(|c| c.is_ascii_alphanumeric()),
23619                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
23620                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23621            );
23622        }
23623    }
23624
23625    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
23626
23627    #[test]
23628    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
23629        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
23630        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
23631        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
23632        // keys the `#[serde(rename_all = "camelCase")]` attribute on
23633        // [`WitContract`] emits for the required-triad. The three
23634        // sibling payload-arm keys already pin under
23635        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
23636        // `STORE_FIELD_NAME` — pin all six alongside so a future
23637        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23638        // verbatim-field-name flip at the derive attribute (any of which
23639        // would silently break every downstream JSON consumer that
23640        // reaches for one of the six via `Value::get(...)`) surfaces
23641        // here as a build-time test failure at `aplicacao.rs`, not as an
23642        // apply-time `.get(<stale-canonical-const>)` returning `None`
23643        // far from the derive-attr drift's commit. Peer with the sibling
23644        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23645        // pin on the M3 `:membros` per-entry axis — same discipline the
23646        // `Membro` per-entry lift established, extended here to the
23647        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
23648        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
23649        // axis on the Aplicacao surface without a lifted serde-key peer.
23650        let c = WitContract {
23651            de: "cart".into(),
23652            para: "catalog".into(),
23653            wit: "wasi:http/proxy".into(),
23654            endpoint: Some("/lookup".into()),
23655            subject: None,
23656            slot: None,
23657        };
23658        let json = serde_json::to_string(&c).unwrap();
23659        for key in [
23660            crate::CONTRATO_KEY_DE,
23661            crate::CONTRATO_KEY_PARA,
23662            crate::CONTRATO_KEY_WIT,
23663            WitTarget::HTTP_FIELD_NAME,
23664        ] {
23665            let quoted = format!("\"{key}\"");
23666            assert!(
23667                json.contains(&quoted),
23668                "serialized WitContract must carry the lifted \
23669                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
23670                 {quoted} verbatim in the JSON emission (got: {json})",
23671            );
23672        }
23673
23674        // Pin the two remaining payload-arm keys by round-tripping a
23675        // `WitContract` under each payload-shape (pub-sub, store) — the
23676        // required-triad appears on every emission but the payload arms
23677        // only surface when their `Option<String>` field is `Some`.
23678        let pubsub = WitContract {
23679            de: "cart".into(),
23680            para: "events".into(),
23681            wit: "nats:pub-sub".into(),
23682            endpoint: None,
23683            subject: Some("orders.placed".into()),
23684            slot: None,
23685        };
23686        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
23687        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
23688        assert!(
23689            pubsub_json.contains(&pubsub_quoted),
23690            "serialized pub-sub WitContract must carry the lifted \
23691             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
23692             verbatim in the JSON emission (got: {pubsub_json})",
23693        );
23694        let store = WitContract {
23695            de: "cart".into(),
23696            para: "sessions".into(),
23697            wit: "wasi:keyvalue/store".into(),
23698            endpoint: None,
23699            subject: None,
23700            slot: Some("cart/$id".into()),
23701        };
23702        let store_json = serde_json::to_string(&store).unwrap();
23703        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
23704        assert!(
23705            store_json.contains(&store_quoted),
23706            "serialized store WitContract must carry the lifted \
23707             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
23708             verbatim in the JSON emission (got: {store_json})",
23709        );
23710    }
23711
23712    #[test]
23713    fn contrato_key_consts_are_pairwise_distinct() {
23714        // Cross-axis drift-detection pin: a future collapse of the six
23715        // canonical [`WitContract`] per-entry byte-strings onto the same
23716        // value (e.g. an accidental copy-paste flip of
23717        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
23718        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
23719        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
23720        // every downstream probe on one axis onto the sibling axis's
23721        // overlay entry and pass every propagation-probe test that
23722        // expected only the stale axis's value. Peer of the sibling
23723        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
23724        // widened here to the six-way axis the `WitContract`
23725        // required-triad + `WitTarget` payload-triad jointly cover.
23726        let all = [
23727            crate::CONTRATO_KEY_DE,
23728            crate::CONTRATO_KEY_PARA,
23729            crate::CONTRATO_KEY_WIT,
23730            WitTarget::HTTP_FIELD_NAME,
23731            WitTarget::PUBSUB_FIELD_NAME,
23732            WitTarget::STORE_FIELD_NAME,
23733        ];
23734        for (i, a) in all.iter().enumerate() {
23735            for b in all.iter().skip(i + 1) {
23736                assert_ne!(
23737                    a, b,
23738                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
23739                     must be pairwise-distinct canonical byte-sequences \
23740                     — got `{a}` == `{b}`",
23741                );
23742            }
23743        }
23744    }
23745
23746    #[test]
23747    fn contrato_key_consts_are_lower_camel_case_shape() {
23748        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
23749        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
23750        // byte-sequence (no `snake_case` underscores, no `kebab-case`
23751        // hyphens, no leading colon, no `PascalCase` leading capital, no
23752        // whitespace / dots) — the canonical shape the
23753        // `#[serde(rename_all = "camelCase")]` derive produces on
23754        // [`WitContract`]. A future flip to a non-camelCase attribute at
23755        // the derive surfaces both here (this test fails on the
23756        // stale-constant shape) and at
23757        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23758        // (that test fails on the mismatch between const and derive).
23759        // Peer with `membro_key_consts_are_lower_camel_case_shape`
23760        // (ce80ca0) on the sibling `Membro` per-entry axis.
23761        for key in [
23762            crate::CONTRATO_KEY_DE,
23763            crate::CONTRATO_KEY_PARA,
23764            crate::CONTRATO_KEY_WIT,
23765            WitTarget::HTTP_FIELD_NAME,
23766            WitTarget::PUBSUB_FIELD_NAME,
23767            WitTarget::STORE_FIELD_NAME,
23768        ] {
23769            assert!(
23770                !key.is_empty(),
23771                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
23772                 non-empty (got {key:?})"
23773            );
23774            let first = key.chars().next().unwrap();
23775            assert!(
23776                first.is_ascii_lowercase(),
23777                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
23778                 with an ASCII-lowercase byte (got {key:?}, leads with \
23779                 {first:?})",
23780            );
23781            assert!(
23782                key.chars().all(|c| c.is_ascii_alphanumeric()),
23783                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
23784                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
23785                 whitespace (got {key:?})",
23786            );
23787        }
23788    }
23789
23790    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
23791
23792    #[test]
23793    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
23794        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
23795        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
23796        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
23797        // name the exact camelCase JSON keys the
23798        // `#[serde(rename_all = "camelCase")]` attribute on
23799        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
23800        // pin that each canonical byte-sequence appears verbatim in the
23801        // JSON — a future accidental `rename_all = "snake_case"` /
23802        // `"kebab-case"` / verbatim-field-name flip at the derive
23803        // attribute (any of which would silently break every downstream
23804        // JSON consumer that reaches for one of the four consts via
23805        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
23806        // emitter's per-Aplicacao hostname/paths/port projection, the
23807        // future `app-operator` reconciler's per-Aplicacao ingress
23808        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
23809        // materializer's admission-time cross-check) surfaces here as
23810        // a build-time test failure at `aplicacao.rs`, not as an
23811        // apply-time `.get(<stale-canonical-const>)` returning `None`
23812        // far from the derive-attr drift's commit. Peer with the
23813        // sibling
23814        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23815        // (ca463a4) and
23816        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23817        // pins on the M3 collection-slot atom axes — same discipline
23818        // both collection-slot lifts established, extended here to the
23819        // singleton `:entrada` mesh-slot atom axis, the last M3
23820        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
23821        // axis on the Aplicacao surface without a lifted serde-key
23822        // peer.
23823        let e = Entrada {
23824            host: "checkout.quero.cloud".into(),
23825            para: "cart".into(),
23826            paths: vec!["/cart".into()],
23827            port: 8080,
23828        };
23829        let json = serde_json::to_string(&e).unwrap();
23830        for key in [
23831            crate::ENTRADA_KEY_HOST,
23832            crate::ENTRADA_KEY_PARA,
23833            crate::ENTRADA_KEY_PATHS,
23834            crate::ENTRADA_KEY_PORT,
23835        ] {
23836            let quoted = format!("\"{key}\"");
23837            assert!(
23838                json.contains(&quoted),
23839                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
23840                 byte-sequence {quoted} verbatim in the JSON emission \
23841                 (got: {json})",
23842            );
23843        }
23844    }
23845
23846    #[test]
23847    fn entrada_key_consts_are_pairwise_distinct() {
23848        // Cross-axis drift-detection pin: a future collapse of the four
23849        // canonical [`Entrada`] singleton byte-strings onto the same
23850        // value (e.g. an accidental copy-paste flip of
23851        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
23852        // silently reroute every downstream probe on one axis onto the
23853        // sibling axis's overlay entry and pass every propagation-probe
23854        // test that expected only the stale axis's value — the
23855        // Gateway/HTTPRoute emitter would read the hostname string
23856        // where the destination-Servico name was expected (or vice
23857        // versa), the admission-webhook cross-check would compare the
23858        // wrong pair of values, and the resulting Gateway resource
23859        // would either be admitted with garbage or rejected at the
23860        // controller far from the rebrand commit's source. Peer of the
23861        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
23862        // tetrad (40cc4e5), the two-way distinct pin on the
23863        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
23864        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
23865        // triad (ca463a4).
23866        let all = [
23867            crate::ENTRADA_KEY_HOST,
23868            crate::ENTRADA_KEY_PARA,
23869            crate::ENTRADA_KEY_PATHS,
23870            crate::ENTRADA_KEY_PORT,
23871        ];
23872        for (i, a) in all.iter().enumerate() {
23873            for b in all.iter().skip(i + 1) {
23874                assert_ne!(
23875                    a, b,
23876                    "ENTRADA_KEY_* consts must be pairwise-distinct \
23877                     canonical byte-sequences — got `{a}` == `{b}`",
23878                );
23879            }
23880        }
23881    }
23882
23883    #[test]
23884    fn entrada_key_consts_are_lower_camel_case_shape() {
23885        // Shape-pin: every `ENTRADA_KEY_*` const must be a
23886        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23887        // `kebab-case` hyphens, no leading colon, no `PascalCase`
23888        // leading capital, no whitespace / dots) — the canonical shape
23889        // the `#[serde(rename_all = "camelCase")]` derive produces on
23890        // [`Entrada`]. A future flip to a non-camelCase attribute at
23891        // the derive surfaces both here (this test fails on the
23892        // stale-constant shape) and at
23893        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
23894        // test fails on the mismatch between const and derive). Peer
23895        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
23896        // and `contrato_key_consts_are_lower_camel_case_shape`
23897        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
23898        // entry axes.
23899        for key in [
23900            crate::ENTRADA_KEY_HOST,
23901            crate::ENTRADA_KEY_PARA,
23902            crate::ENTRADA_KEY_PATHS,
23903            crate::ENTRADA_KEY_PORT,
23904        ] {
23905            assert!(
23906                !key.is_empty(),
23907                "ENTRADA_KEY_* must be non-empty (got {key:?})"
23908            );
23909            let first = key.chars().next().unwrap();
23910            assert!(
23911                first.is_ascii_lowercase(),
23912                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
23913                 (got {key:?}, leads with {first:?})",
23914            );
23915            assert!(
23916                key.chars().all(|c| c.is_ascii_alphanumeric()),
23917                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
23918                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23919            );
23920        }
23921    }
23922
23923    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
23924
23925    #[test]
23926    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
23927        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
23928        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
23929        // [`crate::POLITICAS_KEY_RETRIES`] /
23930        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
23931        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
23932        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
23933        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
23934        // on [`MeshPolicy`] emits. Three of the five axes
23935        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
23936        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
23937        // camelCase transforms — the derive-attribute is load-bearing
23938        // on those, unlike the sibling `Entrada` / `Membro` /
23939        // `WitContract` structs whose fields are all lowercase-single-
23940        // word and where the derive is a no-op on every axis.
23941        // Serialize a fully-populated [`MeshPolicy`] (every axis
23942        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
23943        // on none of the five slots) and pin that each canonical
23944        // byte-sequence appears verbatim in the JSON — a future
23945        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23946        // verbatim-field-name flip at the derive attribute (any of
23947        // which would silently break every downstream JSON consumer
23948        // that reaches for one of the five consts via
23949        // `Value::get(...)` — the future M4 per-edge `:politicas`
23950        // overlay projection onto Cilium `L7Rules` and Gateway API
23951        // `HTTPRoute` backend timeouts, the future
23952        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23953        // admission-time mesh-policy cross-check, the future
23954        // `feira lint` per-`:politicas` bound-check gate) surfaces here
23955        // as a build-time test failure at `aplicacao.rs`, not as an
23956        // apply-time `.get(<stale-canonical-const>)` returning `None`
23957        // far from the derive-attr drift's commit. Peer with the
23958        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
23959        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23960        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
23961        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
23962        // atom axes — same discipline every M3 sibling lift
23963        // established, extended here to the singleton `:politicas`
23964        // mesh-slot atom axis, closing the last M3 typed-struct
23965        // top-level `#[serde(rename_all = "camelCase")]` axis on the
23966        // Aplicacao surface without a lifted serde-key peer.
23967        let p = MeshPolicy {
23968            timeout: Some(Duration::from_secs(30)),
23969            retries: Some(3),
23970            circuit_breaker: Some(CircuitBreaker {
23971                max_failures: 5,
23972                window: Duration::from_secs(60),
23973            }),
23974            mtls_required: Some(true),
23975            rate_limit: Some(RateLimit {
23976                rate: 100,
23977                window: Duration::from_secs(1),
23978            }),
23979        };
23980        let json = serde_json::to_string(&p).unwrap();
23981        for key in [
23982            crate::POLITICAS_KEY_TIMEOUT,
23983            crate::POLITICAS_KEY_RETRIES,
23984            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23985            crate::POLITICAS_KEY_MTLS_REQUIRED,
23986            crate::POLITICAS_KEY_RATE_LIMIT,
23987        ] {
23988            let quoted = format!("\"{key}\"");
23989            assert!(
23990                json.contains(&quoted),
23991                "serialized MeshPolicy must carry the lifted \
23992                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
23993                 JSON emission (got: {json})",
23994            );
23995        }
23996    }
23997
23998    #[test]
23999    fn politicas_key_consts_are_pairwise_distinct() {
24000        // Cross-axis drift-detection pin: a future collapse of the five
24001        // canonical [`MeshPolicy`] singleton byte-strings onto the same
24002        // value (e.g. an accidental copy-paste flip of
24003        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
24004        // would silently reroute every downstream probe on one axis
24005        // onto the sibling axis's overlay entry and pass every
24006        // propagation-probe test that expected only the stale axis's
24007        // value — the M4 per-edge `:politicas` overlay projection would
24008        // read the retry-count string where the timeout duration was
24009        // expected (or vice versa), the CR materializer's admission
24010        // cross-check would compare the wrong pair of values, and the
24011        // resulting mesh reconciler would either bind the wrong axis
24012        // or reject the resource at reconcile far from the rebrand
24013        // commit's source. Peer of the sibling four-way distinct pin
24014        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
24015        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
24016        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
24017        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
24018        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
24019        let all = [
24020            crate::POLITICAS_KEY_TIMEOUT,
24021            crate::POLITICAS_KEY_RETRIES,
24022            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
24023            crate::POLITICAS_KEY_MTLS_REQUIRED,
24024            crate::POLITICAS_KEY_RATE_LIMIT,
24025        ];
24026        for (i, a) in all.iter().enumerate() {
24027            for b in all.iter().skip(i + 1) {
24028                assert_ne!(
24029                    a, b,
24030                    "POLITICAS_KEY_* consts must be pairwise-distinct \
24031                     canonical byte-sequences — got `{a}` == `{b}`",
24032                );
24033            }
24034        }
24035    }
24036
24037    #[test]
24038    fn politicas_key_consts_are_lower_camel_case_shape() {
24039        // Shape-pin: every `POLITICAS_KEY_*` const must be a
24040        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
24041        // `kebab-case` hyphens, no leading colon, no `PascalCase`
24042        // leading capital, no whitespace / dots) — the canonical shape
24043        // the `#[serde(rename_all = "camelCase")]` derive produces on
24044        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
24045        // at the derive surfaces both here (this test fails on the
24046        // stale-constant shape) and at
24047        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
24048        // (that test fails on the mismatch between const and derive).
24049        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
24050        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
24051        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
24052        // (ca463a4) on the sibling M3 typed-struct axes.
24053        for key in [
24054            crate::POLITICAS_KEY_TIMEOUT,
24055            crate::POLITICAS_KEY_RETRIES,
24056            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
24057            crate::POLITICAS_KEY_MTLS_REQUIRED,
24058            crate::POLITICAS_KEY_RATE_LIMIT,
24059        ] {
24060            assert!(
24061                !key.is_empty(),
24062                "POLITICAS_KEY_* must be non-empty (got {key:?})"
24063            );
24064            let first = key.chars().next().unwrap();
24065            assert!(
24066                first.is_ascii_lowercase(),
24067                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
24068                 byte (got {key:?}, leads with {first:?})",
24069            );
24070            assert!(
24071                key.chars().all(|c| c.is_ascii_alphanumeric()),
24072                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
24073                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
24074            );
24075        }
24076    }
24077
24078    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
24079
24080    #[test]
24081    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
24082        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
24083        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
24084        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
24085        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
24086        // [`CircuitBreaker`] emits inside the
24087        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
24088        // two axes (`max_failures` → `maxFailures`) is a non-trivial
24089        // camelCase transform — the derive-attribute is load-bearing on
24090        // that axis, unlike the sibling `window` field where the derive
24091        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
24092        // pin that each canonical byte-sequence appears verbatim in the
24093        // JSON — a future accidental `rename_all = "snake_case"` /
24094        // `"kebab-case"` / verbatim-field-name flip at the derive
24095        // attribute (any of which would silently break every downstream
24096        // JSON consumer that reaches for one of the two consts via
24097        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
24098        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
24099        // per-edge `:politicas` overlay projection onto the mesh's
24100        // per-backend consecutive-failure-counter tripping threshold, the
24101        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
24102        // admission-time breaker cross-check, the future `feira lint`
24103        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
24104        // here as a build-time test failure at `aplicacao.rs`, not as an
24105        // apply-time `.get(<stale-canonical-const>)` returning `None`
24106        // far from the derive-attr drift's commit. Peer with the sibling
24107        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
24108        // (b55cca7) parent-axis pin — that test pins the outer
24109        // sub-block key the derive on [`MeshPolicy`] emits, this test
24110        // pins the inner keys the derive on the payload type emits, so
24111        // the two together lock the whole [`MeshPolicy`] breaker-tuning
24112        // shape end-to-end at build time.
24113        let cb = CircuitBreaker {
24114            max_failures: 5,
24115            window: Duration::from_secs(60),
24116        };
24117        let json = serde_json::to_string(&cb).unwrap();
24118        for key in [
24119            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24120            crate::CIRCUIT_BREAKER_KEY_WINDOW,
24121        ] {
24122            let quoted = format!("\"{key}\"");
24123            assert!(
24124                json.contains(&quoted),
24125                "serialized CircuitBreaker must carry the lifted \
24126                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
24127                 in the JSON emission (got: {json})",
24128            );
24129        }
24130    }
24131
24132    #[test]
24133    fn circuit_breaker_key_consts_are_pairwise_distinct() {
24134        // Cross-axis drift-detection pin: a future collapse of the two
24135        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
24136        // same value (e.g. an accidental copy-paste flip of
24137        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
24138        // `"maxFailures"`) would silently reroute every downstream
24139        // probe on one axis onto the sibling axis's overlay entry and
24140        // pass every propagation-probe test that expected only the
24141        // stale axis's value — the M4 per-edge `:politicas` overlay
24142        // projection would read the failure-count where the window
24143        // duration was expected (or vice versa), the CR materializer's
24144        // admission cross-check would compare the wrong pair of values,
24145        // and the resulting mesh reconciler would either bind the wrong
24146        // axis or reject the resource at reconcile far from the rebrand
24147        // commit's source. Peer of the sibling five-way distinct pin on
24148        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
24149        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
24150        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
24151        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
24152        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
24153        let all = [
24154            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24155            crate::CIRCUIT_BREAKER_KEY_WINDOW,
24156        ];
24157        for (i, a) in all.iter().enumerate() {
24158            for b in all.iter().skip(i + 1) {
24159                assert_ne!(
24160                    a, b,
24161                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
24162                     canonical byte-sequences — got `{a}` == `{b}`",
24163                );
24164            }
24165        }
24166    }
24167
24168    #[test]
24169    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
24170        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
24171        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
24172        // `kebab-case` hyphens, no leading colon, no `PascalCase`
24173        // leading capital, no whitespace / dots) — the canonical shape
24174        // the `#[serde(rename_all = "camelCase")]` derive produces on
24175        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
24176        // at the derive surfaces both here (this test fails on the
24177        // stale-constant shape) and at
24178        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
24179        // (that test fails on the mismatch between const and derive).
24180        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
24181        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
24182        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
24183        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
24184        // (ca463a4) on the sibling M3 typed-struct axes.
24185        for key in [
24186            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24187            crate::CIRCUIT_BREAKER_KEY_WINDOW,
24188        ] {
24189            assert!(
24190                !key.is_empty(),
24191                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
24192            );
24193            let first = key.chars().next().unwrap();
24194            assert!(
24195                first.is_ascii_lowercase(),
24196                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
24197                 byte (got {key:?}, leads with {first:?})",
24198            );
24199            assert!(
24200                key.chars().all(|c| c.is_ascii_alphanumeric()),
24201                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
24202                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
24203            );
24204        }
24205    }
24206
24207    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
24208
24209    #[test]
24210    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
24211        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
24212        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
24213        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
24214        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
24215        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
24216        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
24217        // [`Placement`] emits. One of the four axes (`shard_key` →
24218        // `shardKey`) is a non-trivial camelCase transform — the
24219        // derive-attribute is load-bearing on that axis, unlike the
24220        // sibling `estrategia` / `clusters` / `affinity` axes whose
24221        // source-side field names carry no `_` and where the derive is a
24222        // no-op. Serialize a fully-populated [`Placement`] (both
24223        // `Option`-carrying axes `Some(_)` so
24224        // `skip_serializing_if = "Option::is_none"` fires on neither of
24225        // the two optional slots) and pin that each canonical
24226        // byte-sequence appears verbatim in the JSON — a future
24227        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
24228        // verbatim-field-name flip at the derive attribute (any of which
24229        // would silently break every downstream consumer that reaches
24230        // for one of the four consts via
24231        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
24232        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
24233        // aggregator's per-cluster fanout filter keying off
24234        // `placement.clusters`, the M3 shard-pool dispatch materializer
24235        // keying off `placement.shardKey`, the M3 Adaptive compression
24236        // pass weighting off `placement.affinity`, every downstream
24237        // dispatcher branching on `placement.estrategia`, the future
24238        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
24239        // admission-time placement cross-check, the future `feira lint`
24240        // per-`:placement` bound-check gate) surfaces here as a
24241        // build-time test failure at `aplicacao.rs`, not as an
24242        // apply-time `.get(<stale-canonical-const>)` returning `None`
24243        // far from the derive-attr drift's commit. Peer with the sibling
24244        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
24245        // (b55cca7),
24246        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
24247        // (468e959),
24248        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
24249        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
24250        // (ca463a4), and
24251        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
24252        // pins on the M3 collection-slot / singleton-slot atom axes —
24253        // closes the last M3 typed-struct top-level
24254        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
24255        // surface without a drift-detection pin.
24256        let p = Placement {
24257            estrategia: PlacementStrategy::Sharded,
24258            clusters: vec!["rio".into(), "mar".into()],
24259            affinity: Some("data-locality".into()),
24260            shard_key: Some("$tenantId".into()),
24261        };
24262        let json = serde_json::to_string(&p).unwrap();
24263        for key in [
24264            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
24265            crate::M3_PLACEMENT_KEY_CLUSTERS,
24266            crate::M3_PLACEMENT_KEY_AFFINITY,
24267            crate::M3_PLACEMENT_KEY_SHARD_KEY,
24268        ] {
24269            let quoted = format!("\"{key}\"");
24270            assert!(
24271                json.contains(&quoted),
24272                "serialized Placement must carry the lifted \
24273                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
24274                 the JSON emission (got: {json})",
24275            );
24276        }
24277    }
24278
24279    #[test]
24280    fn m3_placement_key_consts_are_pairwise_distinct() {
24281        // Cross-axis drift-detection pin: a future collapse of the four
24282        // canonical [`Placement`] sub-block byte-strings onto the same
24283        // value (e.g. an accidental copy-paste flip of
24284        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
24285        // `"affinity"`) would silently reroute every downstream probe on
24286        // one axis onto the sibling axis's overlay entry and pass every
24287        // propagation-probe test that expected only the stale axis's
24288        // value — the M3 shard-pool dispatch materializer would read the
24289        // affinity placement-hint where the shard-selection template was
24290        // expected (or vice versa), the M3 Adaptive compression pass's
24291        // cross-check would compare the wrong pair of values, and the
24292        // resulting placement engine would either bind the wrong axis or
24293        // reject the resource at reconcile far from the rebrand commit's
24294        // source. Peer of the sibling two-way distinct pin on the
24295        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
24296        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
24297        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
24298        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
24299        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
24300        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
24301        let all = [
24302            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
24303            crate::M3_PLACEMENT_KEY_CLUSTERS,
24304            crate::M3_PLACEMENT_KEY_AFFINITY,
24305            crate::M3_PLACEMENT_KEY_SHARD_KEY,
24306        ];
24307        for (i, a) in all.iter().enumerate() {
24308            for b in all.iter().skip(i + 1) {
24309                assert_ne!(
24310                    a, b,
24311                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
24312                     canonical byte-sequences — got `{a}` == `{b}`",
24313                );
24314            }
24315        }
24316    }
24317
24318    #[test]
24319    fn m3_placement_key_consts_are_lower_camel_case_shape() {
24320        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
24321        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
24322        // `kebab-case` hyphens, no leading colon, no `PascalCase`
24323        // leading capital, no whitespace / dots) — the canonical shape
24324        // the `#[serde(rename_all = "camelCase")]` derive produces on
24325        // [`Placement`]. A future flip to a non-camelCase attribute at
24326        // the derive surfaces both here (this test fails on the stale-
24327        // constant shape) and at
24328        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
24329        // (that test fails on the mismatch between const and derive).
24330        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
24331        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
24332        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
24333        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
24334        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
24335        // (ca463a4) on the sibling M3 typed-struct axes.
24336        for key in [
24337            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
24338            crate::M3_PLACEMENT_KEY_CLUSTERS,
24339            crate::M3_PLACEMENT_KEY_AFFINITY,
24340            crate::M3_PLACEMENT_KEY_SHARD_KEY,
24341        ] {
24342            assert!(
24343                !key.is_empty(),
24344                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
24345            );
24346            let first = key.chars().next().unwrap();
24347            assert!(
24348                first.is_ascii_lowercase(),
24349                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
24350                 byte (got {key:?}, leads with {first:?})",
24351            );
24352            assert!(
24353                key.chars().all(|c| c.is_ascii_alphanumeric()),
24354                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
24355                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
24356            );
24357        }
24358    }
24359
24360    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
24361    //    destination-facing L4 port resolver every per-Aplicacao renderer
24362    //    reaching for a per-destination Servico TCP port axis routes
24363    //    through. The four pin tests below fix the four-way accept-set
24364    //    the resolver must always honor: (:entrada-para-matches,
24365    //    :entrada-para-mismatches, :entrada-none-so-fallback,
24366    //    :entrada-port-non-default-honored) — drift on any arm surfaces
24367    //    at caixa-core build time rather than at cluster-apply time.
24368
24369    #[test]
24370    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
24371        // The typed `:entrada` block's `:para "cart"` matches the
24372        // queried destination, so the resolver returns the author-
24373        // declared `:port` scalar verbatim — the canonical "the
24374        // destination Servico IS the ingress apex, honor the typed
24375        // listener port" arm of the port-resolution dispatch.
24376        let mut spec = three_member_spec();
24377        if let Some(e) = spec.entrada.as_mut() {
24378            e.para = "cart".into();
24379            e.port = 9090;
24380        }
24381        assert_eq!(
24382            spec.port_for_destination("cart"),
24383            9090,
24384            "port_for_destination(entrada.para) must return entrada.port \
24385             verbatim, not the DEFAULT_SERVICO_PORT fallback"
24386        );
24387    }
24388
24389    #[test]
24390    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
24391        // The typed `:entrada` block names `:para "cart"`, but the
24392        // queried destination is `"payment"` — a Servico that
24393        // participates in the mesh graph but is not the ingress apex.
24394        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
24395        // canonical port floor, closing the "non-apex destination reads
24396        // the substrate default" arm. Same fixture the peer
24397        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
24398        // pin at caixa-mesh exercises through the CNP emit-side path;
24399        // this pin exercises the shared underlying resolver directly.
24400        let spec = three_member_spec();
24401        assert_eq!(
24402            spec.port_for_destination("payment"),
24403            DEFAULT_SERVICO_PORT,
24404            "port_for_destination(non-apex-destination) must route \
24405             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
24406        );
24407    }
24408
24409    #[test]
24410    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
24411        // Internal-only Aplicacao — no `:entrada` block declared. Every
24412        // per-destination port query falls back to the lifted
24413        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
24414        // the Aplicacao surface admits `:entrada None` (internal mesh
24415        // with no external gateway); every downstream renderer's per-
24416        // destination port axis must still resolve to a well-defined
24417        // scalar even without an ingress apex.
24418        let mut spec = three_member_spec();
24419        spec.entrada = None;
24420        assert_eq!(
24421            spec.port_for_destination("cart"),
24422            DEFAULT_SERVICO_PORT,
24423            "port_for_destination on an internal-only Aplicacao must \
24424             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
24425             every destination"
24426        );
24427        assert_eq!(
24428            spec.port_for_destination("payment"),
24429            DEFAULT_SERVICO_PORT,
24430            "port_for_destination on an internal-only Aplicacao must \
24431             fall back uniformly across every destination — the fallback \
24432             is not entrada-shape-conditional"
24433        );
24434    }
24435
24436    #[test]
24437    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
24438        // Structural pin against a hypothetical future refactor that
24439        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
24440        // the resolver (a "normalize to the default when the author's
24441        // port matches the substrate default" collapse) — that would
24442        // break renderer sites that carry meaning on the emitted port
24443        // value beyond bare equality (a future per-cluster listener-
24444        // audit that keys off the author-declared port, not the
24445        // resolved-with-fallback port). Pin that a non-default
24446        // entrada.port is returned verbatim so drift here surfaces at
24447        // caixa-core build time.
24448        let mut spec = three_member_spec();
24449        if let Some(e) = spec.entrada.as_mut() {
24450            e.para = "cart".into();
24451            e.port = 8443;
24452        }
24453        assert_ne!(
24454            8443, DEFAULT_SERVICO_PORT,
24455            "test fixture must probe a port distinct from \
24456             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
24457        );
24458        assert_eq!(
24459            spec.port_for_destination("cart"),
24460            8443,
24461            "port_for_destination(entrada.para) must return entrada.port \
24462             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
24463        );
24464    }
24465
24466    #[test]
24467    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
24468        // Apex-identity pair-invariant pin composing both substrate-
24469        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
24470        // and [`Entrada::destination`] — at the emit-side call shape
24471        // every per-Aplicacao renderer's ingress-apex L4 port reader
24472        // now takes. The invariant:
24473        //
24474        //   spec.port_for_destination(entrada.destination()) == entrada.port
24475        //
24476        // holds by construction under today's single-destination
24477        // `:entrada` slot (`destination()` returns `entrada.para`, and
24478        // the resolver's apex arm matches `para == destination` and
24479        // returns `entrada.port`), and every downstream consumer that
24480        // composes the two accessors at the ingress apex — the
24481        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
24482        // `backendRefs[0].port` emit-site path, the peer future M4 CR
24483        // materializer's admission-webhook that promotes the scalar to
24484        // a per-CR override overlay, every future per-Aplicacao snapshot
24485        // renderer's apex-facing L4 port reader — reaches through the
24486        // same composition. Pin the identity across four permutations
24487        // (`:para` × `:port` including a non-default port to exercise
24488        // the honor-verbatim arm and a non-cart `:para` to exercise
24489        // destination-agnostic identity) so a future refactor that
24490        // silently split either accessor's apex behavior surfaces at
24491        // caixa-core build time — a subtle `destination()` renaming
24492        // that returned `entrada.host.as_str()` instead of
24493        // `entrada.para.as_str()` would blow this pin loudly, closing
24494        // the last quiet failure mode the two lifts admit in composition.
24495        //
24496        // Peer discipline with the sibling caixa-mesh cross-crate pin
24497        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
24498        // on the two-renderer pair-invariant axis; this pin encodes the
24499        // same two-consumer coherence rule at the substrate-primitive
24500        // level so the invariant survives even if every renderer is
24501        // deleted.
24502        for (para, port) in [
24503            ("cart", DEFAULT_SERVICO_PORT),
24504            ("cart", 8443u16),
24505            ("payment", 9090u16),
24506            ("catalog", 443u16),
24507        ] {
24508            let mut spec = three_member_spec();
24509            if let Some(e) = spec.entrada.as_mut() {
24510                e.para = para.into();
24511                e.port = port;
24512            }
24513            let expected_port = spec
24514                .entrada()
24515                .expect("three_member_spec carries a typed `:entrada` block")
24516                .port();
24517            let composed_port = {
24518                let entrada = spec.entrada().expect("entrada present");
24519                spec.port_for_destination(entrada.destination())
24520            };
24521            assert_eq!(
24522                composed_port, expected_port,
24523                "`spec.port_for_destination(entrada.destination())` must \
24524                 equal `entrada.port` under today's single-destination \
24525                 `:entrada` slot — this is the apex-identity contract \
24526                 every downstream ingress-apex L4 port reader relies on. \
24527                 Input :entrada :para: {para:?}, :entrada :port: {port}"
24528            );
24529        }
24530    }
24531
24532    #[test]
24533    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
24534        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
24535        // per-`:entrada` apex-arm membership probe must key off
24536        // [`Entrada::destination`], not the raw `.para` field access.
24537        // Structurally: setting ONLY the `:entrada :para` field to a
24538        // fresh non-cart destination on an otherwise-well-formed
24539        // Aplicacao must (1) leave `e.destination()` byte-equal to
24540        // `e.para.as_str()` (the accessor is byte-projective by
24541        // definition), and (2) cause the resolver's apex arm to fire
24542        // and return `entrada.port` at exactly that new destination
24543        // while every other destination string falls through to
24544        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
24545        // membership check. Pins against a future silent detour that
24546        // (a) re-derived the apex-arm membership probe off
24547        // `e.para == destination` in `port_for_destination` instead of
24548        // `e.destination() == destination`, silently disagreeing with
24549        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
24550        // consumers (`entrada.destination()` at
24551        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
24552        // caixa-mesh/src/lib.rs:2739) that already reach through the
24553        // accessor, (b) accessor-side introduced a per-tenant alias
24554        // arm the caller was unaware of, silently rewriting an
24555        // author-declared `:para "cart"` value to a canary-aliased
24556        // form — the raw-field-access resolver would fall through to
24557        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
24558        // while the peer emit-site consumers landed on the aliased
24559        // destination, splitting the ingress-apex L4 port at
24560        // cluster-apply time.
24561        //
24562        // Peer of the sibling
24563        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
24564        // (d0de220) composition pin on the per-`:membros` refusal-arm
24565        // axis — same "the shape-gate predicate must route through the
24566        // substrate-primitive typed dispatch" discipline extended onto
24567        // the per-`:entrada` apex-arm membership-probe axis. Closes
24568        // the last unlifted `.para` production-code read site on
24569        // `Entrada` in `caixa-core` — after this converge every
24570        // `caixa-core` `.para` field access outside the accessor's own
24571        // body and outside the `WitContract` per-`:contratos` sibling
24572        // axis is either a test-side field-setter or a doc-comment
24573        // reference.
24574        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
24575            let mut spec = three_member_spec();
24576            if let Some(e) = spec.entrada.as_mut() {
24577                e.para = para.into();
24578                e.port = port;
24579            }
24580            let e = spec
24581                .entrada
24582                .as_ref()
24583                .expect("three_member_spec carries a typed `:entrada` block");
24584            assert_eq!(
24585                e.destination(),
24586                e.para.as_str(),
24587                "Entrada::destination must byte-equal the .para field \
24588                 access — an accessor-side detour that no longer \
24589                 projects the raw field would silently split this \
24590                 drift-detection test from the port_for_destination \
24591                 apex-arm membership probe",
24592            );
24593            assert_eq!(
24594                spec.port_for_destination(para),
24595                port,
24596                "port_for_destination must key off the accessor-projected \
24597                 destination and return `entrada.port` on the apex arm — \
24598                 input :entrada :para: {para:?}, :entrada :port: {port}",
24599            );
24600            assert_eq!(
24601                spec.port_for_destination("ghost-destination-never-a-member"),
24602                DEFAULT_SERVICO_PORT,
24603                "port_for_destination must fall through to \
24604                 DEFAULT_SERVICO_PORT on a non-matching destination \
24605                 under the accessor-projected membership check — input \
24606                 :entrada :para: {para:?}, :entrada :port: {port}",
24607            );
24608        }
24609    }
24610
24611    #[test]
24612    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
24613        // The canonical per-`:politicas :rate-limit` `:rate`
24614        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
24615        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
24616        // typed `u32` verbatim, byte-equal to the raw field access
24617        // across every representative value in the accept-set — `1` (the
24618        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
24619        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
24620        // carves out on the sibling `PolicyRateLimitZero` refusal),
24621        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
24622        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
24623        // `0` (a past-the-guard sentinel that pins the accessor doesn't
24624        // perform a silent bounds-collapse into `1` on the zero arm —
24625        // validate rejects zero but the accessor must ship the raw slot
24626        // verbatim so a validate-time gate regression surfaces at the
24627        // emit boundary rather than being silently absorbed), `u32::MAX`
24628        // (a past-the-guard sentinel that pins the accessor doesn't
24629        // perform a silent bounds-collapse through
24630        // `POLICY_RATE_LIMIT_MAX` at the return path).
24631        //
24632        // First sub-struct required-scalar accessor pin on the
24633        // `RateLimit` axis — sibling in shape to the peer
24634        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
24635        // required-`u32` accessor pin on the peer per-sub-struct
24636        // required-axis. Pins against a future silent detour that
24637        // re-derived the token capacity from a peer axis (an accidental
24638        // `self.window.as_secs() as u32` collapse that read the
24639        // rate-limit window duration as a token count), a `0 → 1`
24640        // cluster-default projection (which would silently absorb the
24641        // `PolicyRateLimitZero` refusal case at the accessor boundary),
24642        // or a bounds-collapsing accessor that clamped the return
24643        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
24644        // gate owns the bounds; the accessor must ship the raw slot
24645        // verbatim).
24646        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
24647            let rl = RateLimit {
24648                rate,
24649                window: Duration::from_secs(1),
24650            };
24651            assert_eq!(
24652                rl.rate(),
24653                rate,
24654                "RateLimit::rate must return :politicas :rate-limit :rate \
24655                 verbatim (got {}, expected {rate})",
24656                rl.rate(),
24657            );
24658            assert_eq!(
24659                rl.rate(),
24660                rl.rate,
24661                "RateLimit::rate must byte-equal the raw .rate field \
24662                 access across every value in the u32 accept-set",
24663            );
24664        }
24665    }
24666
24667    #[test]
24668    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
24669        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24670        // `:rate-limit :rate` zero-floor arm must key off
24671        // [`RateLimit::rate`], not the raw `.rate` field access.
24672        // Structurally: a `RateLimit { rate: 0, window:
24673        // Duration::from_secs(1) }` embedded in a `:politicas
24674        // :rate-limit` slot must surface the `PolicyRateLimitZero`
24675        // refusal exactly, and a `RateLimit { rate: 1, window:
24676        // Duration::from_secs(1) }` (the lower boundary of the
24677        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
24678        // The pair jointly pins the accessor + validate-gate composition:
24679        // any future silent detour that had the accessor return a fresh
24680        // `1` on the zero arm (a `.rate().max(1)` collapse) would
24681        // silently absorb the `PolicyRateLimitZero` refusal at the
24682        // accessor boundary and the validate gate would accept a
24683        // struct-literal `RateLimit { rate: 0, .. }` — the composition
24684        // pin catches that at caixa-core build time.
24685        //
24686        // Peer of the sibling per-`CircuitBreaker`
24687        // [`CircuitBreaker::max_failures`] (3a74062) /
24688        // [`CircuitBreaker::window`] (373957f) accessor-composition
24689        // pins on the peer required-scalar axes — same "the validate /
24690        // shape-gate predicate must route through the substrate-primitive
24691        // typed dispatch" discipline extended onto the peer
24692        // per-`RateLimit` required-`u32` composition axis.
24693        let mut spec = three_member_spec();
24694        spec.politicas = MeshPolicy {
24695            rate_limit: Some(RateLimit {
24696                rate: 0,
24697                window: Duration::from_secs(1),
24698            }),
24699            ..MeshPolicy::default()
24700        };
24701        assert!(
24702            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24703            "validate_politicas must reject rate == 0 with \
24704             PolicyRateLimitZero — the accessor and the validate gate \
24705             must route through the same substrate-primitive typed \
24706             dispatch on the :rate zero-floor arm",
24707        );
24708        spec.politicas = MeshPolicy {
24709            rate_limit: Some(RateLimit {
24710                rate: 1,
24711                window: Duration::from_secs(1),
24712            }),
24713            ..MeshPolicy::default()
24714        };
24715        assert!(
24716            spec.validate().is_ok(),
24717            "validate_politicas must accept rate == 1 (the lower \
24718             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
24719        );
24720    }
24721
24722    #[test]
24723    fn rate_limit_rate_projects_u32_by_copy() {
24724        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
24725        // `u32` is `Copy` and the accessor must return by value, not by
24726        // reference. Peer of the sibling per-`CircuitBreaker`
24727        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
24728        // peer required-scalar `:max-failures` axis, extended onto the
24729        // peer per-`RateLimit` required-`u32` copy-invariant shape —
24730        // the accessor's returned `u32` must outlive `&self` (multiple
24731        // calls must return equal values from a dropped-`&self` copy,
24732        // since the returned scalar carries no borrow), and calling the
24733        // accessor twice on the same RateLimit must yield the same
24734        // `u32` verbatim (idempotent, no side effects on `&self`).
24735        //
24736        // Pins against a future silent detour that returned `&u32`
24737        // (which would type-check but silently break every downstream
24738        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
24739        // first parameter is `u32`, and `&u32` would fold to a detached
24740        // copy at the call site with a `*` deref the sibling accessors
24741        // don't need), an accidental `.rate.wrapping_add(0)` detour that
24742        // returned a fresh copy through an arithmetic no-op (breaking a
24743        // future `const fn` regression), or a one-arm-only accessor
24744        // that returned a saturating value on some sentinel input
24745        // (breaking the pass-through invariant the sibling required-
24746        // scalar accessors carry).
24747        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
24748            let rl = RateLimit {
24749                rate,
24750                window: Duration::from_secs(1),
24751            };
24752            let first = rl.rate();
24753            let second = rl.rate();
24754            assert_eq!(
24755                first, second,
24756                "RateLimit::rate must be idempotent — two successive \
24757                 calls on the same &self must return the same u32",
24758            );
24759            assert_eq!(
24760                first, rate,
24761                "RateLimit::rate must return :politicas :rate-limit :rate \
24762                 verbatim by copy — got {first}, expected {rate}",
24763            );
24764        }
24765    }
24766
24767    #[test]
24768    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
24769        // The canonical per-`:politicas :rate-limit` `:window`
24770        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
24771        // pin: [`RateLimit::window`] must return the
24772        // `:politicas :rate-limit :window` typed `Duration` verbatim,
24773        // byte-equal to the raw field access across every
24774        // representative value in the accept-set — `Duration::from_secs(1)`
24775        // (the `"s"` canonical window, the lower row of
24776        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
24777        // [`AplicacaoSpec::validate_politicas`] gate accepts via
24778        // [`is_canonical_rate_limit_window`]),
24779        // `Duration::from_secs(60)` (the `"m"` canonical window, the
24780        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
24781        // window, the upper row), `Duration::ZERO` (a past-the-guard
24782        // sentinel that pins the accessor doesn't perform a silent
24783        // bounds-collapse into `Duration::from_secs(1)` on the zero
24784        // arm — validate rejects an off-set window through
24785        // `PolicyRateLimitWindowNotCanonical` but the accessor must
24786        // ship the raw slot verbatim so a validate-time gate
24787        // regression surfaces at the emit boundary rather than being
24788        // silently absorbed), `Duration::from_millis(500)` (a
24789        // sub-canonical past-the-guard sentinel that pins the accessor
24790        // doesn't silently normalize a non-canonical fractional
24791        // magnitude onto the nearest canonical row).
24792        //
24793        // Second sub-struct required-scalar accessor pin on the
24794        // `RateLimit` axis — sibling in shape to the just-landed
24795        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
24796        // accessor pin on the peer per-sub-struct required-axis,
24797        // extended onto the per-`RateLimit` required-`Duration` axis.
24798        // Pins against a future silent detour that re-derived the
24799        // refill period from a peer axis (an accidental
24800        // `Duration::from_secs(self.rate as u64)` collapse that read
24801        // the rate-limit token capacity as a refill-interval
24802        // duration), a `Duration::ZERO → Duration::from_secs(1)`
24803        // canonical-default projection (which would silently absorb
24804        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
24805        // accessor boundary), or a canonical-set-collapsing accessor
24806        // that clamped the return through [`rate_limit_window_unit`]
24807        // (the `AplicacaoSpec::validate` gate owns the canonical-set
24808        // membership; the accessor must ship the raw slot verbatim).
24809        for window in [
24810            Duration::from_secs(1),
24811            Duration::from_secs(60),
24812            Duration::from_secs(3600),
24813            Duration::ZERO,
24814            Duration::from_millis(500),
24815        ] {
24816            let rl = RateLimit { rate: 100, window };
24817            assert_eq!(
24818                rl.window(),
24819                window,
24820                "RateLimit::window must return :politicas :rate-limit :window \
24821                 verbatim (got {:?}, expected {window:?})",
24822                rl.window(),
24823            );
24824            assert_eq!(
24825                rl.window(),
24826                rl.window,
24827                "RateLimit::window must byte-equal the raw .window field \
24828                 access across every value in the Duration accept-set",
24829            );
24830        }
24831    }
24832
24833    #[test]
24834    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
24835        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24836        // `:rate-limit :window` canonical-set arm must key off
24837        // [`RateLimit::window`], not the raw `.window` field access.
24838        // Structurally: a `RateLimit { window: Duration::from_millis(500),
24839        // .. }` embedded in a `:politicas :rate-limit` slot must
24840        // surface the `PolicyRateLimitWindowNotCanonical` refusal
24841        // exactly (with the sub-canonical `Duration::from_millis(500)`
24842        // magnitude carried through verbatim), and a `RateLimit
24843        // { window: Duration::from_secs(1), .. }` (the lower row of
24844        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
24845        // The pair jointly pins the accessor + validate-gate
24846        // composition: any future silent detour that had the accessor
24847        // normalize the off-set window to the nearest canonical row
24848        // (a `.window().max(Duration::from_secs(1))` collapse, or a
24849        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
24850        // collapse) would silently absorb the
24851        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
24852        // boundary — including a drift in the error's `window` payload
24853        // (the emit-side diagnostic reader keys off the offending
24854        // magnitude verbatim, so a normalization at the accessor
24855        // boundary would silently pin the wrong magnitude in the
24856        // refusal). The composition pin catches that at caixa-core
24857        // build time.
24858        //
24859        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
24860        // (7f81a60) accessor-composition pin on the peer required-
24861        // scalar `:rate` axis — same "the validate / shape-gate
24862        // predicate must route through the substrate-primitive typed
24863        // dispatch, and the error payload must project through the
24864        // same accessor" discipline extended onto the peer
24865        // per-`RateLimit` required-`Duration` composition axis.
24866        let mut spec = three_member_spec();
24867        spec.politicas = MeshPolicy {
24868            rate_limit: Some(RateLimit {
24869                rate: 100,
24870                window: Duration::from_millis(500),
24871            }),
24872            ..MeshPolicy::default()
24873        };
24874        match spec.validate() {
24875            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
24876                assert_eq!(
24877                    window,
24878                    Duration::from_millis(500),
24879                    "PolicyRateLimitWindowNotCanonical must carry the \
24880                     offending :window magnitude verbatim through the \
24881                     accessor — got {window:?}, expected 500ms",
24882                );
24883            }
24884            other => panic!(
24885                "validate_politicas must reject non-canonical :window \
24886                 with PolicyRateLimitWindowNotCanonical — the accessor \
24887                 and the validate gate must route through the same \
24888                 substrate-primitive typed dispatch on the :window \
24889                 canonical-set arm; got {other:?}",
24890            ),
24891        }
24892        spec.politicas = MeshPolicy {
24893            rate_limit: Some(RateLimit {
24894                rate: 100,
24895                window: Duration::from_secs(1),
24896            }),
24897            ..MeshPolicy::default()
24898        };
24899        assert!(
24900            spec.validate().is_ok(),
24901            "validate_politicas must accept window == Duration::from_secs(1) \
24902             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
24903        );
24904    }
24905
24906    #[test]
24907    fn rate_limit_window_projects_duration_by_copy() {
24908        // The by-copy pin: [`RateLimit::window`] returns `Duration`
24909        // by copy — `Duration` is `Copy` and the accessor must return
24910        // by value, not by reference. Peer of the sibling per-`RateLimit`
24911        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
24912        // required-scalar `:rate` axis, extended onto the peer
24913        // per-`RateLimit` required-`Duration` copy-invariant shape —
24914        // the accessor's returned `Duration` must outlive `&self`
24915        // (multiple calls must return equal values from a
24916        // dropped-`&self` copy, since the returned scalar carries no
24917        // borrow), and calling the accessor twice on the same
24918        // RateLimit must yield the same `Duration` verbatim
24919        // (idempotent, no side effects on `&self`).
24920        //
24921        // Pins against a future silent detour that returned
24922        // `&Duration` (which would type-check but silently break every
24923        // downstream `Duration`-by-value consumer —
24924        // [`is_canonical_rate_limit_window`]'s first parameter is
24925        // `Duration`, and `&Duration` would fold to a detached copy at
24926        // the call site with a `*` deref the sibling accessors don't
24927        // need), an accidental `.window + Duration::ZERO` detour that
24928        // returned a fresh copy through an arithmetic no-op (breaking
24929        // a future `const fn` regression), or a one-arm-only accessor
24930        // that returned a canonical fallback on some sentinel input
24931        // (breaking the pass-through invariant the sibling required-
24932        // scalar accessors carry).
24933        for window in [
24934            Duration::from_secs(1),
24935            Duration::from_secs(60),
24936            Duration::from_secs(3600),
24937            Duration::ZERO,
24938            Duration::from_millis(500),
24939        ] {
24940            let rl = RateLimit { rate: 100, window };
24941            let first = rl.window();
24942            let second = rl.window();
24943            assert_eq!(
24944                first, second,
24945                "RateLimit::window must be idempotent — two successive \
24946                 calls on the same &self must return the same Duration",
24947            );
24948            assert_eq!(
24949                first, window,
24950                "RateLimit::window must return :politicas :rate-limit :window \
24951                 verbatim by copy — got {first:?}, expected {window:?}",
24952            );
24953        }
24954    }
24955}