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 targets *none* of the three known payload-
797    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
798    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
799    /// open on the [`WitContract`] surface. Returns the exact-inverse
800    /// disjunction of the peer trio — `true` when none of the three
801    /// prefix-set predicates matches the raw `:contratos :wit` value; the
802    /// author-declared WIT world is a pure typed capability edge with no
803    /// payload selector (the shape [`WitContract::target`] projects onto
804    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
805    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
806    ///
807    /// The `:contratos :wit` shape-space is closed at four arms
808    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
809    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
810    /// everything else on the payload-less capability arm), and every
811    /// downstream consumer that must filter contratos by shape-class
812    /// keys off the four sibling predicates (the [`WitContract::target`]
813    /// dispatch's implicit `else` after the three payload-shape arm
814    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
815    /// every future substrate-side capability-shape-only emitter — the
816    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
817    /// future `feira app graph --capability` per-Aplicacao capability-
818    /// column filter, the future per-cluster capability-scope reconciler
819    /// that skips L4/L7 emission for payload-less edges since Cilium
820    /// can't introspect WASI capability calls, the future
821    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
822    /// shape shape-count histogram). Every such consumer reaches for one
823    /// typed dispatch on the substrate primitive so the "which arm
824    /// carries the capability-only shape?" answer lives at one caixa-core
825    /// edit rather than open-coded across per-consumer
826    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
827    /// negations, each of which would silently drop a future fourth
828    /// payload-arm addition without a compile-time signal at the
829    /// consumer site.
830    ///
831    /// Prior to this lift the "not one of the three known payload
832    /// shapes" classification sat inline at [`WitContract::target`]'s
833    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
834    /// [`WitTarget::Capability`] admission arm after the three `if
835    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
836    /// { … }` guards) with no named accessor for downstream consumers
837    /// to reach through. A future substrate-side capability-only
838    /// filter or a future capability-scope reconciler would have had to
839    /// re-inline the same triplet negation at every emit site with no
840    /// compile-time link back to the sibling trio, and a future arm
841    /// addition (a hypothetical fourth payload-shape prefix set — a
842    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
843    /// import carrier per the sibling [`wit_shape_matches`] docstring's
844    /// trajectory bullet) would land the new predicate on the payload-
845    /// carrying trio and silently misclassify the new shape as
846    /// capability at every triplet-negation consumer site, propagating
847    /// the drift far from the caixa-core prefix-set commit.
848    ///
849    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
850    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
851    /// trio into a 4-way partition witness on the raw `:contratos :wit`
852    /// axis, mirroring the paired post-projection [`WitTarget`]
853    /// `gen_platform::IsVariant`-derived 4-way predicate set
854    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
855    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
856    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
857    /// arm-set). The two typed axes — pre-projection on the raw
858    /// `:contratos :wit` string, post-projection on the validated typed
859    /// view — now carry a matched 4-arm predicate discipline: every
860    /// arm on the closed [`WitTarget`] set has a peer pre-projection
861    /// predicate on the [`WitContract`] surface, and any future
862    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
863    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
864    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
865    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
866    /// pre-projection axis through a matching peer prefix-set + peer
867    /// predicate lift by construction — the compile-time exhaustiveness
868    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
869    /// the post-projection accessor family stays in sync, and the sibling
870    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
871    /// partition-witness pin locks the pre-projection classification in
872    /// load-bearing so a peer prefix-set addition that widened one arm's
873    /// accept-set without shrinking the [`Self::is_capability`] accept-set
874    /// surfaces as a test failure at caixa-core build time rather than a
875    /// silent per-consumer split at renderer emit time.
876    ///
877    /// Composes byte-for-byte through the lifted peer trio
878    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
879    /// any future rebrand of any prefix-set const flows through this
880    /// method by construction without a coordinated per-consumer rewrite
881    /// (pinned by the sibling
882    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
883    /// composition-witness).
884    ///
885    /// Note: purely syntactic classification on the `:wit` prefix-set —
886    /// unlike [`Self::target`], which additionally rejects value-shape-
887    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
888    /// package) via [`crate::render::is_wit_world_ref`] and payload-
889    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
890    /// structurally malformed returns `true` from `is_capability()` (the
891    /// prefix set matches nothing), and the surrounding
892    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
893    /// is where the [`AplicacaoError::EmptyWit`] /
894    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
895    /// predicate is the classifier, not the validator.
896    #[must_use]
897    pub fn is_capability(&self) -> bool {
898        !self.is_http() && !self.is_pubsub() && !self.is_store()
899    }
900
901    /// True when this contract's caller equals its callee — a
902    /// structurally degenerate typed edge that no `:contratos` entry can
903    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
904    /// Servico B" is an *inter*-Servico contract between two distinct
905    /// graph nodes). A Servico contracting with itself resolves to an
906    /// in-process call the wasm-engine never routes through the mesh at
907    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
908    /// per-edge policy can express the intended shape — the pub-sub
909    /// path silently rendered a self-allow rule that is a no-op (intra-
910    /// pod traffic bypasses the mesh entirely), and the synchronous
911    /// paths surfaced as a misleading `ContratoCycle` whose path was
912    /// `["cart", "cart"]` — framing a self-edge as a multi-node
913    /// deadlock. Every downstream consumer that must reject the shape
914    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
915    /// gate at caixa-core/src/aplicacao.rs:5559, every future
916    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
917    /// axis, every future adjacency-graph builder that must skip self-
918    /// edges rather than fold them into an incidental cycle) now keys
919    /// off exactly one typed dispatch on the substrate primitive, so
920    /// any future rebrand on the axis (an M4-typed-caller enum whose
921    /// identity comparison rule the accessor could route through, an
922    /// operator-side per-cluster caller/callee-alias table the
923    /// materializer resolves per-CR before the equality probe, a
924    /// promotion of the pointwise `==` to a set-membership check once
925    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
926    /// so a per-replica self-edge is rejected under the same predicate)
927    /// migrates as a single caixa-core edit rather than a coordinated
928    /// rewrite of every downstream self-edge consumer. Composes
929    /// byte-for-byte through the lifted [`Self::source`] /
930    /// [`Self::destination`] scalar accessors — the accessor pair every
931    /// per-`:contratos` scalar-value axis already routes through — so
932    /// any future rebrand of the underlying `:de` / `:para` storage
933    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
934    /// a per-Aplicacao interning arena the M4 CR materializer authors,
935    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
936    /// same one body without a coordinated per-consumer rewrite.
937    ///
938    /// Sibling in shape to the peer per-`:contratos` shape-predicate
939    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
940    /// on the `:wit` world-ref axis — extended onto the per-edge
941    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
942    /// partition the WIT-shape-space; `is_self_loop` partitions the
943    /// caller-callee identity-space. Named `is_self_loop()` to reflect
944    /// the graph-theoretic identity of the shape (a loop from a graph
945    /// node to itself, distinct from the sibling multi-node
946    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
947    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
948    /// variant already carrying the term.
949    #[must_use]
950    pub fn is_self_loop(&self) -> bool {
951        self.source() == self.destination()
952    }
953
954    /// Typed view of the contract's payload target. Enforces that the
955    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
956    /// fields agree, and that each carried value is itself
957    /// value-shape valid:
958    ///
959    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
960    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
961    ///     `PathPrefix` invariant — same shape required of `:entrada
962    ///     :paths`)
963    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
964    ///     non-empty (NATS / Kafka publish without a subject is a
965    ///     no-op subscribe, never the author's intent)
966    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
967    ///     non-empty (an empty slot template addresses the bucket
968    ///     root, defeating the per-key isolation the slot exists for)
969    ///   - Anything else ⇒ none of the three; the contract is a pure
970    ///     typed capability edge with no payload selector.
971    ///
972    /// Translates the Apollo Federation discipline ("conflicts are
973    /// errors at compile time, not warnings at runtime";
974    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
975    /// a contract whose WIT shape disagrees with its target field, or
976    /// whose target field carries a value-shape-invalid string, is a
977    /// build error — not a silent renderer drop. The returned
978    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
979    /// non-empty (and absolute, for `Http`); every downstream consumer
980    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
981    /// the M4 per-edge policy resolver) can rely on that without
982    /// re-checking.
983    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
984        // Route the HTTP-shaped payload-target extraction through the
985        // lifted [`WitContract::endpoint`] accessor rather than the raw
986        // `self.endpoint.as_deref()` field access — the two production
987        // consumers of the per-`:contratos :endpoint` HTTP-shaped
988        // payload-carrier scalar (this method's Http-arm payload
989        // extraction, the [`AplicacaoSpec::validate`] duplicate-
990        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
991        // off exactly one typed dispatch on the substrate primitive, so
992        // any future rebrand on the axis (an M4 per-cluster endpoint-
993        // alias rewrite, a per-CR fully-qualified path prefix the M4
994        // materializer applies per-tenant, an M4 promotion from
995        // `Option<String>` to a typed HTTP path-template enum) migrates
996        // as a single caixa-core edit rather than a coordinated rewrite
997        // of the two call sites — peer of the sibling M3 per-`:placement`
998        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
999        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1000        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1001        let endpoint = self.endpoint();
1002        let subject = self.subject();
1003        // Route the store-arm payload-carrier scalar through the
1004        // lifted [`WitContract::slot`] accessor rather than the raw
1005        // `self.slot.as_deref()` field access — the two production
1006        // consumers of the per-`:contratos :slot` key/value-store-
1007        // shaped payload-carrier scalar (this method's Store-arm
1008        // payload extraction, the [`AplicacaoSpec::validate`]
1009        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1010        // arm) now key off exactly one typed dispatch on the substrate
1011        // primitive. Closes the last unlifted per-`:contratos`
1012        // `Option<String>` axis, completing the payload-carrier
1013        // accessor family peer of the sibling per-`:contratos`
1014        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1015        // (90de675) lifts across the HTTP / pub-sub arms.
1016        let slot = self.slot();
1017        // Route the local `(de, para, wit)` triple-projection closure
1018        // through the lifted [`WitContract::edge_triple`] typed accessor
1019        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1020        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1021        // triple-carrying diagnostic constructors below (wrong-target /
1022        // missing-target on all three payload arms + capability-with-
1023        // payload + invalid-wit) now key off exactly one typed dispatch
1024        // on the substrate-primitive composite projection, sibling to
1025        // the peer [`WitContract::edge_pair`]-routed
1026        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1027        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1028        // diagnostic constructors on the same per-`:contratos`
1029        // diagnostic-construction surface.
1030        let edge = || self.edge_triple();
1031
1032        // The `:wit` value drives every downstream dispatch — the
1033        // is_http/is_pubsub/is_store prefix matchers below, the
1034        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1035        // exclusion. Until this gate landed `target()` accepted any
1036        // non-empty string and silently demoted unrecognized shapes to
1037        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1038        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1039        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1040        // package, the paste-from-binary footgun a multi-line blob
1041        // accidentally landing in the slot, the un-percent-encoded
1042        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1043        // routing, got L4-only" footgun. Empty is still pre-checked at
1044        // the [`AplicacaoSpec::validate`] call site via the narrower
1045        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1046        // validate layer); the value-shape gate here picks up the
1047        // structurally-invalid non-empty cases the empty check misses,
1048        // and remains correct under direct `target()` calls outside
1049        // validate (the predicate's defensive empty arm returns a
1050        // parser-shaped reason rather than silently falling through to
1051        // the Capability arm). Same trajectory as c4213a4 (WitContract
1052        // endpoint/subject/slot value-shape gates lifted into
1053        // `target()`) on the peer payload axes.
1054        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1055            let (de, para, wit) = edge();
1056            return Err(AplicacaoError::ContratoWitInvalid {
1057                de,
1058                para,
1059                wit,
1060                reason,
1061            });
1062        }
1063
1064        if self.is_http() {
1065            if subject.is_some() || slot.is_some() {
1066                let (de, para, wit) = edge();
1067                return Err(AplicacaoError::ContratoWrongTarget {
1068                    de,
1069                    para,
1070                    wit,
1071                    expected: WitTarget::HTTP_FIELD_NAME,
1072                });
1073            }
1074            let ep = endpoint.ok_or_else(|| {
1075                let (de, para, wit) = edge();
1076                AplicacaoError::ContratoMissingTarget {
1077                    de,
1078                    para,
1079                    wit,
1080                    expected: WitTarget::HTTP_FIELD_NAME,
1081                }
1082            })?;
1083            if ep.is_empty() {
1084                let (de, para) = self.edge_pair();
1085                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1086            }
1087            if !ep.starts_with('/') {
1088                let (de, para) = self.edge_pair();
1089                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1090                    de,
1091                    para,
1092                    endpoint: ep.to_string(),
1093                });
1094            }
1095            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1096            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1097            // API v1 HTTPPathMatch.value admission grammar with the
1098            // sibling `:entrada :paths` axis. Until this gate landed
1099            // `target()` only refused the empty string + the missing-
1100            // leading-`/` form; a structurally invalid endpoint
1101            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1102            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1103            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1104            // path-traversal segment, the >1024-byte slug) silently
1105            // passed validate and the failure surfaced at apply time
1106            // as a Cilium policy rejection / silent traffic drop, far
1107            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1108            // grammar `:entrada :paths` already gates (55410e4), now
1109            // shared with `:contratos :endpoint` through the lifted
1110            // `crate::render::is_gateway_api_http_path` predicate.
1111            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1112                let (de, para) = self.edge_pair();
1113                return Err(AplicacaoError::ContratoEndpointInvalid {
1114                    de,
1115                    para,
1116                    endpoint: ep.to_string(),
1117                    reason,
1118                });
1119            }
1120            return Ok(WitTarget::Http { endpoint: ep });
1121        }
1122        if self.is_pubsub() {
1123            if endpoint.is_some() || slot.is_some() {
1124                let (de, para, wit) = edge();
1125                return Err(AplicacaoError::ContratoWrongTarget {
1126                    de,
1127                    para,
1128                    wit,
1129                    expected: WitTarget::PUBSUB_FIELD_NAME,
1130                });
1131            }
1132            let s = subject.ok_or_else(|| {
1133                let (de, para, wit) = edge();
1134                AplicacaoError::ContratoMissingTarget {
1135                    de,
1136                    para,
1137                    wit,
1138                    expected: WitTarget::PUBSUB_FIELD_NAME,
1139                }
1140            })?;
1141            if s.is_empty() {
1142                let (de, para) = self.edge_pair();
1143                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1144            }
1145            // The `:subject` lands at runtime as the NATS subject the
1146            // producer publishes to and the consumer subscribes from.
1147            // Until this gate landed `target()` only refused the
1148            // empty string; a structurally invalid subject
1149            // (`"foo..bar"` — empty token between separators,
1150            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1151            // server's subject parser rejects, `"foo bar"` —
1152            // un-percent-encoded whitespace, `"foo.café"` —
1153            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1154            // empty leading/trailing tokens, the >256-byte
1155            // paste-from-binary slug) silently passed validate and
1156            // the failure surfaced at runtime as a NATS server-side
1157            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1158            // a silent message drop, far from the source caixa.lisp.
1159            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1160            // trajectory `:contratos :endpoint` (4f0390b) and
1161            // `:contratos :wit` (6226bf4) already gate, now shared
1162            // with `:contratos :subject` through the lifted
1163            // `crate::render::is_nats_subject` predicate.
1164            if let Err(reason) = crate::render::is_nats_subject(s) {
1165                let (de, para) = self.edge_pair();
1166                return Err(AplicacaoError::ContratoSubjectInvalid {
1167                    de,
1168                    para,
1169                    subject: s.to_string(),
1170                    reason,
1171                });
1172            }
1173            return Ok(WitTarget::PubSub { subject: s });
1174        }
1175        if self.is_store() {
1176            if endpoint.is_some() || subject.is_some() {
1177                let (de, para, wit) = edge();
1178                return Err(AplicacaoError::ContratoWrongTarget {
1179                    de,
1180                    para,
1181                    wit,
1182                    expected: WitTarget::STORE_FIELD_NAME,
1183                });
1184            }
1185            let sl = slot.ok_or_else(|| {
1186                let (de, para, wit) = edge();
1187                AplicacaoError::ContratoMissingTarget {
1188                    de,
1189                    para,
1190                    wit,
1191                    expected: WitTarget::STORE_FIELD_NAME,
1192                }
1193            })?;
1194            if sl.is_empty() {
1195                let (de, para) = self.edge_pair();
1196                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1197            }
1198            // Value-shape gate on the third (and last) typed payload
1199            // axis the `WitContract::target` dispatch carries — the
1200            // peer of [`crate::render::is_gateway_api_http_path`] for
1201            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1202            // for `:subject` (63e18a0). Until this gate landed
1203            // `target()` only refused the empty string; a structurally
1204            // invalid slot (`"check out/$order"` — un-percent-encoded
1205            // whitespace whose runtime behavior varies unpredictably
1206            // across kv backends, `"checkout/\x01order"` — control
1207            // character that Redis admits but corrupts on next read
1208            // and DynamoDB rejects outright, `"chéckout/$order"` —
1209            // un-percent-encoded non-ASCII byte each backend re-encodes
1210            // differently, `"checkout\n/$order"` — embedded newline,
1211            // the 513-byte paste-from-binary slug) silently passed
1212            // validate and surfaced at runtime as a per-backend kv
1213            // write rejection (DynamoDB / etcd) or as a silent
1214            // next-read corruption (Redis-via-RESP3), far from the
1215            // source caixa.lisp with no field naming which `:contratos`
1216            // edge carried the typo. The lifted predicate makes the
1217            // kv-backend intersection-floor a substrate-level
1218            // invariant at validate time, not a runtime "this passed
1219            // validate but the kv backend rejected on first write"
1220            // surprise — closes the typed payload-axis value-shape
1221            // trajectory across all three legs of the four
1222            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1223            // that caixa-mesh + the future kv emitters land in.
1224            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1225                let (de, para) = self.edge_pair();
1226                return Err(AplicacaoError::ContratoSlotInvalid {
1227                    de,
1228                    para,
1229                    slot: sl.to_string(),
1230                    reason,
1231                });
1232            }
1233            return Ok(WitTarget::Store { slot: sl });
1234        }
1235
1236        // Unrecognized WIT world — must not carry any payload target.
1237        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1238            let (de, para, wit) = edge();
1239            return Err(AplicacaoError::ContratoWrongTarget {
1240                de,
1241                para,
1242                wit,
1243                expected: WitTarget::CAPABILITY_EXPECTED,
1244            });
1245        }
1246        Ok(WitTarget::Capability)
1247    }
1248}
1249
1250/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1251/// gate (see [`AplicacaoSpec::validate`]): every field that
1252/// distinguishes one contract from another, in declaration order
1253/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1254/// with equal [`ContratoIdentity`]s are the same typed edge declared
1255/// twice — the graph-edge analogue of duplicate `:membros` /
1256/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1257/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1258/// clippy's `type_complexity` lint (and so a future axis added to
1259/// `WitContract` is one alias edit, not a coordinated rewrite of
1260/// every set instantiation).
1261pub type ContratoIdentity<'a> = (
1262    &'a str,
1263    &'a str,
1264    &'a str,
1265    Option<&'a str>,
1266    Option<&'a str>,
1267    Option<&'a str>,
1268);
1269
1270/// Typed view of a [`WitContract`]'s payload target. Each variant
1271/// carries the field its WIT shape requires; constructing a `Http`
1272/// view without an endpoint is impossible by the type system.
1273///
1274/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1275/// instead of probing `Option<String>` fields one by one — the
1276/// "which payload field is set?" question is answered once, at
1277/// validation time.
1278#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1279pub enum WitTarget<'a> {
1280    /// HTTP-shaped WIT world. Carries the configured request path.
1281    Http { endpoint: &'a str },
1282    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1283    ///
1284    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1285    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1286    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1287    /// method name byte-identical to the sibling
1288    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1289    /// arm-discriminator that routes through
1290    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1291    /// through `matches!` on the variant), so the two arm-discriminator
1292    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1293    /// every downstream consumer through the same `is_pubsub()` name.
1294    #[is_variant(name = "pubsub")]
1295    PubSub { subject: &'a str },
1296    /// Key-value-shaped WIT world. Carries the slot template.
1297    Store { slot: &'a str },
1298    /// A typed capability edge with no payload selector — the WIT
1299    /// world stands on its own (rare; reserved for plain capability
1300    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1301    Capability,
1302}
1303
1304impl<'a> WitTarget<'a> {
1305    /// Canonical author-facing `:contratos` payload field name for the
1306    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1307    /// [`AplicacaoError::ContratoMissingTarget`] /
1308    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1309    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1310    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1311    /// the `feira app graph` verb prints. Peer of
1312    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1313    /// on the payload-field-name axis; declared as a peer const next
1314    /// to the [`WitTarget::Http`] variant so a future rename on the
1315    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1316    /// :endpoint …)))` field lands in exactly one place, not scattered
1317    /// across the [`WitContract::target`] gate's six `expected:`
1318    /// literals, the label template, and every downstream consumer
1319    /// that prints a per-arm prefix. Same trajectory as the peer
1320    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1321    /// for the arm's shape, next to the variant declaration.
1322    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1323    /// Canonical author-facing `:contratos` payload field name for the
1324    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1325    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1326    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1327    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1328    /// Canonical author-facing `:contratos` payload field name for the
1329    /// key/value-store-shaped arm. Peer of
1330    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1331    /// on the payload-field-name axis; see
1332    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1333    pub const STORE_FIELD_NAME: &'static str = "slot";
1334
1335    /// Canonical stable human-readable label the payload-less
1336    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1337    /// the byte-string every consumer that formats a payload-less
1338    /// typed capability edge as text lands on (the
1339    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1340    /// naming which identical edge was declared twice, the future
1341    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1342    /// policy resolver's audit view, the operator's mesh-graph audit).
1343    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1344    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1345    /// author-facing label-scalar consts — the same
1346    /// "one canonical declaration per arm, next to the variant, so a
1347    /// future rename lands in one place" discipline extended to the
1348    /// payload-less arm. Until this lift landed the byte-string sat
1349    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1350    /// match arm, once in the pin test asserting the label's
1351    /// [`WitTarget::Capability`] output — with no compile-time link
1352    /// between the two: a rebrand on either side (an operator-facing
1353    /// vocabulary shift, a per-consumer disambiguation like
1354    /// `"(capability — no payload; typed edge only)"`) would silently
1355    /// desynchronize until a downstream consumer surfaced the drift at
1356    /// runtime.
1357    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1358
1359    /// Canonical `expected:` scalar the
1360    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1361    /// through for the payload-less [`WitTarget::Capability`] arm — the
1362    /// byte-string authors read as "this WIT world's shape is not one
1363    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1364    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1365    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1366    /// [`Self::STORE_FIELD_NAME`] consts on the
1367    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1368    /// same "which payload field name goes in the diagnostic" dispatch
1369    /// the three payload-arm consts cover, extended to the payload-less
1370    /// arm. Until this lift landed the byte-string sat twice — once
1371    /// inline in the [`Self::target`] Capability-arm rejection at the
1372    /// production dispatch, once in the pin test asserting the
1373    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1374    /// no compile-time link between the two: a rebrand on either side
1375    /// (an author-facing vocabulary shift to `"capability"` /
1376    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1377    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1378    /// [`WitTarget::Capability`] into per-shape peers) would silently
1379    /// desynchronize until a downstream consumer surfaced the drift at
1380    /// runtime. Same "one canonical declaration per arm, next to the
1381    /// variant, so a future rename lands in one place" discipline the
1382    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1383    /// established for the payload-less arm's human-readable label
1384    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1385    /// so both halves of the "how does the Capability arm surface at
1386    /// its two consumer axes (human-readable label, wrong-target
1387    /// diagnostic)" pipeline route through peer consts declared next
1388    /// to the variant.
1389    ///
1390    /// Pairwise-distinctness against the three payload-arm scalars
1391    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1392    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1393    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1394    /// test — the 4-way closure of the 3-way
1395    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1396    /// the `ContratoWrongTarget::expected` axis, matching the peer
1397    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1398    /// scalar-value distinctness discipline the sibling M3 typed-enum
1399    /// discriminator axis already carries.
1400    pub const CAPABILITY_EXPECTED: &'static str = "none";
1401
1402    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1403    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1404    /// as under [`Self::graph_label`] — the sibling
1405    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1406    /// payload-column axis (the graph verb spells payload-less as
1407    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1408    /// diagnostic's `(capability — no payload)` on the human-readable
1409    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1410    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1411    /// family — extends the "one canonical declaration per arm, next to
1412    /// the variant, so a future rename lands in one place" discipline
1413    /// onto the third payload-less-arm consumer axis (`feira app graph`
1414    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1415    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1416    /// axis).
1417    ///
1418    /// Until this lift landed the byte-string sat inline in
1419    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1420    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1421    /// `"(capability-only)".to_string()` literal, with no compile-time link
1422    /// back to the [`WitTarget::Capability`] variant declaration nor to
1423    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1424    /// peer consts already carrying the "one canonical declaration per
1425    /// payload-less-arm consumer axis" discipline. A rebrand on either
1426    /// side (the graph verb's operator-facing vocabulary tightening from
1427    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1428    /// the WIT registry vocabulary sharpens, an M4 split of
1429    /// [`Self::Capability`] into per-shape peers) would silently
1430    /// desynchronize the graph-verb byte-string from the paired
1431    /// per-arm-adjacent const and land two spellings of the same axis in
1432    /// two spots.
1433    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1434
1435    /// The `(author-facing field name, payload)` pair this typed target
1436    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1437    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1438    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1439    /// [`Self::Store`], `None` for the payload-less
1440    /// [`Self::Capability`] arm.
1441    ///
1442    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1443    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1444    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1445    /// (returns the first component) route through, so a future
1446    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1447    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1448    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1449    /// exactly one new match-arm here (a compile-time exhaustiveness
1450    /// error otherwise), not a coordinated three-way rewrite of the
1451    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1452    /// + every downstream consumer that reaches for the pair.
1453    ///
1454    /// Until this lift landed the three payload arms sat in
1455    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1456    /// invocations (one per variant, each hand-quoting the paired
1457    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1458    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1459    /// "same shape, written N times" duplication THEORY.md §I.3.5
1460    /// ("Generation first, composition second, hand-authoring last;
1461    /// the duplication budget is zero") promotes to a build-time
1462    /// concern, with each per-arm site paired to its own const with no
1463    /// compile-time link between the format template and the arm's
1464    /// payload extraction.
1465    #[must_use]
1466    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1467        match *self {
1468            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1469            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1470            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1471            WitTarget::Capability => None,
1472        }
1473    }
1474
1475    /// The canonical author-facing `:contratos` payload field name
1476    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1477    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1478    /// `None` for the payload-less `Capability` arm.
1479    ///
1480    /// Routes through [`Self::payload_pair`] — the single 4-arm
1481    /// dispatch [`Self::label`] also reads — so a future variant
1482    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1483    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1484    /// dispatch, thin projections at each consumer" trajectory the
1485    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1486    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1487    #[must_use]
1488    pub const fn field_name(&self) -> Option<&'static str> {
1489        match self.payload_pair() {
1490            Some((f, _)) => Some(f),
1491            None => None,
1492        }
1493    }
1494
1495    /// The underlying scalar the payload-carrying arm carries — the
1496    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1497    /// subject ([`Self::PubSub`] `:subject`), or slot template
1498    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1499    /// `&'a str` storage — or `None` on the payload-less
1500    /// [`Self::Capability`] arm.
1501    ///
1502    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1503    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1504    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1505    /// the paired sub-selector axis. Both per-half accessors read from
1506    /// one authoritative match, so a future [`WitTarget`] variant
1507    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1508    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1509    /// on [`Self::payload_pair`] and both per-half projections + every
1510    /// downstream consumer picks the new arm up by construction — no
1511    /// coordinated N-way rewrite across the paired accessor dispatches,
1512    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1513    /// and every future WIT-registry-shaped consumer.
1514    ///
1515    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1516    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1517    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1518    /// both per-half projections as thin readers, every downstream
1519    /// consumer through the same match" discipline extended onto the
1520    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1521    /// gap between the two paired-dispatch surfaces: the peer
1522    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1523    /// the first-component projection until this lift; the second-
1524    /// component sibling now sits alongside so both halves reach every
1525    /// future consumer through the same substrate-primitive dispatch.
1526    ///
1527    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1528    #[must_use]
1529    pub const fn payload(&self) -> Option<&'a str> {
1530        match self.payload_pair() {
1531            Some((_, p)) => Some(p),
1532            None => None,
1533        }
1534    }
1535
1536    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1537    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1538    /// returns the [`Self::Http`]-arm's author-declared request path
1539    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1540    /// projected target is [`Self::Http { endpoint }`], `None` on the
1541    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1542    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1543    /// definition).
1544    ///
1545    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1546    /// `path:` rule payload every substrate-side L7-introspecting
1547    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1548    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1549    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1550    /// on the L7 introspection branch; every peer WIT shape stays
1551    /// L4-only because Cilium can't introspect NATS / key-value / plain
1552    /// capability edges), and every future L7-introspecting consumer
1553    /// of the projected target's HTTP endpoint (the future M4
1554    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1555    /// materializer's per-edge L7 admission-webhook overlay, the
1556    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1557    /// path bucket-key resolver, the future per-`:contratos`-edge
1558    /// mTLS-required overlay's HTTP-shape scope filter, the future
1559    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1560    /// through the same typed dispatch.
1561    ///
1562    /// Prior to this lift the sole production consumer of the projected-
1563    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1564    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1565    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1566    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1567    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1568    /// match that expressed no compile-time link back to the substrate
1569    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1570    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1571    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1572    /// with no post-projection peer on the typed-view surface. A future
1573    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1574    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1575    /// gRPC-shaped worlds per this enum's own docstring at
1576    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1577    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1578    /// would have had to be threaded through the caixa-mesh L7 emit
1579    /// branch's raw `if let` in lockstep — either coalescing the two
1580    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1581    /// emit path per-arm — with no substrate-primitive dispatch making
1582    /// the "which arms count as L7-HTTP-shaped for path-emission
1583    /// purposes" question the substrate's answer to give. Lifting the
1584    /// resolution to a typed method on the substrate primitive means
1585    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1586    /// projected-target HTTP endpoint reaches for exactly one typed
1587    /// dispatch — the resolver's accept-set migrates as a unit on any
1588    /// future arm-family widening, and the caixa-mesh L7 emit branch
1589    /// reads through the same substrate primitive.
1590    ///
1591    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1592    /// (7020470) `Option<&str>` scalar accessor on the raw
1593    /// `:contratos :endpoint` field-access axis — same "one typed
1594    /// dispatch on the substrate primitive, thin projections at each
1595    /// consumer" discipline extended onto the peer post-projection typed-
1596    /// view surface (the [`WitContract::endpoint`] pre-projection
1597    /// accessor returns `Some` for any author-declared `:endpoint`
1598    /// value regardless of the paired `:wit` world's HTTP-shape
1599    /// classification — the raw slot before validation crosses it —
1600    /// while this post-projection [`Self::http_endpoint`] accessor
1601    /// returns `Some` iff the target has been projected onto the
1602    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1603    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1604    /// coherence; the two accessors close the pre-projection /
1605    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1606    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1607    /// the three payload-carrying arms) — extends the per-arm
1608    /// projection family onto the [`Self::Http`] specialization axis
1609    /// that the pan-arm accessor's shape blends into a single arm-
1610    /// agnostic view; paired with [`Self::pubsub_subject`] /
1611    /// [`Self::store_slot`] on the sibling per-arm axes so every
1612    /// per-payload-arm shape carries a named post-projection accessor
1613    /// on the same shape as `http_endpoint`, closing the per-arm-shape
1614    /// accept-set the substrate primitive owns.
1615    #[must_use]
1616    pub const fn http_endpoint(&self) -> Option<&'a str> {
1617        match *self {
1618            WitTarget::Http { endpoint } => Some(endpoint),
1619            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1620        }
1621    }
1622
1623    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1624    /// consumer that fans on the pub-sub-shaped payload keys off —
1625    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1626    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1627    /// the projected target is [`Self::PubSub { subject }`], `None` on
1628    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1629    /// [`Self::Capability`], each of which carries no NATS-shaped
1630    /// subject by definition).
1631    ///
1632    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1633    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1634    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1635    /// CR materializer's `spec.subjects[]` projection, the future
1636    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1637    /// bucket-key resolver, the future `feira app graph --pubsub`
1638    /// per-Aplicacao subject column, any future substrate-lifted
1639    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
1640    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
1641    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
1642    /// future pub-sub-shape consumer reaches for the same typed
1643    /// dispatch this accessor exposes so the "which arm carries the
1644    /// subject scalar?" answer lives at one caixa-core edit rather
1645    /// than open-coded across per-consumer `if let WitTarget::PubSub
1646    /// { subject } = c.target()…` pattern-matches.
1647    ///
1648    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
1649    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
1650    /// the pre-projection [`WitContract::subject`] scalar accessor on
1651    /// the raw `:contratos :subject` field-access axis — same "one
1652    /// typed dispatch on the substrate primitive, thin projections at
1653    /// each consumer" discipline extended onto the per-arm pub-sub
1654    /// post-projection axis. The pre-projection accessor returns
1655    /// `Some` for any author-declared `:subject` value regardless of
1656    /// the paired `:wit` world's pub-sub-shape classification (the raw
1657    /// slot before validation crosses it); this post-projection
1658    /// accessor returns `Some` iff the target has been projected onto
1659    /// the [`Self::PubSub`] arm, i.e. only after the
1660    /// [`WitContract::target`] gate has admitted the
1661    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
1662    /// the pre-/post-projection pair on the pub-sub-subject axis to
1663    /// match the pair the [`WitContract::endpoint`] +
1664    /// [`Self::http_endpoint`] surfaces already close on the peer
1665    /// HTTP-endpoint axis.
1666    ///
1667    /// Sibling of the unified pan-arm [`Self::payload`]
1668    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1669    /// extends the per-arm projection family onto the [`Self::PubSub`]
1670    /// specialization axis that the pan-arm accessor's shape blends
1671    /// into a single arm-agnostic view; the pair
1672    /// (`pubsub_subject`, `store_slot`) closes the trio
1673    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
1674    /// payload arm now carries its own per-arm-shape post-projection
1675    /// accessor.
1676    #[must_use]
1677    pub const fn pubsub_subject(&self) -> Option<&'a str> {
1678        match *self {
1679            WitTarget::PubSub { subject } => Some(subject),
1680            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1681        }
1682    }
1683
1684    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
1685    /// every consumer that fans on the store-shaped payload keys off —
1686    /// returns the [`Self::Store`]-arm's author-declared slot template
1687    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
1688    /// projected target is [`Self::Store { slot }`], `None` on the
1689    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
1690    /// [`Self::Capability`], each of which carries no
1691    /// key/value-store slot by definition).
1692    ///
1693    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
1694    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
1695    /// every future substrate-side store-introspecting per-`(:de,
1696    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
1697    /// namespace / prefix reconciler's per-slot projection, the future
1698    /// per-store-backend routing overlay's slot-shape gate, the future
1699    /// `feira app graph --store` per-Aplicacao slot column, any future
1700    /// substrate-lifted store-shape emitter that reads a projected
1701    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
1702    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
1703    /// Every future store-shape consumer reaches for the same typed
1704    /// dispatch this accessor exposes so the "which arm carries the
1705    /// slot scalar?" answer lives at one caixa-core edit rather than
1706    /// open-coded across per-consumer
1707    /// `if let WitTarget::Store { slot } = c.target()…`
1708    /// pattern-matches.
1709    ///
1710    /// Peer of the sibling [`Self::http_endpoint`] +
1711    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
1712    /// axes and of the pre-projection [`WitContract::slot`] scalar
1713    /// accessor on the raw `:contratos :slot` field-access axis — same
1714    /// "one typed dispatch on the substrate primitive, thin projections
1715    /// at each consumer" discipline extended onto the per-arm store
1716    /// post-projection axis. Closes the pre-/post-projection pair on
1717    /// the store-slot axis to match the pairs the
1718    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
1719    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
1720    /// already close on the peer HTTP-endpoint and pub-sub-subject
1721    /// axes; the substrate-side pre-/post-projection accessor family
1722    /// now spans all three payload arms as a matched trio, so any
1723    /// future arm-shape widening (a `Rest`/`Grpc` split of
1724    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
1725    /// lands one accessor without threading through the sibling
1726    /// pre-projection or the peer per-arm post-projection surfaces a
1727    /// compile-time exhaustiveness error at the substrate primitive,
1728    /// not a silent per-consumer split at renderer emit time.
1729    ///
1730    /// Sibling of the unified pan-arm [`Self::payload`]
1731    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1732    /// closes the per-arm projection family onto the [`Self::Store`]
1733    /// specialization axis that the pan-arm accessor's shape blends
1734    /// into a single arm-agnostic view. The trio
1735    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
1736    /// pan-arm accept-set on every payload-carrying arm: exactly one
1737    /// per-arm accessor returns `Some(payload)` and the two peers
1738    /// return `None`, and every payload-less [`Self::Capability`]
1739    /// input returns `None` on all three — the partition the sibling
1740    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
1741    /// pin locks in load-bearing.
1742    #[must_use]
1743    pub const fn store_slot(&self) -> Option<&'a str> {
1744        match *self {
1745            WitTarget::Store { slot } => Some(slot),
1746            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
1747        }
1748    }
1749
1750    /// Render this typed target as a stable human-readable label
1751    /// (`:endpoint "/charge"`, `:subject "events.x"`,
1752    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1753    /// the WIT world is a pure capability edge).
1754    ///
1755    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1756    /// gate so the diagnostic names *which* identical edge was
1757    /// declared twice (not just which `(de, para, wit)` triple).
1758    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1759    /// on the payload-carrying arms (`Some((field, payload)) →
1760    /// format!(":{field} {payload:?}")`) and through the lifted
1761    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1762    /// [`Self::Capability`] arm — so a future variant addition (the
1763    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1764    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1765    /// `Queue`-shaped peer) becomes a single new match-arm on
1766    /// [`Self::payload_pair`] rather than a rewrite of this template
1767    /// (and every downstream consumer that reaches for the label
1768    /// shape: the per-edge policy resolver in M4, the `feira app
1769    /// graph` view, the operator's mesh-graph audit). Until this
1770    /// lift landed the three payload arms carried three near-identical
1771    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1772    /// [`Self::Capability`] arm carried the payload-less byte-string
1773    /// twice (once inline here, once in the pin test) — closing the
1774    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1775    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1776    /// / 4a1e490) peer-const lifts already established for the
1777    /// payload-carrying arms.
1778    #[must_use]
1779    pub fn label(&self) -> String {
1780        match self.payload_pair() {
1781            Some((field, payload)) => format!(":{field} {payload:?}"),
1782            None => Self::CAPABILITY_LABEL.to_string(),
1783        }
1784    }
1785
1786    /// Render this typed target as the `feira app graph` per-`:contratos`
1787    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
1788    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
1789    /// payload-less arm).
1790    ///
1791    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1792    /// on the payload-carrying arms (`Some((field, payload)) →
1793    /// format!("{field}={payload}")`) and through the lifted
1794    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
1795    /// [`Self::Capability`] arm — so a future variant addition
1796    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
1797    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1798    /// `Queue`-shaped peer) becomes one match-arm edit at
1799    /// [`Self::payload_pair`], propagating through this graph-verb
1800    /// projection at zero call-site cost, sibling to the peer
1801    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
1802    /// same 4-arm dispatch.
1803    ///
1804    /// Until this lift landed the [`caixa-feira`]
1805    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
1806    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
1807    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
1808    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
1809    /// `format!("{}={endpoint}", ...)` template and hard-coding
1810    /// `"(capability-only)"` as a fifth payload-less scalar with no link
1811    /// back to the paired [`WitTarget::Capability`] variant declaration.
1812    /// A future variant addition would have had to be threaded through
1813    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
1814    /// verb's inline match in lockstep or the two projections would
1815    /// silently disagree on the arm-set the graph verb prints — the
1816    /// duplicate-`:contratos` diagnostic reading one shape while the
1817    /// graph verb's payload column silently dropped the new arm to
1818    /// `(capability-only)`. Lifting the graph-verb projection onto the
1819    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
1820    /// the axis: both projections migrate as a unit.
1821    ///
1822    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
1823    /// quoting) shape is graph-verb-canonical — distinct from the
1824    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
1825    /// duplicate-`:contratos` diagnostic seeds (see
1826    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
1827    /// on the payload-less axis for the paired distinction).
1828    #[must_use]
1829    pub fn graph_label(&self) -> String {
1830        match self.payload_pair() {
1831            Some((field, payload)) => format!("{field}={payload}"),
1832            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
1833        }
1834    }
1835}
1836
1837/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1838/// pretty-printed byte-string every consumer that formats a typed
1839/// payload target as user-facing text lands on (the
1840/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1841/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1842/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1843/// graph` per-`:contratos`-edge payload column that reaches the graph
1844/// verb through `format!("{target}")`, the future M4 per-edge policy
1845/// resolver's per-edge audit-log line, the operator's mesh-graph
1846/// per-edge inspection view) reaches for the same lifted
1847/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1848/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1849/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1850/// routes through — extending the three-path-convergence
1851/// (`Debug` for structural inspection, `Display` for user-facing text,
1852/// per-arm typed accessor for the canonical byte-string) discipline the
1853/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1854/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1855/// onto the fourth (and only remaining) typed-shape-discriminator axis
1856/// on the caixa surface.
1857///
1858/// Pre-lift the two paths were structurally independent — every consumer
1859/// reaching for a payload byte-string past the [`WitTarget::label`]
1860/// helper had to pick between three paths ([`WitTarget::label`],
1861/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1862/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1863/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1864/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1865/// that reached for `format!("{target}")` — the canonical shape every
1866/// user-facing pretty-print site on the sibling typed-enum axes already
1867/// uses — would silently land on the `Debug` derive's structural output
1868/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1869/// than the `label()` helper's stable byte-string (`:endpoint
1870/// "/charge"` — the author-facing `:contratos` keyword form) the
1871/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1872/// already threads through. The two spellings would diverge silently in
1873/// every downstream diagnostic / graph / audit line reached through
1874/// `format!` rather than through the `label()` helper. Routing
1875/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1876/// path: every `format!("{v}")` call reaches the same
1877/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1878/// and the duplicate-`:contratos` gate already route through, so a
1879/// future variant addition (the M4-and-later per-edge WIT registry may
1880/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1881/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1882/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1883/// match — rather than fanning out through hand-rolled per-arm
1884/// [`std::fmt::Display`] arms.
1885///
1886/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1887/// is the typed view returned by [`WitContract::target`], not a
1888/// closed-set discriminator enum with a gen-platform Discriminant
1889/// registration, so the `Debug` derive's structural output (which every
1890/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1891/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1892/// shape for structural inspection; `Display` (via `label`) reveals the
1893/// stable author-facing payload projection.
1894///
1895/// Pin tests
1896/// [`tests::wit_target_display_routes_through_label_helper`] and
1897/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1898/// assert the two paths agree byte-for-byte on every variant, so a
1899/// future variant addition or `label()` reimplementation that hand-rolls
1900/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1901/// build error visible at caixa-core test time, not a silent
1902/// per-consumer dispatch miss at diagnostic / audit / graph time.
1903impl std::fmt::Display for WitTarget<'_> {
1904    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1905        f.write_str(&self.label())
1906    }
1907}
1908
1909// ── one Aplicacao member ─────────────────────────────────────────────
1910
1911/// A Servico participating in the Aplicacao. Same shape as
1912/// `crate::supervisor::ChildSpec` but without a restart policy —
1913/// supervision is per-Servico (each member has its own
1914/// `:supervisor`), the Aplicacao orchestrates *placement*.
1915#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1916#[serde(rename_all = "camelCase")]
1917pub struct Membro {
1918    /// Member caixa's `:nome`. Resolves through the same dep
1919    /// resolution path as `crate::dep::Dep`.
1920    pub caixa: String,
1921
1922    /// Semver constraint.
1923    pub versao: String,
1924}
1925
1926impl Membro {
1927    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1928    /// accessor every consumer that reads the member's Servico identity
1929    /// keys off — returns the author-declared `:membros :caixa`
1930    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1931    /// own [`String`] storage.
1932    ///
1933    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1934    /// participating in the Aplicacao — validated by
1935    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1936    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1937    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1938    /// [`validate_no_self_membership`]) — and every downstream consumer
1939    /// that fans on the member's identity keys off this scalar (the
1940    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1941    /// lookup, the per-`:membros` duplicate gate's dedup key, the
1942    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1943    /// identity, the self-membership gate, the
1944    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1945    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1946    /// CR materializer's per-member resolver).
1947    ///
1948    /// Prior to this lift the `.caixa` byte-string was read inline at
1949    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1950    /// set collector at
1951    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1952    /// [`validate_membros`] validation-side member-caixa gate at
1953    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1954    /// per-member duplicate-gate dedup key at
1955    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1956    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1957    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1958    /// [`validate_no_self_membership`] self-loop gate at
1959    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1960    /// expressed no compile-time link back to the typed slot. Every
1961    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1962    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1963    /// `name:` axis, so a future extension of the `:membros :caixa`
1964    /// axis to a richer author surface — a per-cluster alias table the
1965    /// operator pins through a future `:placement`-scoped slot, a
1966    /// namespace-qualified rewrite the M4 CR materializer applies
1967    /// per-CR, a per-member overlay from the future `:membros
1968    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1969    /// acknowledges — would have had to be threaded through every
1970    /// open-coded copy in lockstep or one consumer would silently
1971    /// disagree with the peers on which caixa a given member resolves
1972    /// to. A member-set lookup that treated the name as `"cart"` while
1973    /// the peer adjacency map treated it as `"tenant-a/cart"` would
1974    /// silently split the `:contratos` membership-lookup diagnostic from
1975    /// the cycle-detector's node identity — a two-consumer split at the
1976    /// validator far from the source `caixa.lisp` with no field naming
1977    /// the identity-drift root cause. Lifting the resolution rule to a
1978    /// typed method on the substrate primitive means every downstream
1979    /// consumer of the Aplicacao's per-`:membros` identity surface
1980    /// reaches for exactly one typed dispatch — the resolver's
1981    /// accept-set migrates as a unit on any future axis addition.
1982    ///
1983    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1984    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1985    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1986    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1987    /// destination-Servico scalar accessors — same "one typed dispatch
1988    /// on the substrate primitive, thin projections at each consumer"
1989    /// discipline extended onto the per-`:membros` member-caixa `:nome`
1990    /// byte-string axis. Named `nome()` to match the tatara-lisp
1991    /// author-surface term the field's docstring already reaches for
1992    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1993    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1994    /// already carries — the accessor's name maps directly onto the
1995    /// canonical caixa-identity vocabulary rather than shadowing the
1996    /// field's storage-side `caixa` label.
1997    #[must_use]
1998    pub fn nome(&self) -> &str {
1999        self.caixa.as_str()
2000    }
2001
2002    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2003    /// requirement scalar accessor every consumer that reads the
2004    /// member's version pin keys off — returns the author-declared
2005    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2006    /// from the typed slot's own [`String`] storage.
2007    ///
2008    /// The `:membros :versao` slot carries the Cargo-shaped semver
2009    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2010    /// pins which release of the member-caixa the Aplicacao composes
2011    /// against — the same requirement grammar the peer `:deps :versao`
2012    /// / `:children :versao` axes carry, resolved through the shared
2013    /// [`crate::render::require_valid_versao_requirement`] cascade and
2014    /// the shared [`crate::version::parse_requirement`] parser. Every
2015    /// downstream consumer that fans on the member's version pin keys
2016    /// off this scalar (the [`validate_membros`] per-member requirement
2017    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2018    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2019    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2020    /// version-lock overlay the operator pins through a future
2021    /// `:placement`-scoped slot, the future
2022    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2023    /// version resolver, the future `feira app deploy` pipeline's
2024    /// per-member lacre BLAKE3-closure lookup).
2025    ///
2026    /// Prior to this lift the `.versao` byte-string was accessed inline
2027    /// at two `&str`-shaped sites — the [`validate_membros`]
2028    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2029    /// …)` and the `feira app graph` per-member printer's `println!(
2030    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2031    /// prior to this lift) — two open-coded field-accesses that expressed
2032    /// no compile-time link back to the typed slot. A future extension of
2033    /// the `:membros :versao` axis to a richer author surface (a
2034    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2035    /// flow, a lacre-projected concrete-version rewrite the operator
2036    /// materializes at CR-admission time, a future `:membros :versao-lock`
2037    /// per-cluster override slot) would have had to be threaded through
2038    /// every open-coded copy in lockstep or one consumer would silently
2039    /// disagree with the peers on which release constraint a given
2040    /// member resolves to. Lifting the resolution rule to a typed method
2041    /// on the substrate primitive means every downstream requirement-
2042    /// facing consumer reaches for exactly one typed dispatch — the
2043    /// resolver's accept-set migrates as a unit on any future axis
2044    /// addition.
2045    ///
2046    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2047    /// member-caixa `:nome` scalar accessor — the pair
2048    /// `(nome(), versao_requirement())` jointly projects the
2049    /// `(caixa, versao)` field pair every renderer that fans on
2050    /// per-member identity + version pin keys off, closing the last
2051    /// unlifted per-`:membros` scalar axis so every downstream
2052    /// per-`:membros` reader now routes through a typed dispatch on the
2053    /// substrate primitive. Named `versao_requirement()` rather than
2054    /// `versao()` because the field's storage-side `.versao` label is
2055    /// already the author-surface term (`:versao`); the accessor's name
2056    /// carries the semantic role — the semver *requirement* string the
2057    /// shared [`crate::version::parse_requirement`] entry-point consumes
2058    /// — so a raw field access and a typed dispatch read differently at
2059    /// every consumer site.
2060    ///
2061    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2062    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2063    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2064    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2065    /// destination-Servico scalar accessors — same "one typed dispatch
2066    /// on the substrate primitive, thin projections at each consumer"
2067    /// discipline extended onto the per-`:membros` member-`:versao`
2068    /// semver-requirement byte-string axis.
2069    #[must_use]
2070    pub fn versao_requirement(&self) -> &str {
2071        self.versao.as_str()
2072    }
2073}
2074
2075// ── mesh-level policies ──────────────────────────────────────────────
2076
2077/// Mesh policies that apply to every `:contratos` edge unless
2078/// overridden per-edge in M4. V0 is a single global policy block.
2079#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2080#[serde(rename_all = "camelCase")]
2081pub struct MeshPolicy {
2082    /// Per-call timeout. Authored as a duration string (`"30s"`).
2083    #[serde(
2084        default,
2085        skip_serializing_if = "Option::is_none",
2086        with = "supervisor::duration_codec"
2087    )]
2088    pub timeout: Option<Duration>,
2089
2090    /// Number of retries on transient failure. None = no retries.
2091    #[serde(default, skip_serializing_if = "Option::is_none")]
2092    pub retries: Option<u32>,
2093
2094    /// Circuit breaker config. Trips after N failures within W
2095    /// duration; closes after a cooldown.
2096    #[serde(default, skip_serializing_if = "Option::is_none")]
2097    pub circuit_breaker: Option<CircuitBreaker>,
2098
2099    /// Whether mTLS is required for every contrato. Default: true
2100    /// (sandboxing-by-default; explicit opt-out only).
2101    #[serde(default, skip_serializing_if = "Option::is_none")]
2102    pub mtls_required: Option<bool>,
2103
2104    /// Token-bucket rate limit. Authored as `"100/s"` or
2105    /// `"5000/m"`; stored as `(rate, window)`.
2106    #[serde(
2107        default,
2108        skip_serializing_if = "Option::is_none",
2109        with = "rate_limit_codec"
2110    )]
2111    pub rate_limit: Option<RateLimit>,
2112}
2113
2114impl MeshPolicy {
2115    /// True when no `:politicas` axis carries a value — every field is
2116    /// `None`. The same emptiness contract every other M2/M3 typed
2117    /// surface carries ([`crate::LimitsSpec::is_empty`],
2118    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2119    /// typed slot onto a cluster artifact key off this predicate to
2120    /// decide "emit the slot" vs "skip the slot entirely", so an
2121    /// authored-but-unset `:politicas (())` round-trips to a rendered
2122    /// artifact that's structurally identical to one that omits the
2123    /// slot. Lifted as a typed predicate (rather than per-renderer
2124    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2125    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2126    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2127    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2128    /// not a coordinated rewrite of every consumer that's reaching
2129    /// for the emptiness semantic.
2130    #[must_use]
2131    pub const fn is_empty(&self) -> bool {
2132        self.timeout().is_none()
2133            && self.retries().is_none()
2134            && self.circuit_breaker().is_none()
2135            && self.mtls_required().is_none()
2136            && self.rate_limit().is_none()
2137    }
2138
2139    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2140    /// per-call-deadline scalar accessor every consumer of the
2141    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2142    /// returns the author-declared `:politicas :timeout` typed
2143    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2144    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2145    /// is `Copy`, so the accessor returns by value; no borrow of
2146    /// `&self` past the call). `None` when the slot is absent (the
2147    /// "cluster default applies — typically the gateway class's
2148    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2149    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2150    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2151    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2152    /// round-trips to a rendered `HTTPRoute` structurally identical to
2153    /// one that omits the slot).
2154    ///
2155    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2156    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2157    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2158    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2159    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2160    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2161    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2162    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2163    /// Every downstream consumer that reads the per-call cap keys off
2164    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2165    /// renderers key off to decide "emit :politicas overlay" vs "skip
2166    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2167    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2168    /// fans the deadline into every rule via
2169    /// [`crate::render::single_field_overlay`], the future M4 per-
2170    /// Aplicacao Gateway API reconciler materialization pass, the
2171    /// future per-`:contratos`-edge timeout-override overlay the
2172    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2173    ///
2174    /// Prior to this lift the `.timeout` field was accessed inline at
2175    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2176    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2177    /// …)` call — two open-coded field-accesses that expressed no
2178    /// compile-time link back to the typed slot. A future extension of
2179    /// the `:politicas :timeout` axis to a richer author surface — a
2180    /// per-`:contratos`-edge timeout override the operator pins through
2181    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2182    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2183    /// M4 CR materializer resolves per-CR, a split of the single
2184    /// per-call `Duration` into a richer `{request, backendRequest}`
2185    /// pair once the Gateway API's per-rule `timeouts` block grows the
2186    /// upstream-facing backendRequest arm alongside the client-facing
2187    /// request arm — would have had to be threaded through both open-
2188    /// coded copies in lockstep or the emptiness predicate and the
2189    /// caixa-mesh emit path would silently disagree on which per-call
2190    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2191    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2192    /// == false` while the renderer's overlay-emit path silently read
2193    /// a drifted other value, or vice versa: an author's `:timeout
2194    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2195    /// the emptiness predicate still classified the policy as non-
2196    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2197    /// | grep -A2 timeouts` audit would land on a route whose author's
2198    /// typed slot value silently vanished at the renderer layer).
2199    /// Lifting the resolution to a typed method on the substrate
2200    /// primitive means every downstream consumer of the Aplicacao's
2201    /// per-`:politicas` deadline surface reaches for exactly one typed
2202    /// dispatch — the resolver's accept-set migrates as a unit on any
2203    /// future axis addition.
2204    ///
2205    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2206    /// family (sibling of the peer per-`:politicas`
2207    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2208    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2209    /// `Option<bool>` accessor — same "one typed dispatch on the
2210    /// substrate primitive, thin projections at each consumer"
2211    /// discipline extended onto the peer per-`:politicas` typed-
2212    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2213    /// numeric-Copy-T scalar" projection pattern the sibling
2214    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2215    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2216    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2217    /// than a scalar). Named `timeout()` to match the storage field's
2218    /// name; the accessor's identity maps onto the canonical MESH-
2219    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2220    #[must_use]
2221    pub const fn timeout(&self) -> Option<Duration> {
2222        self.timeout
2223    }
2224
2225    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2226    /// retry-budget scalar accessor every consumer of the Aplicacao's
2227    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2228    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2229    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2230    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2231    /// value; no borrow of `&self` past the call). `None` when the slot
2232    /// is absent (the "cluster default applies — typically 'no retries
2233    /// beyond a single dispatch attempt'" arm the caixa-mesh
2234    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2235    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2236    /// this predicate too, so an authored-but-unset `:politicas
2237    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2238    /// identical to one that omits the slot).
2239    ///
2240    /// The `:politicas :retries` slot carries the "transient failure
2241    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2242    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2243    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2244    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2245    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2246    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2247    /// Every downstream consumer that reads the retry cap keys off this
2248    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2249    /// renderers key off to decide "emit :politicas overlay" vs "skip
2250    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2251    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2252    /// the value into every rule via [`crate::render::single_field_overlay`],
2253    /// the future M4 per-Aplicacao Gateway API reconciler
2254    /// materialization pass, the future per-`:contratos`-edge retry-
2255    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2256    /// acknowledges).
2257    ///
2258    /// Prior to this lift the `.retries` field was accessed inline at
2259    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2260    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2261    /// …)` call — two open-coded field-accesses that expressed no
2262    /// compile-time link back to the typed slot. A future extension of
2263    /// the `:politicas :retries` axis to a richer author surface — a
2264    /// per-`:contratos`-edge retry override the operator pins through a
2265    /// future `:contratos :retries` slot, a per-cluster retry-default
2266    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2267    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2268    /// backoff}` sub-block once the Gateway API grows the peer
2269    /// `retry.codes` / `retry.backoff` axes — would have had to be
2270    /// threaded through both open-coded copies in lockstep or the
2271    /// emptiness predicate and the caixa-mesh emit path would silently
2272    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2273    /// (a `:politicas` block whose only axis is a `Some :retries` would
2274    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2275    /// path silently read a drifted other value, or vice versa: an
2276    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2277    /// block while the emptiness predicate still classified the policy
2278    /// as non-empty). Lifting the resolution to a typed method on the
2279    /// substrate primitive means every downstream consumer of the
2280    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2281    /// one typed dispatch — the resolver's accept-set migrates as a
2282    /// unit on any future axis addition.
2283    ///
2284    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2285    /// family (sibling of the peer per-`:politicas`
2286    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2287    /// same "one typed dispatch on the substrate primitive, thin
2288    /// projections at each consumer" discipline extended onto the
2289    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2290    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2291    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2292    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2293    /// fold on). Named `retries()` to match the storage field's name;
2294    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2295    /// §III.2 vocabulary the slot's docstring already carries.
2296    #[must_use]
2297    pub const fn retries(&self) -> Option<u32> {
2298        self.retries
2299    }
2300
2301    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2302    /// enforcement-toggle scalar accessor every consumer of the
2303    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2304    /// — returns the author-declared `:politicas :mtls-required` typed
2305    /// bool verbatim as an `Option<bool>`, copied out of the typed
2306    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2307    /// the accessor returns by value; no borrow of `&self` past the
2308    /// call). `None` when the slot is absent (the "cluster default
2309    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2310    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2311    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2312    /// this predicate too, so an authored-but-unset `:politicas
2313    /// (:mtls-required ())` round-trips to a rendered
2314    /// `CiliumNetworkPolicy` structurally identical to one that omits
2315    /// the slot).
2316    ///
2317    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2318    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2319    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2320    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2321    /// Cilium `authentication.mode` bijection through
2322    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2323    /// handshake enforced), `Some(false) → "disabled"` (handshake
2324    /// skipped — the debug-edge opt-out), `None` → omit the block
2325    /// (cluster default applies). Every downstream consumer that
2326    /// reads the toggle keys off this scalar (the
2327    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2328    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2329    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2330    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2331    /// ingress rule via [`crate::render::single_field_overlay`], the
2332    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2333    /// materialization pass, the future per-`:contratos`-edge mTLS
2334    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2335    ///
2336    /// Prior to this lift the `.mtls_required` field was accessed
2337    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2338    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2339    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2340    /// two open-coded field-accesses that expressed no compile-time
2341    /// link back to the typed slot. A future extension of the
2342    /// `:politicas :mtls-required` axis to a richer author surface —
2343    /// a per-`:contratos`-edge mTLS override the operator pins through
2344    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2345    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2346    /// M4 CR materializer resolves per-CR, a three-valued
2347    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2348    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2349    /// would have had to be threaded through both open-coded copies in
2350    /// lockstep or the emptiness predicate and the caixa-mesh emit
2351    /// path would silently disagree on which toggle a given
2352    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2353    /// axis is a `Some`
2354    /// `:mtls-required` would satisfy `is_empty() == false` while the
2355    /// renderer's overlay-emit path silently read a drifted other
2356    /// value, or vice versa). Lifting the resolution to a typed method
2357    /// on the substrate primitive means every downstream consumer of
2358    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2359    /// for exactly one typed dispatch — the resolver's accept-set
2360    /// migrates as a unit on any future axis addition.
2361    ///
2362    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2363    /// family (peer of the sibling per-`:placement`
2364    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2365    /// same "one typed dispatch on the substrate primitive, thin
2366    /// projections at each consumer" discipline extended onto the
2367    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2368    /// the "optional per-slot Copy-T scalar" projection pattern the
2369    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2370    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2371    /// `mtls_required()` to match the storage field's name; the
2372    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2373    /// §III.2 vocabulary the slot's docstring already carries.
2374    #[must_use]
2375    pub const fn mtls_required(&self) -> Option<bool> {
2376        self.mtls_required
2377    }
2378
2379    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2380    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2381    /// accessor every consumer of the Aplicacao's per-`:politicas`
2382    /// per-`(rate, window)` rate-limit surface keys off — returns the
2383    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2384    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2385    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2386    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2387    /// past the call). `None` when the slot is absent (the "cluster
2388    /// default applies — typically 'no per-Aplicacao rate declaration,
2389    /// gateway-class per-listener default applies'" arm the future
2390    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2391    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2392    /// `rate_limit().is_none()` arm reads this predicate too, so an
2393    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2394    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2395    /// identical to one that omits the slot).
2396    ///
2397    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2398    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2399    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2400    /// (rate lower-bounded by 1 through
2401    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2402    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2403    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2404    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2405    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2406    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2407    /// `:politicas` overlay emits. Every downstream consumer that
2408    /// reads the rate declaration keys off this scalar (the
2409    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2410    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2411    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2412    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2413    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2414    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2415    /// the future per-`:contratos`-edge rate-limit override the
2416    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2417    ///
2418    /// Prior to this lift the `.rate_limit` field was accessed inline
2419    /// at two sites — [`MeshPolicy::is_empty`]'s
2420    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2421    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2422    /// field-accesses that expressed no compile-time link back to the
2423    /// typed slot. A future extension of the `:politicas :rate-limit`
2424    /// axis to a richer author surface — a per-`:contratos`-edge
2425    /// rate-limit override the operator pins through a future
2426    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2427    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2428    /// the M4 CR materializer resolves per-CR, a promotion of the
2429    /// plain `(rate, window)` scalar pair to a richer
2430    /// `{rate, window, burst, key}` sub-block once Envoy's
2431    /// `local_rate_limit` grows the peer `burst_size` /
2432    /// `descriptor_key` axes — would have had to be threaded through
2433    /// both open-coded copies in lockstep or the emptiness predicate
2434    /// and the validate gate would silently disagree on which rate
2435    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2436    /// block whose only axis is a `Some :rate-limit` would satisfy
2437    /// `is_empty() == false` while the validate path silently read a
2438    /// drifted other value, or vice versa: an author's
2439    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2440    /// emptiness predicate still classified the policy as non-empty).
2441    /// Lifting the resolution to a typed method on the substrate
2442    /// primitive means every downstream consumer of the Aplicacao's
2443    /// per-`:politicas` rate-limit surface reaches for exactly one
2444    /// typed dispatch — the resolver's accept-set migrates as a unit
2445    /// on any future axis addition.
2446    ///
2447    /// First `Option<Copy-composite-T>`-return accessor on the M3
2448    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2449    /// scalar-value axis. Peer of the sibling per-`:politicas`
2450    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2451    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2452    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2453    /// "one typed dispatch on the substrate primitive, thin
2454    /// projections at each consumer" discipline extended onto the
2455    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2456    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2457    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2458    /// sub-accessors rather than a top-level accessor because
2459    /// consumers reach for the axes not the aggregate). Named
2460    /// `rate_limit()` to match the storage field's name; the
2461    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2462    /// §III.2 vocabulary the slot's docstring already carries.
2463    #[must_use]
2464    pub const fn rate_limit(&self) -> Option<RateLimit> {
2465        self.rate_limit
2466    }
2467
2468    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2469    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2470    /// declaration scalar accessor every consumer of the Aplicacao's
2471    /// per-`:politicas` breaker declaration keys off — returns the
2472    /// author-declared `:politicas :circuit-breaker` typed
2473    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2474    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2475    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2476    /// by value; no borrow of `&self` past the call). `None` when the
2477    /// slot is absent (the "cluster default applies — typically 'no
2478    /// per-Aplicacao breaker declaration, gateway-class per-listener
2479    /// default applies'" arm the future caixa-mesh
2480    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2481    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2482    /// arm reads this predicate too, so an authored-but-unset
2483    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2484    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2485    /// that omits the slot).
2486    ///
2487    /// The `:politicas :circuit-breaker` slot carries the
2488    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2489    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2490    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2491    /// zero-floor rejected through
2492    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2493    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2494    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2495    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2496    /// canonical-form pinned through
2497    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2498    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2499    /// bijection the future `CiliumClusterwideEnvoyConfig`
2500    /// per-`:politicas` overlay emits. Every downstream consumer that
2501    /// reads the breaker declaration keys off this scalar (the
2502    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2503    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2504    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2505    /// that brackets `cb.max_failures()` against
2506    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2507    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2508    /// [`crate::render::require_positive_canonical_bounded_duration`],
2509    /// the future M4 per-Aplicacao Envoy reconciler materialization
2510    /// pass, the future per-`:contratos`-edge breaker override the
2511    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2512    ///
2513    /// Prior to this lift the `.circuit_breaker` field was accessed
2514    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2515    /// `self.circuit_breaker.is_none()` arm and the
2516    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2517    /// bind — two open-coded field-accesses that expressed no
2518    /// compile-time link back to the typed slot. A future extension of
2519    /// the `:politicas :circuit-breaker` axis to a richer author
2520    /// surface — a per-`:contratos`-edge breaker override the operator
2521    /// pins through a future `:contratos :circuit-breaker` slot the
2522    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2523    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2524    /// a promotion of the plain `(max_failures, window)` scalar pair to
2525    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2526    /// sub-block once Envoy's `outlier_detection` grows the peer
2527    /// ejection-percentage / ejection-time axes — would have had to be
2528    /// threaded through both open-coded copies in lockstep or the
2529    /// emptiness predicate and the validate gate would silently
2530    /// disagree on which breaker declaration a given [`MeshPolicy`]
2531    /// resolves to (a `:politicas` block whose only axis is a
2532    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2533    /// the validate path silently read a drifted other value, or vice
2534    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2535    /// "60s"))` would omit the value-shape gate while the emptiness
2536    /// predicate still classified the policy as non-empty). Lifting
2537    /// the resolution to a typed method on the substrate primitive
2538    /// means every downstream consumer of the Aplicacao's
2539    /// per-`:politicas` breaker surface reaches for exactly one typed
2540    /// dispatch — the resolver's accept-set migrates as a unit on any
2541    /// future axis addition.
2542    ///
2543    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2544    /// mesh-slot family (sibling of the peer per-`:politicas`
2545    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2546    /// on the same composite-Copy shape, and of the sibling per-
2547    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2548    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2549    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2550    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2551    /// same "one typed dispatch on the substrate primitive, thin
2552    /// projections at each consumer" discipline extended onto the last
2553    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2554    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2555    /// match the storage field's name; the accessor's identity maps
2556    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2557    /// docstring already carries. Closes the last unlifted
2558    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2559    /// reader now routes through a typed dispatch on the substrate
2560    /// primitive.
2561    #[must_use]
2562    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2563        self.circuit_breaker
2564    }
2565}
2566
2567#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2568#[serde(rename_all = "camelCase")]
2569pub struct CircuitBreaker {
2570    pub max_failures: u32,
2571    #[serde(with = "supervisor::duration_codec_required")]
2572    pub window: Duration,
2573}
2574
2575impl CircuitBreaker {
2576    /// Substrate-canonical per-`:politicas :circuit-breaker`
2577    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2578    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2579    /// breaker trip-count keys off — returns the author-declared
2580    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2581    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2582    /// so the accessor returns by value; no borrow of `&self` past the
2583    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2584    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2585    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2586    /// present, and its `:max-failures` field carries the trip count as a
2587    /// required-axis scalar).
2588    ///
2589    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2590    /// "consecutive-transient-failure trip threshold" contract
2591    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2592    /// (zero-floor rejected through
2593    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2594    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2595    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2596    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2597    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2598    /// Every downstream consumer that reads the trip threshold keys off
2599    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2600    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2601    /// canonical `require_positive_bounded_u32` helper, the future M4
2602    /// per-Aplicacao Envoy config reconciler materialization pass, the
2603    /// future per-`:contratos`-edge breaker-override overlay the
2604    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2605    ///
2606    /// Prior to this lift the `.max_failures` field was accessed inline
2607    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2608    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2609    /// open-coded field-access that expressed no compile-time link back
2610    /// to the typed sub-struct axis. A future extension of the
2611    /// `:max-failures` axis to a richer author surface — a
2612    /// per-`:contratos`-edge breaker override the operator pins through a
2613    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2614    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2615    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2616    /// plain `u32` trip count to a richer
2617    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2618    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2619    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2620    /// count arms — would have had to be threaded through every open-
2621    /// coded copy in lockstep or the validate gate and the future M4
2622    /// emit path would silently disagree on which trip threshold a given
2623    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2624    /// would satisfy validate while the emit path silently read a drifted
2625    /// other value, or vice versa: a validated typed slot would land at
2626    /// the emit boundary as a no-op breaker whose trip threshold is
2627    /// structurally never reached). Lifting the resolution to a typed
2628    /// method on the substrate primitive means every downstream consumer
2629    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2630    /// trip-threshold surface reaches for exactly one typed dispatch —
2631    /// the resolver's accept-set migrates as a unit on any future axis
2632    /// addition.
2633    ///
2634    /// First sub-struct scalar accessor on the M3 mesh-slot family
2635    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2636    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2637    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2638    /// closes the last unlifted per-`:politicas` scalar-value axis after
2639    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2640    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2641    /// Same "one typed dispatch on the substrate primitive, thin
2642    /// projections at each consumer" discipline the peer
2643    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2644    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2645    /// [`Membro::versao_requirement`] (a40b0e3),
2646    /// [`Entrada::destination`] (6db982c) accessors carry on their
2647    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2648    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2649    /// match the storage field's name; the accessor's identity maps onto
2650    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2651    /// docstring already carries.
2652    #[must_use]
2653    pub const fn max_failures(&self) -> u32 {
2654        self.max_failures
2655    }
2656
2657    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2658    /// Envoy-outlier-detection rolling-observation-interval scalar
2659    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2660    /// breaker rolling-window duration keys off — returns the
2661    /// author-declared `:politicas :circuit-breaker :window` typed
2662    /// `Duration` verbatim, copied out of the typed slot's own
2663    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2664    /// by value; no borrow of `&self` past the call). Non-optional (the
2665    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2666    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2667    /// `CircuitBreaker` past pattern-match is definitionally present,
2668    /// and its `:window` field carries the rolling-observation interval
2669    /// as a required-axis scalar).
2670    ///
2671    /// The `:politicas :circuit-breaker :window` axis carries the
2672    /// "consecutive-transient-failure rolling-observation interval"
2673    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2674    /// `Duration` accept-set (zero-floor rejected through
2675    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2676    /// residue rejected through
2677    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2678    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2679    /// Envoy `outlier_detection.interval` per-cluster
2680    /// ejection-observation-interval scalar (equivalently the future
2681    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2682    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2683    /// consumer that reads the rolling-observation interval keys off
2684    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2685    /// integer-millisecond canonical-form + cap bracket at
2686    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2687    /// [`crate::render::require_positive_canonical_bounded_duration`]
2688    /// helper, the future M4 per-Aplicacao Envoy config reconciler
2689    /// materialization pass, the future per-`:contratos`-edge
2690    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2691    /// acknowledges).
2692    ///
2693    /// Prior to this lift the `.window` field was accessed inline at
2694    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2695    /// `require_positive_canonical_bounded_duration(cb.window, …)`
2696    /// call — one open-coded field-access that expressed no compile-
2697    /// time link back to the typed sub-struct axis. A future extension
2698    /// of the `:window` axis to a richer author surface — a
2699    /// per-`:contratos`-edge window override the operator pins through
2700    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2701    /// #3 roadmap acknowledges, a per-cluster window-default overlay
2702    /// the M4 CR materializer resolves per-CR, a promotion of the plain
2703    /// `Duration` observation interval to a richer
2704    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2705    /// once Envoy's `outlier_detection` block's peer axes come into
2706    /// scope, a per-Envoy-cluster minimum-request-volume gate before
2707    /// the window arms — would have had to be threaded through every
2708    /// open-coded copy in lockstep or the validate gate and the future
2709    /// M4 emit path would silently disagree on which observation
2710    /// interval a given [`CircuitBreaker`] resolves to (an author's
2711    /// `:window "60s"` would satisfy validate while the emit path
2712    /// silently read a drifted other value, or vice versa: a validated
2713    /// typed slot would land at the emit boundary as a breaker whose
2714    /// observation window is structurally so wide that no realistic
2715    /// failure-rate shape can trip it). Lifting the resolution to a
2716    /// typed method on the substrate primitive means every downstream
2717    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2718    /// observation-window surface reaches for exactly one typed
2719    /// dispatch — the resolver's accept-set migrates as a unit on any
2720    /// future axis addition.
2721    ///
2722    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2723    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2724    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2725    /// required-axis, extended onto the per-sub-struct required-`Duration`
2726    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2727    /// axis. Same "one typed dispatch on the substrate primitive, thin
2728    /// projections at each consumer" discipline the peer
2729    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2730    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2731    /// [`Membro::versao_requirement`] (a40b0e3),
2732    /// [`Entrada::destination`] (6db982c) accessors carry on their
2733    /// respective per-mesh-slot-atom scalar-value axes, extended onto
2734    /// the per-sub-struct required-`Duration` axis. Named `window()` to
2735    /// match the storage field's name; the accessor's identity maps onto
2736    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2737    /// docstring already carries.
2738    #[must_use]
2739    pub const fn window(&self) -> Duration {
2740        self.window
2741    }
2742}
2743
2744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2745pub struct RateLimit {
2746    /// Requests per window.
2747    pub rate: u32,
2748    /// Window duration.
2749    pub window: Duration,
2750}
2751
2752impl RateLimit {
2753    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2754    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2755    /// every consumer of the Aplicacao's per-`:contratos`-edge
2756    /// rate-limit-bucket capacity keys off — returns the author-declared
2757    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2758    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2759    /// returns by value; no borrow of `&self` past the call). Non-optional
2760    /// (the surrounding `Option<RateLimit>` is the "slot present?"
2761    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2762    /// `RateLimit` past pattern-match is definitionally present, and its
2763    /// `:rate` field carries the token-bucket capacity as a required-axis
2764    /// scalar).
2765    ///
2766    /// The `:politicas :rate-limit` `:rate` axis carries the
2767    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2768    /// the typed slot's `u32` accept-set (zero-floor rejected through
2769    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2770    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2771    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2772    /// token-bucket-capacity scalar (equivalently the future
2773    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2774    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2775    /// consumer that reads the token-bucket capacity keys off this
2776    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2777    /// cap bracket that gates on the canonical
2778    /// [`crate::render::require_positive_bounded_u32`] helper, the
2779    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2780    /// emits the `<n>/<s|m|h>` author surface, the future M4
2781    /// per-Aplicacao Envoy config reconciler materialization pass, the
2782    /// future per-`:contratos`-edge rate-limit-override overlay the
2783    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2784    ///
2785    /// Prior to this lift the `.rate` field was accessed inline at three
2786    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2787    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2788    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2789    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2790    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2791    /// field-accesses that expressed no compile-time link back to the
2792    /// typed sub-struct axis. A future extension of the `:rate` axis
2793    /// to a richer author surface — a per-`:contratos`-edge rate
2794    /// override the operator pins through a future `:contratos :rate`
2795    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2796    /// per-cluster rate-default overlay the M4 CR materializer resolves
2797    /// per-CR, a promotion of the plain `u32` token capacity to a
2798    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2799    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2800    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2801    /// before the token arms — would have had to be threaded through
2802    /// every open-coded copy in lockstep or the validate gate, the
2803    /// codec's render path, and the future M4 emit path would silently
2804    /// disagree on which token capacity a given [`RateLimit`] resolves
2805    /// to (an author's `:rate-limit "100/s"` would satisfy validate
2806    /// while the render / emit paths silently read a drifted other
2807    /// value, or vice versa: a validated typed slot would land at the
2808    /// emit boundary as a no-op limiter whose token capacity is
2809    /// structurally so high that no realistic per-edge traffic shape
2810    /// can drain it). Lifting the resolution to a typed method on the
2811    /// substrate primitive means every downstream consumer of the
2812    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2813    /// reaches for exactly one typed dispatch — the resolver's
2814    /// accept-set migrates as a unit on any future axis addition.
2815    ///
2816    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2817    /// in shape to the peer per-`CircuitBreaker`
2818    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2819    /// on the peer per-sub-struct required-axis, extended onto the
2820    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2821    /// required-axis scalar" projection pattern the sibling
2822    /// [`RateLimit::window`] future lift folds on. Same "one typed
2823    /// dispatch on the substrate primitive, thin projections at each
2824    /// consumer" discipline the peer [`WitContract::source`] /
2825    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2826    /// (0804823), [`Membro::nome`] (4a32abf),
2827    /// [`Membro::versao_requirement`] (a40b0e3),
2828    /// [`Entrada::destination`] (6db982c),
2829    /// [`CircuitBreaker::max_failures`] (3a74062),
2830    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2831    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2832    /// to match the storage field's name; the accessor's identity maps
2833    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2834    /// docstring already carries.
2835    #[must_use]
2836    pub const fn rate(&self) -> u32 {
2837        self.rate
2838    }
2839
2840    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2841    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2842    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2843    /// rate-limit-bucket refill period keys off — returns the
2844    /// author-declared `:politicas :rate-limit` typed `Duration`
2845    /// verbatim, copied out of the typed slot's own `Duration` storage
2846    /// (`Duration` is `Copy`, so the accessor returns by value; no
2847    /// borrow of `&self` past the call). Non-optional (the surrounding
2848    /// `Option<RateLimit>` is the "slot present?" projection at the
2849    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2850    /// pattern-match is definitionally present, and its `:window`
2851    /// field carries the token-bucket refill period as a required-axis
2852    /// scalar).
2853    ///
2854    /// The `:politicas :rate-limit` `:window` axis carries the
2855    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2856    /// — the typed slot's `Duration` accept-set (constrained to the
2857    /// three canonical windows `{1s, 60s, 3600s}` the
2858    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2859    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2860    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2861    /// per-cluster token-bucket-refill-period scalar (equivalently the
2862    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2863    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2864    /// consumer that reads the token-bucket refill period keys off
2865    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2866    /// canonical-window gate that keys off
2867    /// [`is_canonical_rate_limit_window`], the
2868    /// [`rate_limit_codec::render`] `Duration → unit` projection that
2869    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2870    /// [`rate_limit_window_unit`] and non-canonical fallback via
2871    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2872    /// reconciler materialization pass, the future per-`:contratos`-
2873    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2874    /// roadmap acknowledges).
2875    ///
2876    /// Prior to this lift the `.window` field was accessed inline at
2877    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2878    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2879    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2880    /// error-payload construction on refusal, and the two
2881    /// [`rate_limit_codec::render`] arms
2882    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2883    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2884    /// open-coded field-accesses that expressed no compile-time link
2885    /// back to the typed sub-struct axis. A future extension of the
2886    /// `:window` axis to a richer author surface — a per-`:contratos`-
2887    /// edge window override the operator pins through a future
2888    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2889    /// acknowledges, a per-cluster window-default overlay the M4 CR
2890    /// materializer resolves per-CR, a promotion of the plain
2891    /// `Duration` refill period to a richer
2892    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2893    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2894    /// axis comes into scope, an addition of a `"d"` day suffix once
2895    /// Envoy's `rate_limit_action` grows daily-bucket support — would
2896    /// have had to be threaded through every open-coded copy in
2897    /// lockstep or the validate gate, the codec's render path, and
2898    /// the future M4 emit path would silently disagree on which
2899    /// refill period a given [`RateLimit`] resolves to (an author's
2900    /// `:rate-limit "100/s"` would satisfy validate while the render
2901    /// / emit paths silently read a drifted other value, or vice
2902    /// versa: a validated typed slot would land at the emit boundary
2903    /// as a limiter whose refill period is structurally so long that
2904    /// no realistic per-edge traffic shape stays inside the token
2905    /// budget). Lifting the resolution to a typed method on the
2906    /// substrate primitive means every downstream consumer of the
2907    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2908    /// reaches for exactly one typed dispatch — the resolver's
2909    /// accept-set migrates as a unit on any future axis addition.
2910    ///
2911    /// Second sub-struct scalar accessor on the `RateLimit` axis —
2912    /// sibling in shape to the just-landed [`RateLimit::rate`]
2913    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2914    /// required-axis, extended onto the per-sub-struct
2915    /// required-`Duration` axis; closes the last unlifted
2916    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2917    /// per-sub-struct accessor coverage is now complete across both
2918    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2919    /// the substrate primitive, thin projections at each consumer"
2920    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2921    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2922    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2923    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2924    /// [`Membro::nome`] (4a32abf),
2925    /// [`Membro::versao_requirement`] (a40b0e3),
2926    /// [`Entrada::destination`] (6db982c) accessors carry on their
2927    /// respective per-mesh-slot-atom scalar-value axes. Named
2928    /// `window()` to match the storage field's name; the accessor's
2929    /// identity maps onto the canonical MESH-COMPOSITION §III.2
2930    /// vocabulary the slot's docstring already carries.
2931    #[must_use]
2932    pub const fn window(&self) -> Duration {
2933        self.window
2934    }
2935
2936    /// Recognize this rate-limit's `:window` as a canonical
2937    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2938    /// exactly matches one of the three closed-set arm-Durations
2939    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2940    /// non-canonical magnitude the codec's round-trip would break on
2941    /// (sub-second residue, or a second-magnitude outside the set
2942    /// [`RateLimitUnit::ALL`] enumerates).
2943    ///
2944    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2945    /// returns `Some` here — the validate gate's
2946    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2947    /// rejects every window this accessor returns `None` on. Downstream
2948    /// consumers past validate (the codec's [`rate_limit_codec::render`]
2949    /// path, the future M4 per-Aplicacao Envoy config reconciler's
2950    /// materialization pass, the future per-`:contratos`-edge rate-limit-
2951    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2952    /// acknowledges) that read the typed unit off a validated slot can
2953    /// pattern-match on the returned `Some` without re-checking
2954    /// canonicality at the consumer layer — the typed enum surface is
2955    /// the load-bearing carrier of the canonicality invariant.
2956    ///
2957    /// Preferred over the free [`is_canonical_rate_limit_window`]
2958    /// module-private helper at any call site that has the typed
2959    /// [`RateLimit`] in hand (the codec's `render` arm at
2960    /// [`rate_limit_codec::render`], the validate gate's canonical-form
2961    /// arm in [`AplicacaoSpec::validate_politicas`], any future
2962    /// per-`:contratos` edge-override overlay resolver): those consumers
2963    /// reach for the typed enum without going through the
2964    /// `.window()` scalar-projection layer, and get the enum value
2965    /// directly (which the codec's render arm can then format via
2966    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2967    /// "typed sub-struct scalar accessor, one dispatch on the substrate
2968    /// primitive" discipline the sibling [`RateLimit::rate`] and
2969    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2970    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2971    /// projection axis (the third scalar accessor on the [`RateLimit`]
2972    /// axis, first typed-enum-return projection).
2973    #[must_use]
2974    pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2975        RateLimitUnit::from_window(self.window)
2976    }
2977}
2978
2979/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2980/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2981/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2982///
2983/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2984/// the `:politicas :rate-limit` unit surface reads from
2985/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2986/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2987/// [`is_canonical_rate_limit_window`] predicate the
2988/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2989/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2990/// projection) now lives inside this typed enum's `match self` arms — a
2991/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2992/// `rate_limit_action` grows daily-bucket support) is one new variant
2993/// plus the exhaustiveness arms on the four methods, so every consumer
2994/// picks it up by compile-time construction rather than a runtime
2995/// table-scan miss.
2996///
2997/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2998/// scanned via `find_map` at every projection call — an untyped runtime
2999/// walk that carried no compile-time link between the parse arm's
3000/// accepted suffixes, the render arm's emitted suffixes, and the
3001/// validate gate's accepted windows. A future rate-limit-unit addition
3002/// that landed one row without threading through the other consumers
3003/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3004/// silently split the accepted-set across the three consumers — the
3005/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3006/// for a 24h window that parse can't round-trip, the validate gate
3007/// misses one canonical window. Lifting the pairs onto a typed
3008/// closed-set enum with exhaustive `match` arms makes any such
3009/// half-landed extension a caixa-core build error (the compiler enforces
3010/// arm coverage on every method), not a silent per-consumer drift
3011/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3012/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3013/// [`crate::supervisor::RestartStrategy`],
3014/// [`crate::supervisor::RestartPolicy`],
3015/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3016/// closed-set typed enums carry on their respective closed-set axes —
3017/// extended onto the seventh closed-set typed-enum discriminator axis
3018/// on the caixa typed surface (the `:politicas :rate-limit :window`
3019/// canonical-unit axis).
3020#[derive(
3021    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3022)]
3023pub enum RateLimitUnit {
3024    /// 1-second window — canonical author-surface suffix `"s"`
3025    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3026    /// with a 1s magnitude.
3027    Second,
3028    /// 1-minute window — canonical author-surface suffix `"m"`
3029    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3030    /// with a 60s magnitude.
3031    Minute,
3032    /// 1-hour window — canonical author-surface suffix `"h"`
3033    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3034    /// with a 3600s magnitude.
3035    Hour,
3036}
3037
3038impl RateLimitUnit {
3039    /// Exhaustive iteration surface for every consumer that reads the
3040    /// full canonical-unit set (the byte-parity witness against the
3041    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3042    /// webhook's accepted-suffix listing in its rejection body, any
3043    /// future round-trip fuzz harness). A future variant addition to
3044    /// [`RateLimitUnit`] extends this slice as a single edit and every
3045    /// consumer picks up the new entry by construction — the compiler-
3046    /// checked exhaustiveness on the sibling method `match` arms is the
3047    /// build-time guarantee that no arm forgets to grow.
3048    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3049
3050    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3051    /// string every `<n>/<unit>` rate-limit shape carries after its
3052    /// `/` separator. The single source of truth the codec's parse and
3053    /// render arms both dispatch on: the parse arm matches an incoming
3054    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3055    /// output; the render arm emits the entry's `as_suffix` verbatim
3056    /// after the rate magnitude.
3057    #[must_use]
3058    pub const fn as_suffix(self) -> &'static str {
3059        match self {
3060            Self::Second => "s",
3061            Self::Minute => "m",
3062            Self::Hour => "h",
3063        }
3064    }
3065
3066    /// Canonical `Duration` for this unit — the token-bucket refill
3067    /// period the [`RateLimit::window`] axis carries when the surrounding
3068    /// slot's `:rate-limit` author surface named this unit.
3069    #[must_use]
3070    pub const fn window(self) -> Duration {
3071        Duration::from_secs(match self {
3072            Self::Second => 1,
3073            Self::Minute => 60,
3074            Self::Hour => 3_600,
3075        })
3076    }
3077
3078    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3079    /// `None` when `suffix` is outside the closed-set arm-string set
3080    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3081    /// [`rate_limit_codec::parse`] consumes.
3082    #[must_use]
3083    pub fn from_suffix(suffix: &str) -> Option<Self> {
3084        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3085    }
3086
3087    /// Recognize a canonical rate-limit `Duration` as one of the three
3088    /// arms, or `None` when `window` carries sub-second residue or a
3089    /// second-magnitude outside the closed-set arm-window set
3090    /// [`Self::window`] emits. The single `Duration → Self` projection
3091    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3092    /// both consume.
3093    #[must_use]
3094    pub fn from_window(window: Duration) -> Option<Self> {
3095        if window.subsec_nanos() != 0 {
3096            return None;
3097        }
3098        Self::ALL.iter().copied().find(|u| u.window() == window)
3099    }
3100
3101    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3102    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3103    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3104    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3105    /// consumes.
3106    ///
3107    /// The peer `Duration → &'static str` axis folded onto the substrate
3108    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3109    /// production consumers ([`rate_limit_codec::render`] and
3110    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3111    /// migrated (61421a6): the free helper's `Duration → &str` projection
3112    /// is now the two-step composition
3113    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3114    /// reads through the typed accessor. This lift closes the peer
3115    /// `&str → Duration` axis by folding the vestigial module-private
3116    /// `rate_limit_window_from_unit` delegate onto this associated method
3117    /// — the codec's parse arm and every future wire-side consumer of the
3118    /// `&str → Duration` projection (a future admission-webhook that
3119    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3120    /// before it's promoted to a validated typed slot, a future
3121    /// `feira lint` shape-probe that reads the author-surface bytes
3122    /// verbatim) now reach for exactly one typed dispatch on the
3123    /// substrate primitive.
3124    ///
3125    /// Same "closed-set typed-enum discriminator with canonical
3126    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3127    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3128    /// methods carry — this associated method closes the fifth (and last
3129    /// unlifted) projection axis on the arm-table, so the closed-set enum
3130    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3131    /// consumer of the `:politicas :rate-limit :window` axis reaches
3132    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3133    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3134    /// `"ms"` sub-second window once high-throughput per-edge policies
3135    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3136    /// variant plus one arm per method — the compiler enforces
3137    /// exhaustiveness on every consumer's `match self` arms and picks
3138    /// the new unit up by construction across all five projections.
3139    #[must_use]
3140    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3141        Self::from_suffix(suffix).map(Self::window)
3142    }
3143}
3144
3145/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3146/// every consumer that formats a canonical rate-limit unit as user-
3147/// facing text (future M4 admission-webhook rejection bodies naming
3148/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3149/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3150/// codec's parse arm accepts and the render arm emits. Same
3151/// as_str-through-Display convergence discipline the sibling
3152/// [`PlacementStrategy`], [`crate::CaixaKind`],
3153/// [`crate::supervisor::RestartStrategy`], and
3154/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3155impl std::fmt::Display for RateLimitUnit {
3156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3157        f.write_str(self.as_suffix())
3158    }
3159}
3160
3161/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3162/// validated [`MeshPolicy::timeout`] past
3163/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3164/// (inclusive on both ends, integer-millisecond magnitudes by the
3165/// canonical-form gate immediately preceding).
3166///
3167/// The typed field is `Option<Duration>` (the zero-floor arm
3168/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3169/// `Duration::ZERO`, and the canonical-form arm
3170/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3171/// sub-millisecond residue), so a programmatic struct literal
3172/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3173/// 24h) and the equivalent author-surface form
3174/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3175/// integer-hour magnitude) both round-trip cleanly through serde — a
3176/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3177/// above the documented production-playbook band (Envoy default `15s`,
3178/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3179/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3180/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3181/// at `~3600s`) silently degenerates the mesh-policy contract: the
3182/// per-call deadline is structurally so long that no realistic
3183/// synchronous-`:contratos` traversal can reach it, so the typed slot
3184/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3185/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3186/// blocking" degenerates to a nominal-only contract on the
3187/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3188/// the sibling `:politicas :retries` axis and the
3189/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3190/// `:politicas :circuit-breaker :max-failures` axis — all three close
3191/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3192/// footgun the prior zero-floor-and-canonical-form-only checks left
3193/// open.
3194///
3195/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3196/// shared duration codec emits (`"<n>h"` for any integer-hour
3197/// magnitude) — every value in the canonical authoring form's
3198/// `<integer><unit>` grammar at or below this cap renders to a clean
3199/// canonical string. The cap sits an order of magnitude above every
3200/// documented production-playbook recommendation band (Envoy default
3201/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3202/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3203/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3204/// below the clearly-pathological "effectively no timeout" floor
3205/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3206/// want for a long-running synchronous workflow, but a hard wall above
3207/// which the mesh-level deadline is structurally a non-deadline.
3208/// Lifted as a typed `pub const` so the bound has exactly one source
3209/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3210/// materializer's admission webhook and the caixa-mesh-side
3211/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3212/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3213/// other typed upper bound in this crate carries
3214/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3215/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3216/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3217/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3218pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3219
3220/// Upper-bound ceiling on the `:politicas :retries` axis — every
3221/// validated [`MeshPolicy::retries`] past
3222/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3223///
3224/// The typed slot is `Option<u32>` (`None` = no retries on transient
3225/// failure; `Some(0)` already rejected by the
3226/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3227/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3228/// .. }`) and the equivalent author-surface form
3229/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3230/// serde / the codec — a structurally unbounded `u32` ceiling. The
3231/// runtime substrate that consumes the value (Envoy's
3232/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3233/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3234/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3235/// admission cap is 10) translates a four-billion-retry policy into a
3236/// thundering-herd amplification vector on transient failure — the
3237/// caller's one request fans out to `retries` server-side calls per
3238/// edge per traversal, multiplying load by `(retries+1)^depth` across
3239/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3240/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3241/// invariant on the retry axis; both belong at the typed-slot layer.
3242///
3243/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3244/// upstream mesh-policy schema that documents one) and sits above the
3245/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3246/// every documented production playbook): a value the author can
3247/// plausibly want, but a hard wall above which the policy is
3248/// structurally a footgun. Lifted as a typed `pub const` so the bound
3249/// has exactly one source of truth — a future axis reaching for the
3250/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3251/// materializer's admission webhook, the caixa-mesh-side
3252/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3253/// one place. Same shape every other typed upper bound in this crate
3254/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3255/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3256/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3257/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3258pub const POLICY_RETRIES_MAX: u32 = 10;
3259
3260/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3261/// axis — every validated [`CircuitBreaker::max_failures`] past
3262/// [`AplicacaoSpec::validate_politicas`] lies in
3263/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3264///
3265/// The typed field is `u32` (the zero-floor arm
3266/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3267/// `0` — a breaker that trips on the first call), so a programmatic
3268/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3269/// and the equivalent author-surface form
3270/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3271/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3272/// `max_failures` value far above the documented production-playbook
3273/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3274/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3275/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3276/// typical 5–50) silently disables the breaker's protection role:
3277/// the threshold is structurally so high that no realistic
3278/// failures-per-`:window` traffic shape can reach it, so the breaker
3279/// never trips and the typed slot becomes a no-op carried on every
3280/// emitted Envoy / Cilium L7 overlay. Pairs with the
3281/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3282/// axis — both close the "structurally unbounded `u32` ceiling on a
3283/// typed policy axis" footgun the prior zero-floor-only checks left
3284/// open.
3285///
3286/// The `1000` ceiling sits an order of magnitude above every
3287/// documented upstream production-playbook recommendation band (the
3288/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3289/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3290/// the clearly-pathological "effectively no protection"
3291/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3292/// plausibly want at hyperscale, but a hard wall above which the
3293/// policy is structurally a no-op. Lifted as a typed `pub const` so
3294/// the bound has exactly one source of truth — the future M4
3295/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3296/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3297/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3298/// one place. Same shape every other typed upper bound in this crate
3299/// carries ([`POLICY_RETRIES_MAX`],
3300/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3301/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3302/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3303pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3304
3305/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3306/// every validated [`CircuitBreaker::window`] past
3307/// [`AplicacaoSpec::validate_politicas`] lies in
3308/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3309/// integer-millisecond magnitudes by the canonical-form gate
3310/// immediately preceding).
3311///
3312/// The typed field is `Duration` (the zero-floor arm
3313/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3314/// `Duration::ZERO`, and the canonical-form arm
3315/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3316/// sub-millisecond residue), so a programmatic struct literal
3317/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3318/// and the equivalent author-surface form
3319/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3320/// integer-hour magnitude) both round-trip cleanly through serde — a
3321/// structurally unbounded `Duration` ceiling. A `:window` value far
3322/// above the documented production-playbook band (Hystrix
3323/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3324/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3325/// Istio `outlierDetection.interval` default `10s`, Envoy
3326/// `outlier_detection.interval` default `10s`, AWS App Mesh
3327/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3328/// breaker's role: a rolling-window failure counter whose window is
3329/// hours long is operationally a lifetime counter, the breaker's
3330/// "recent failures" memory is structurally so long that transient
3331/// failures are never forgotten, and the typed slot becomes a no-op
3332/// trigger that trips once and stays tripped for the lifetime of the
3333/// component carried on every emitted Envoy / Cilium L7 overlay.
3334///
3335/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3336/// shared duration codec emits (`"<n>h"` for any integer-hour
3337/// magnitude) — every value in the canonical authoring form's
3338/// `<integer><unit>` grammar at or below this cap renders to a clean
3339/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3340/// cap on the first typed-`Duration` `:politicas` axis: the two
3341/// duration-typed `:politicas` axes now share a single uniform top
3342/// edge so the next typed-slot wiring (the future caixa-mesh
3343/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3344/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3345/// admission webhook) reaches for either field knowing the value is
3346/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3347/// sits two orders of magnitude above every documented upstream
3348/// production-playbook recommendation band (Hystrix / resilience4j /
3349/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3350/// and below the clearly-pathological "rolling window degenerates to
3351/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3352/// author can plausibly want for a very-low-traffic long-tail
3353/// failure-detection window, but a hard wall above which the breaker's
3354/// rolling-window contract is structurally a lifetime-counter contract.
3355/// Lifted as a typed `pub const` so the bound has exactly one source
3356/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3357/// materializer's admission webhook and the caixa-mesh-side
3358/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3359/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3360/// other typed upper bound in this crate carries
3361/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3362/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3363/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3364/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3365/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3366pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3367
3368/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3369/// every validated [`RateLimit::rate`] past
3370/// [`AplicacaoSpec::validate_politicas`] lies in
3371/// `1..=POLICY_RATE_LIMIT_MAX`.
3372///
3373/// The typed field is `u32` (the zero-floor arm
3374/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3375/// zero-rate limit denies every request, the canonical "I forgot
3376/// that 0 means deny-everything" footgun), so a programmatic struct
3377/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3378/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3379/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3380/// round-trip cleanly through serde — a structurally unbounded `u32`
3381/// ceiling. The runtime substrate consuming the value (Envoy's
3382/// `local_rate_limit.token_bucket.max_tokens`, the future
3383/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3384/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3385/// rate-limit into a no-op rate-limiter: the bucket capacity is
3386/// structurally so high no realistic per-edge traffic shape can
3387/// drain it, the limiter never trips, and the typed slot becomes a
3388/// "rate-limit declared, no enforcement" footgun — the canonical
3389/// declared-but-inert shape every other `:politicas` cap arm
3390/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3391/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3392///
3393/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3394/// above every documented upstream production-playbook recommendation
3395/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3396/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3397/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3398/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3399/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3400/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3401/// `u32::MAX`): a value the author can plausibly want at hyperscale
3402/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3403/// /h-window arm), but a hard wall above which the policy is
3404/// structurally a no-op carried verbatim on every emitted Envoy /
3405/// Cilium L7 overlay. The cap brackets all three canonical windows
3406/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3407/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3408/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3409/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3410/// has exactly one source of truth — the future M4
3411/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3412/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3413/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3414/// one place. Same shape every other typed upper bound in this crate
3415/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3416/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3417/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3418/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3419/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3420/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3421pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3422
3423// `:entrada :host` total-length and per-label cap axes route through
3424// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3425// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3426// pair of aplicacao-private aliases the previous `validate_entrada_host`
3427// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3428// = 63`) were structurally the same K8s Gateway API v1 Hostname
3429// admission-schema bounds — the total-length cap on the OpenAPI
3430// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3431// same regex — that the peer axes at the caixa-core::render level pin,
3432// so hoisting both readers onto the shared lifted constants closes the
3433// third-occurrence duplication threshold structurally: the M4
3434// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3435// label validator, the future per-`Certificate` SAN emitter, and every
3436// other per-Gateway-API-Hostname landing site reach the same one place
3437// as the `:entrada :host` gate does — no per-axis alias drift surface
3438// between them, by construction.
3439
3440/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3441/// extractor expression — the upper bound `validate_placement_shard_key`
3442/// enforces on every well-shaped shard-key past validate. The realistic
3443/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3444/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3445/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3446/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3447/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3448/// in `:shard-key`" footgun at validate time rather than at the future
3449/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3450const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3451
3452/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3453/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3454/// that maps the shared parser-shaped reason into the
3455/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3456/// is self-locating (the offending `caixa:` is named verbatim) and
3457/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3458/// fix it in one edit. Same diagnostic shape as
3459/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3460/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3461fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3462    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3463    // re-checking here keeps the predicate usable from any future
3464    // call site (the M4 CR materializer) without an empty-check
3465    // footgun. The shared
3466    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3467    // the empty-first + shape cascade every peer name axis
3468    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3469    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3470    // `:upgrade-from :module`) routes through, so drift between the
3471    // eight axes' accepted DNS-1123-label sets is structurally
3472    // impossible.
3473    crate::render::require_valid_dns_1123_label(
3474        caixa,
3475        || AplicacaoError::MembroCaixaEmpty,
3476        |reason| AplicacaoError::MembroCaixaInvalid {
3477            caixa: caixa.to_string(),
3478            reason,
3479        },
3480    )
3481}
3482
3483/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3484/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3485/// that maps the shared parser-shaped reason into the
3486/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3487///
3488/// Cluster names land in DNS-1123-label territory across every consumer:
3489/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3490/// the `lareira-fleet-programs` aggregator applies to scope programs to
3491/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3492/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3493/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3494/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3495/// side schema enforces the DNS-1123 label rule on admission; a
3496/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3497/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3498/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3499/// only gate and the failure surfaces as a no-match at filter time —
3500/// the workload doesn't land in the named cluster, with no diagnostic
3501/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3502/// build time mirrors the `:membros :caixa` value-shape trajectory
3503/// (3f9d7a0) on the peer name axis.
3504///
3505/// The diagnostic carries the offending `cluster:` verbatim plus a
3506/// parser-shaped `reason:` naming the specific violation, so the
3507/// author can grep their caixa.lisp for `:clusters` and fix it in
3508/// one edit. Same diagnostic shape as
3509/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3510fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3511    // Empty is already gated by `PlacementClusterEmpty` at the call
3512    // site; re-checking here keeps the predicate usable from any
3513    // future call site (the M4 CR materializer's per-cluster validator)
3514    // without an empty-check footgun. Routes through the shared
3515    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3516    // name axes each land on.
3517    crate::render::require_valid_dns_1123_label(
3518        cluster,
3519        || AplicacaoError::PlacementClusterEmpty,
3520        |reason| AplicacaoError::PlacementClusterInvalid {
3521            cluster: cluster.to_string(),
3522            reason,
3523        },
3524    )
3525}
3526
3527/// Reject `:placement :affinity` hints whose shape can never legitimately
3528/// land in any downstream selector or label-keyed routing axis. Thin
3529/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3530/// shared parser-shaped reason into the
3531/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3532/// diagnostic is self-locating (the offending `:affinity` is named
3533/// verbatim) and the author can grep their caixa.lisp for
3534/// `:affinity "<hint>"` and fix it in one edit.
3535///
3536/// The `:affinity` slot carries a placement-engine hint — canonical
3537/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3538/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3539/// compression overlay and the future M4 placement-engine's per-hint
3540/// routing axis. Each downstream consumer (caixa-mesh's
3541/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3542/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3543/// `spec.placement.affinity` admission rule, the future M4 per-hint
3544/// node-affinity / pod-affinity rule generator keying off the same
3545/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3546/// selector) requires the value to be a DNS-1123 label — K8s label
3547/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3548/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3549/// admission rule the apiserver enforces.
3550///
3551/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3552/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3553/// Python-module-name leak), `:affinity "data.locality"` (the
3554/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3555/// `:affinity "data-locality-"` (boundary-hyphen violation),
3556/// `:affinity "data locality"` (paste-from-doc whitespace),
3557/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3558/// 64-byte over-cap slug silently passed the empty-only check and the
3559/// failure surfaced as a no-match at the M3 Adaptive compression
3560/// overlay's filter time (`placement.affinity` carried a malformed
3561/// value, no node matched, the workload landed on the default
3562/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3563/// the empty-:affinity / empty-shard-key / zero-:politicas /
3564/// empty-:contratos-target gates already close on every other
3565/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3566/// gate closes the fifth typed slot on the Aplicacao surface to land
3567/// on the canonical DNS-1123 label floor (after the four Servico-name
3568/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3569/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3570/// b0e8748).
3571///
3572/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3573/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3574/// validated values are guaranteed-accepted by the apiserver without
3575/// re-validation at any downstream renderer or admission layer.
3576fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3577    // Empty is gated separately at the call site for a self-locating
3578    // diagnostic; re-checking here keeps the predicate usable from any
3579    // future call site (the M4 CR materializer's per-affinity
3580    // validator) without an empty-check footgun. Routes through the
3581    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3582    // peer name axes each land on.
3583    crate::render::require_valid_dns_1123_label(
3584        affinity,
3585        || AplicacaoError::PlacementAffinityEmpty,
3586        |reason| AplicacaoError::PlacementAffinityInvalid {
3587            affinity: affinity.to_string(),
3588            reason,
3589        },
3590    )
3591}
3592
3593/// Reject `:placement :shard-key` extractor expressions whose shape can
3594/// never legitimately drive the future M4 Akka-style cluster-sharding
3595/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3596/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3597/// diagnostic is self-locating (the offending `:shard-key` value is
3598/// named verbatim alongside the parser-shaped reason) and the author can
3599/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3600/// edit.
3601///
3602/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3603/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3604/// expression naming the message property to hash on. The realistic
3605/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3606/// property name; `$tenantId` — Akka entity-id placeholder;
3607/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3608/// `${tenant}` — interpolation-style template) all sit in the printable
3609/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3610/// multi-line blob landing in `:shard-key`, an embedded space from a
3611/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3612/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3613/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3614/// check and the failure surfaces at the future M4 reconciler's hash
3615/// pass as a runtime extractor-evaluation error far from the source
3616/// `caixa.lisp`, with no field naming which member's `:shard-key`
3617/// carried the offending value.
3618///
3619/// The contract — the printable ASCII single-token intersection-floor
3620/// every Akka-style entity-id extractor implementation admits:
3621///
3622///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3623///     peer DNS-1123-label-shaped `:placement :affinity` /
3624///     `:placement :clusters` identifier axes; realistic shard-keys sit
3625///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
3626///     blob footguns at validate time;
3627///   - every byte in the printable ASCII range `0x21..=0x7E` —
3628///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3629///     `"$tenantId\n"` from paste-from-aligned-doc /
3630///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3631///     `\x7F` — the canonical "embedded null from a copy-paste-binary
3632///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
3633///     un-Punycode-encoded IDN that round-trips inconsistently across
3634///     NFC/NFD normalization).
3635///
3636/// The accepted set is broader than the DNS-1123 label floor the peer
3637/// `:placement :clusters` / `:placement :affinity` axes use because the
3638/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3639/// landing site; it's an extractor expression the future Akka-style
3640/// reconciler reads as a property reference. The realistic forms
3641/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3642/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3643/// but every Akka-style entity-id extractor parses. The
3644/// printable-ASCII-token floor accepts every shape any such extractor
3645/// would accept while rejecting the cross-implementation footguns
3646/// (whitespace breaks token boundaries; non-ASCII round-trips
3647/// inconsistently across YAML emitters and NFC/NFD normalization;
3648/// control characters silently corrupt the next read).
3649///
3650/// Until this gate landed `validate_placement` only refused the
3651/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3652/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3653/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3654/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3655/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3656/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3657/// control character from paste-from-binary, the 64-byte over-cap
3658/// paste-from-doc multi-line slug) silently passed validate. The future
3659/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3660/// would then surface the malformed value either as a runtime
3661/// extractor-evaluation error (whitespace breaks the extractor's token
3662/// boundary, no match) or as a silently-different shard assignment
3663/// across YAML emitters (non-ASCII normalizes differently between the
3664/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3665/// parser, the same entity ID maps to two distinct shards on a
3666/// re-render). Lifting the shape gate to caixa-build time makes the
3667/// extractor-floor invariant a structural property of every validated
3668/// `Placement`: every `Sharded` placement past `validate_placement` has
3669/// a `:shard-key` the future M4 reconciler can hash without
3670/// re-validating at the runtime layer.
3671///
3672/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3673/// [`AplicacaoError::ContratoSubjectInvalid`] /
3674/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3675/// on the peer `:contratos` payload axes — each lifts the
3676/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3677/// closing the canonical "this passed validate but the runtime parser
3678/// rejected it" surprise.
3679fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3680    // Empty is gated separately at the call site via the more
3681    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3682    // re-checking here keeps the predicate usable from any future call
3683    // site (the M4 CR materializer's per-shard-key validator) without
3684    // an empty-check footgun.
3685    if key.is_empty() {
3686        return Err(AplicacaoError::ShardedKeyEmpty);
3687    }
3688    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3689        return Err(AplicacaoError::ShardKeyInvalid {
3690            shard_key: key.to_string(),
3691            reason: format!(
3692                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3693                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3694                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3695                 well under 32 bytes, this length suggests a paste-from-doc \
3696                 multi-line blob landed in `:shard-key` instead of a single-token \
3697                 extractor expression)",
3698                key.len()
3699            ),
3700        });
3701    }
3702    for &b in key.as_bytes() {
3703        if (0x21..=0x7E).contains(&b) {
3704            continue;
3705        }
3706        let reason = if b == b' ' {
3707            "contains a space (Akka-style entity-id extractor expressions are \
3708             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3709             whitespace breaks the extractor's token boundary at the runtime layer, \
3710             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3711             a multi-token blob in one `:shard-key` slot)"
3712                .to_string()
3713        } else if b == b'\t' {
3714            "contains a tab character (paste-from-aligned-doc footgun; the \
3715             Akka-style entity-id extractor reads `:shard-key` as a single-token \
3716             reference, embedded whitespace breaks the token boundary at the \
3717             runtime hash-extractor pass)"
3718                .to_string()
3719        } else if b == b'\n' || b == b'\r' {
3720            format!(
3721                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3722                 paste-from-multiline-doc footgun; the Akka-style entity-id \
3723                 extractor reads `:shard-key` as a single-token reference, embedded \
3724                 newlines either truncate the value at the YAML emitter layer or \
3725                 break the token boundary at the runtime hash-extractor pass)"
3726            )
3727        } else if b < 0x20 || b == 0x7F {
3728            format!(
3729                "contains control character 0x{b:02x} (the canonical \
3730                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3731                 control characters silently corrupt round-trip serialization \
3732                 across YAML emitters and break the runtime hash-extractor's \
3733                 single-token parser)"
3734            )
3735        } else {
3736            format!(
3737                "contains non-ASCII byte 0x{b:02x} (the canonical \
3738                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3739                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3740                 across YAML emitter implementations — the same entity ID can \
3741                 silently map to two distinct shards on a re-render. Use a \
3742                 printable-ASCII extractor expression like `tenantId`, \
3743                 `$tenantId`, or `metadata.tenantId`)"
3744            )
3745        };
3746        return Err(AplicacaoError::ShardKeyInvalid {
3747            shard_key: key.to_string(),
3748            reason,
3749        });
3750    }
3751    Ok(())
3752}
3753
3754/// Reject `:contratos :de` / `:contratos :para` values whose shape
3755/// can never legitimately match a validated `:membros :caixa`. Thin
3756/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3757/// shared parser-shaped reason into the
3758/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3759/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3760/// the offending value verbatim) and the author can grep their
3761/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3762/// one edit.
3763///
3764/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3765/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3766/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3767/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3768/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3769/// un-Punycode-encoded IDN) silently passed the per-axis check and
3770/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3771/// membership lookup — diagnostic-framed as "this caixa is not in
3772/// `:membros`" when the root cause is "this `:de` value is not a
3773/// well-shaped Servico-name identifier and could never legitimately
3774/// match any validated member". Because every `:membros :caixa` is
3775/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3776/// `names` HashSet structurally never contains an empty / malformed
3777/// string, so the membership lookup arm misframes every empty /
3778/// malformed input. Lifting the shape arm ahead of the lookup
3779/// preserves the legitimate `ContratoMemberMissing` arm (a
3780/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3781/// reference) while routing every structurally-impossible-to-match
3782/// input through the narrower self-locating shape diagnostic.
3783///
3784/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3785/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3786/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3787/// to land on the canonical [`crate::render::is_dns_1123_label`]
3788/// floor. The `slot: &'static str` field carries the kebab-case
3789/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3790/// per-callback-slot diagnostic shape and the
3791/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3792/// (85f102c) cross-list-tag pattern.
3793fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3794    // Routes through the shared
3795    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3796    // name axes each land on. The `slot: &'static str` field flows
3797    // through both error variants so the diagnostic names which
3798    // per-edge axis (`:de` vs `:para`) the offending value came from.
3799    crate::render::require_valid_dns_1123_label(
3800        caixa,
3801        || AplicacaoError::ContratoCaixaEmpty { slot },
3802        |reason| AplicacaoError::ContratoCaixaInvalid {
3803            slot,
3804            caixa: caixa.to_string(),
3805            reason,
3806        },
3807    )
3808}
3809
3810/// Reject `:entrada :para` values whose shape can never legitimately
3811/// match a validated `:membros :caixa`. Thin wrapper around
3812/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3813/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3814/// variant, so the diagnostic is self-locating (the offending
3815/// `:entrada :para` value is named verbatim) and the author can grep
3816/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3817///
3818/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3819/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3820/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3821/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3822/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3823/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3824/// silently passed the per-axis check and surfaced as
3825/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3826/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3827/// root cause is "this `:entrada :para` value is not a well-shaped
3828/// Servico-name identifier and could never legitimately match any
3829/// validated member". Because every `:membros :caixa` is shape-
3830/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3831/// `HashSet` structurally never contains an empty / malformed string,
3832/// so the membership lookup arm misframes every empty / malformed
3833/// input. Lifting the shape arm ahead of the lookup preserves the
3834/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3835/// simply isn't in `:membros` — a phantom reference) while routing
3836/// every structurally-impossible-to-match input through the narrower
3837/// self-locating shape diagnostic.
3838///
3839/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3840/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3841/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3842/// fourth and last Aplicacao-level Servico-name reference axis to
3843/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3844/// No `slot: &'static str` field because there is only one axis
3845/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3846/// the simpler shape mirrors [`validate_membro_caixa`] and
3847/// [`validate_placement_cluster`].
3848fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3849    // Empty is gated separately at the call site for a self-locating
3850    // diagnostic; re-checking here keeps the predicate usable from any
3851    // future call site (the M4 CR materializer's per-`:entrada`
3852    // validator) without an empty-check footgun. Routes through the
3853    // shared [`crate::render::require_valid_dns_1123_label`] gate the
3854    // peer name axes each land on.
3855    crate::render::require_valid_dns_1123_label(
3856        para,
3857        || AplicacaoError::EntradaParaEmpty,
3858        |reason| AplicacaoError::EntradaParaInvalid {
3859            para: para.to_string(),
3860            reason,
3861        },
3862    )
3863}
3864
3865/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3866/// would refuse at admission time. The contract — exactly the regex
3867/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3868/// and `HTTPRoute.spec.hostnames[]`,
3869/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3870/// (max length 253; per-label max length 63):
3871///
3872///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3873///     uppercase, no underscore, no Unicode/IDN — IDN must be
3874///     pre-encoded as Punycode `xn--…` by the author);
3875///   - exactly one optional leading wildcard label (`*.`); a wildcard
3876///     in any non-leading label position is rejected;
3877///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
3878///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
3879///   - total length 1..=253 bytes;
3880///   - no IPv4 literal (Gateway API forbids IP literals);
3881///   - no scheme (`https://`, `http://`), no port (`:8080`), no
3882///     whitespace, no path (`/`).
3883///
3884/// Lifted as a typed gate (rather than an inline cascade in
3885/// `validate()`) so the contract lives in one place — every future
3886/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3887/// materializer's host validator, the future per-`:entrada` SAN
3888/// emission for cert-manager Certificates, the multi-`:entrada`
3889/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3890/// for the same predicate, not its own. Same compounding shape as
3891/// `is_canonical_rate_limit_window` (808017c) and
3892/// [`WitTarget::label`] (previously the free `contrato_target_label`
3893/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3894/// per-variant label match is compiler-checked-exhaustive).
3895///
3896/// The diagnostic carries the offending `host:` verbatim plus a
3897/// parser-shaped `reason:` naming the specific violation, so the
3898/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3899/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3900/// (9888b13).
3901fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3902    // Empty is already gated by `EmptyEntradaHost` at the call site;
3903    // re-checking here keeps the predicate usable from any future
3904    // call site (M4 CR materializer) without an empty-check footgun.
3905    if host.is_empty() {
3906        return Err(AplicacaoError::EmptyEntradaHost);
3907    }
3908    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3909        return Err(AplicacaoError::EntradaHostInvalid {
3910            host: host.to_string(),
3911            reason: format!(
3912                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3913                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3914                host.len(),
3915                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3916            ),
3917        });
3918    }
3919    if host.contains("://") {
3920        return Err(AplicacaoError::EntradaHostInvalid {
3921            host: host.to_string(),
3922            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3923                     Gateway API takes the bare hostname)"
3924                .to_string(),
3925        });
3926    }
3927    if host.contains('/') {
3928        return Err(AplicacaoError::EntradaHostInvalid {
3929            host: host.to_string(),
3930            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3931                     matching is in `:entrada :paths`)"
3932                .to_string(),
3933        });
3934    }
3935    // After the `://` scheme-prefix and `/` path arms have ruled out the
3936    // two `:`-bearing shapes the Gateway API actively rejects with
3937    // location-shaped diagnostics, any remaining `:` in the host body is
3938    // either the canonical "I put the port in the `:host` slot"
3939    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3940    // slot lives one axis away on the same `:entrada` block) or an
3941    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3942    // Hostname forbids identically to the IPv4-literal arm below. Both
3943    // shapes silently fell through the `://` and `/` arms before this
3944    // lift and surfaced as a deep `label "<rest>:<port>" contains
3945    // invalid character ':'` diagnostic from the per-byte loop near the
3946    // bottom of this predicate, which named the offending byte but not
3947    // the canonical authoring fix — for the port case the author has to
3948    // know the `:entrada` block carries a separate `:port u16` slot
3949    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3950    // move the value over; for the IPv6 case the author has to know
3951    // Gateway API v1 forbids IP literals across the board. The contract
3952    // doc-comment above already promises "no port (`:8080`)" verbatim
3953    // in the rejected-shape enumeration but the predicate's
3954    // implementation refused the `:` only as a side-effect of the
3955    // per-label `[a-z0-9-]` character-class loop; this arm brings the
3956    // implementation in line with the documented contract by surfacing
3957    // the canonical fix at the top-level shape gate, peer with how the
3958    // `://` arm names the scheme prefix and the `/` arm names the
3959    // `:entrada :paths` axis. Same compounding trajectory the recent
3960    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3961    // — the typed slot's rejected set matches the apiserver's rejected
3962    // set, structurally, with a self-locating diagnostic at the
3963    // offending axis instead of a deep parser-shape leak.
3964    if host.contains(':') {
3965        return Err(AplicacaoError::EntradaHostInvalid {
3966            host: host.to_string(),
3967            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3968                     slot — a separate `u16` axis on the same `:entrada` block, \
3969                     defaulting to 8080 — not in the host body; drop the `:<port>` \
3970                     suffix and author the bare hostname. If you intended an IPv6 \
3971                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3972                     Hostname forbids IP literals identically to the IPv4-literal \
3973                     arm — use a DNS name)"
3974                .to_string(),
3975        });
3976    }
3977    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3978    // predicate — the same single source of truth every peer
3979    // ASCII-whitespace scan in caixa-core flows through: the four
3980    // typed-magnitude codec sites (`limits::parse_byte_size` backing
3981    // `:limits :memory`, `limits::parse_duration` backing `:limits
3982    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3983    // `aplicacao::rate_limit_codec::parse` backing `:politicas
3984    // :rate-limit`) and the shared duration codec
3985    // (`supervisor::duration_codec::parse`) backing `:supervisor
3986    // :restart-window` / `:politicas :timeout` / `:politicas
3987    // :circuit-breaker :window`. This landing closes the last string-typed
3988    // slot in caixa-core still calling `.bytes().any(|b|
3989    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3990    // across every typed slot now shares one predicate, so a future
3991    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3992    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3993    // deliberately excluded from the peer non-ASCII predicate) can
3994    // extend at this shared site in one edit rather than seven
3995    // independent scans diverging over time. Naming the offending byte
3996    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3997    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3998    // the offending byte verbatim" discipline every peer codec site
3999    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4000    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4001    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4002        return Err(AplicacaoError::EntradaHostInvalid {
4003            host: host.to_string(),
4004            reason: format!(
4005                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4006                 Hostname is a single-token DNS name — leading, trailing, \
4007                 or embedded whitespace breaks the K8s apiserver's Hostname \
4008                 regex at admission time; the paste-from-aligned-doc / \
4009                 paste-from-shell-history / paste-from-CSV footgun silently \
4010                 lands a multi-token blob in `:entrada :host`. Strip every \
4011                 whitespace byte and author the bare hostname — space \
4012                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4013                 refuse identically)"
4014            ),
4015        });
4016    }
4017    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4018    // subset of Unicode `White_Space` through the shared
4019    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4020    // single source of truth every peer non-ASCII-whitespace scan in
4021    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4022    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4023    // `limits::parse_millicores` (`:limits :cpu`),
4024    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4025    // and `supervisor::duration_codec::parse` (`:supervisor
4026    // :restart-window` / `:politicas :timeout` / `:politicas
4027    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4028    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4029    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4030    // paste-from-web-doc), or an EM-SPACE-split host
4031    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4032    // survived this predicate's ASCII byte-scan (none of the UTF-8
4033    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4034    // `u8::is_ascii_whitespace`), then landed on the per-label
4035    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4036    // predicate with the generic `label "…" must start and end with an
4037    // alphanumeric` diagnostic — a "far from source at build-time"
4038    // leak that names the label-shape violation but not the
4039    // paste-from-typography origin the author actually needs to fix.
4040    // Peer with the four codec sites the 1b75b38 landing pinned: the
4041    // typed slot's diagnostic axis names the offending codepoint
4042    // (`U+XXXX`) verbatim rather than laundering the value through a
4043    // downstream label-shape arm, so the author can grep their
4044    // caixa.lisp for the invisible codepoint at the surfaced position
4045    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4046    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4047    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4048    // drift between any two typed-slot sites' non-ASCII-whitespace
4049    // rejection set becomes a single-edit fix at the shared predicate
4050    // rather than N independent inline scans diverging over time, and
4051    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4052    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4053    // `char::is_whitespace`" class the peer non-ASCII predicate's
4054    // doc-comment names as the follow-up trajectory) extends at the
4055    // shared predicate in one edit rather than seven.
4056    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4057        return Err(AplicacaoError::EntradaHostInvalid {
4058            host: host.to_string(),
4059            reason: format!(
4060                "contains non-ASCII Unicode whitespace character {ch:?} \
4061                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4062                 single-token DNS name limited to `[a-z0-9-]` labels; \
4063                 the paste-from-typography footgun silently lands an \
4064                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4065                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4066                 `U+3000`, and every other member of the Unicode \
4067                 `White_Space` property outside the ASCII byte range) \
4068                 in `:entrada :host`, which the K8s apiserver's \
4069                 Hostname regex refuses at admission time far from the \
4070                 caixa.lisp source line. Strip every non-ASCII \
4071                 whitespace character and author the bare hostname \
4072                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4073                 verbatim)",
4074                codepoint = ch as u32,
4075            ),
4076        });
4077    }
4078
4079    // Strip the optional single leading wildcard label *before* the
4080    // trailing-dot check so the bare `"*."` form surfaces the more
4081    // self-locating "wildcard without domain" diagnostic instead of
4082    // the generic "trailing dot" one.
4083    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4084        Some(r) => (true, r),
4085        None => (false, host),
4086    };
4087    if had_wildcard && rest.is_empty() {
4088        return Err(AplicacaoError::EntradaHostInvalid {
4089            host: host.to_string(),
4090            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4091        });
4092    }
4093    if rest.contains('*') {
4094        return Err(AplicacaoError::EntradaHostInvalid {
4095            host: host.to_string(),
4096            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4097                     no inner or trailing `*` labels"
4098                .to_string(),
4099        });
4100    }
4101    if rest.ends_with('.') {
4102        return Err(AplicacaoError::EntradaHostInvalid {
4103            host: host.to_string(),
4104            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4105                     fully-qualified with a root dot; the apiserver regex rejects \
4106                     trailing dots)"
4107                .to_string(),
4108        });
4109    }
4110
4111    // Reject pure IPv4 literals: four dot-separated labels, every
4112    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4113    // literals as Hostnames.
4114    let labels: Vec<&str> = rest.split('.').collect();
4115    if labels.len() == 4
4116        && labels
4117            .iter()
4118            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4119    {
4120        return Err(AplicacaoError::EntradaHostInvalid {
4121            host: host.to_string(),
4122            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4123                     literals; use a DNS name)"
4124                .to_string(),
4125        });
4126    }
4127
4128    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4129    // hyphen, with non-hyphen at both boundaries.
4130    for label in &labels {
4131        if label.is_empty() {
4132            return Err(AplicacaoError::EntradaHostInvalid {
4133                host: host.to_string(),
4134                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4135            });
4136        }
4137        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4138            return Err(AplicacaoError::EntradaHostInvalid {
4139                host: host.to_string(),
4140                reason: format!(
4141                    "label {label:?} exceeds DNS-1123 label max length of \
4142                     {cap} bytes (got {} bytes)",
4143                    label.len(),
4144                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4145                ),
4146            });
4147        }
4148        let bytes = label.as_bytes();
4149        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4150            return Err(AplicacaoError::EntradaHostInvalid {
4151                host: host.to_string(),
4152                reason: format!(
4153                    "label {label:?} must start and end with an alphanumeric \
4154                     (no leading or trailing `-`)"
4155                ),
4156            });
4157        }
4158        for &b in bytes {
4159            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4160            if !valid {
4161                let msg = if b.is_ascii_uppercase() {
4162                    format!(
4163                        "label {label:?} contains uppercase character {ch:?} \
4164                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4165                        ch = b as char,
4166                        lower = label.to_ascii_lowercase()
4167                    )
4168                } else if b == b'_' {
4169                    format!(
4170                        "label {label:?} contains `_` (Gateway API hostnames \
4171                         allow only `[a-z0-9-]`; use `-` instead)"
4172                    )
4173                } else {
4174                    format!(
4175                        "label {label:?} contains invalid character {ch:?} \
4176                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4177                        ch = b as char
4178                    )
4179                };
4180                return Err(AplicacaoError::EntradaHostInvalid {
4181                    host: host.to_string(),
4182                    reason: msg,
4183                });
4184            }
4185        }
4186    }
4187    Ok(())
4188}
4189
4190/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4191/// would refuse at admission time. Thin wrapper around
4192/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4193/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4194/// variant, preserving the more self-locating
4195/// [`AplicacaoError::EntradaPathEmpty`] /
4196/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4197/// path fails those narrower invariants first.
4198///
4199/// The contract is the canonical HTTP-path grammar — `1..=
4200/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4201/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4202/// whitespace/control/non-ASCII bytes — shared with the
4203/// `:contratos :endpoint` axis through the lifted predicate so drift
4204/// between either landing site and the K8s apiserver-side
4205/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4206/// the predicate, not a per-renderer "this passed validate but failed
4207/// admission" surprise. The diagnostic carries the offending `path:`
4208/// verbatim plus a parser-shaped `reason:` naming the specific
4209/// violation, so the author can grep their caixa.lisp for `:paths`
4210/// and fix it in one edit. Same diagnostic shape as
4211/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4212/// axis.
4213fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4214    // Empty and missing-leading-`/` are already gated at the call
4215    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4216    // checking here keeps the per-axis narrower diagnostics in force
4217    // when the predicate is reached directly (and `is_gateway_api_http_path`
4218    // itself defends against `bytes[0]`-style indexing on empty
4219    // input).
4220    if path.is_empty() {
4221        return Err(AplicacaoError::EntradaPathEmpty);
4222    }
4223    if !path.starts_with('/') {
4224        return Err(AplicacaoError::EntradaPathNotAbsolute {
4225            path: path.to_string(),
4226        });
4227    }
4228    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4229        AplicacaoError::EntradaPathInvalid {
4230            path: path.to_string(),
4231            reason,
4232        }
4233    })
4234}
4235
4236mod rate_limit_codec {
4237    // `Duration` is no longer named here — the codec routes through
4238    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4239    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4240    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4241    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4242    // closed-set enum's arm-table rather than through vestigial free-helper
4243    // delegates.
4244    use super::{RateLimit, RateLimitUnit};
4245    use serde::{Deserialize, Deserializer, Serializer};
4246
4247    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4248        match v {
4249            Some(rl) => s.serialize_str(&render(*rl)),
4250            None => s.serialize_none(),
4251        }
4252    }
4253
4254    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4255        let opt: Option<String> = Option::deserialize(d)?;
4256        match opt {
4257            None => Ok(None),
4258            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4259        }
4260    }
4261
4262    fn parse(s: &str) -> Result<RateLimit, String> {
4263        // Whitespace-rejection arm — peer with the leading-`+`
4264        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4265        // same canonical-form render-determinism axis. Until this gate
4266        // landed the parser silently tolerated leading / trailing /
4267        // internal whitespace via the top-level `s.trim()` and the
4268        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4269        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4270        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4271        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4272        // serde silently round-tripped to `"100/s"` on the next emit
4273        // (a *different* canonical string) — breaking the THEORY.md
4274        // Part V render-determinism contract on the same
4275        // canonical-form-drift axis the leading-`+` arm below (the
4276        // 4eeae98 predecessor) and the leading-zero arm below (the
4277        // 4f46830 predecessor) already close.
4278        //
4279        // The canonical author shape is `<integer>/<s|m|h>` with no
4280        // whitespace bytes anywhere — every string [`render`] emits
4281        // carries none, so the parser's accepted set must match for
4282        // serialize / deserialize to round-trip losslessly. This gate
4283        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4284        // `unit.trim()` calls below strict no-ops on the accepted set
4285        // (every byte-position match they would perform is now already
4286        // trimmed away by the accepted set itself), while the arm
4287        // surfaces every rejected whitespace-carrying shape with a
4288        // self-locating diagnostic naming the offending byte and the
4289        // canonical form the author intended, peer with every prior
4290        // canonical-form-drift arm on this codec.
4291        //
4292        // Routed through the lifted
4293        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4294        // same source of truth the four peer typed-magnitude codec
4295        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4296        // `limits::parse_millicores`, `supervisor::duration_codec`)
4297        // share. `u8::is_ascii_whitespace()` at the predicate covers
4298        // the five WhatWG-conformant ASCII whitespace bytes (space,
4299        // tab, LF, FF, CR); the "single lifted predicate" discipline
4300        // the peer non-ASCII arm below carries on the strictly-
4301        // complementary Unicode `White_Space` class extends here to
4302        // the ASCII byte set as well.
4303        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4304            return Err(format!(
4305                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4306                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4307                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4308                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4309                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4310                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4311                 on first serialize — breaking the THEORY.md Part V render-determinism \
4312                 contract every typed slot carries. Strip every whitespace byte (write \
4313                 `\"100/s\"` verbatim)"
4314            ));
4315        }
4316        // Non-ASCII Unicode `White_Space` arm — the strictly-
4317        // complementary class the ASCII arm above cannot see.
4318        // `str::trim` at the top of every peer codec uses
4319        // `char::is_whitespace` (Unicode `White_Space`, strictly
4320        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4321        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4322        // survives the byte-scan (its UTF-8 bytes are not in
4323        // `is_ascii_whitespace`), gets silently stripped by the
4324        // top-level `s.trim()` below, and the value round-trips
4325        // through `render` to a *different* canonical form
4326        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4327        // render-determinism contract every typed slot carries.
4328        // Closed here (`:politicas :rate-limit`) and at the three
4329        // peer codec sites (`limits::parse_byte_size`,
4330        // `limits::parse_duration`, `supervisor::duration_codec`)
4331        // through the shared
4332        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4333        // — the "single lifted predicate across all four codec sites
4334        // in one follow-up run" the 24a8ad4 commit body's `Forward
4335        // compounding` bullet named as the next compounding step.
4336        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4337            return Err(format!(
4338                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4339                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4340                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4341                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4342                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4343                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4344                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4345                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4346                 silently strips it at parse entry, and the value round-trips through \
4347                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4348                 serialize — breaking the THEORY.md Part V render-determinism contract \
4349                 every typed slot carries. Strip every non-ASCII whitespace character \
4350                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4351                cp = ch as u32
4352            ));
4353        }
4354        let s = s.trim();
4355        let (rate_str, unit) = s
4356            .split_once('/')
4357            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4358        let rate_trim = rate_str.trim();
4359        // The canonical authoring form for `:politicas :rate-limit` is
4360        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4361        // non-negative integer with no decimal point and no leading
4362        // sign, so the parser's accepted set must match for
4363        // serialize/deserialize to round-trip without canonical-form
4364        // drift. Until this gate landed the parser accepted any
4365        // `u32::from_str`-shaped magnitude — and current Rust
4366        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4367        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4368        // serde silently round-tripped to `"100/s"` on the next emit
4369        // (a *different* canonical string) — breaking the THEORY.md
4370        // Part V render-determinism contract on the fifth typed-codec
4371        // surface in caixa-core (peer with the four duration codecs the
4372        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4373        // already covered: `supervisor::duration_codec` backing three
4374        // typed-duration slots, `limits::parse_duration` backing
4375        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4376        // `:limits :memory`). The fractional / decimal-shaped sibling
4377        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4378        // existing rejection arm, but the diagnostic is value-laundered
4379        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4380        // doesn't name the canonical-form remediation or the round-trip
4381        // drift the next emit would produce); this gate lifts the
4382        // fractional arm onto the same canonical-form diagnostic the
4383        // peer codecs carry.
4384        //
4385        // Strict canonical form: every byte of the magnitude is an
4386        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4387        // inputs the gate distinguishes "non-canonical-but-numeric"
4388        // (parses as f64 or i64 — surfaced with a self-locating
4389        // diagnostic naming the canonical authoring form and the
4390        // round-trip drift the rejected shape would produce on first
4391        // serialize) from "garbage" (parses as neither — surfaced with
4392        // the existing narrower `"not a u32"` wording so its
4393        // diagnostic shape remains stable for the parser-shape footgun
4394        // case).
4395        //
4396        // Routed through the lifted
4397        // [`crate::render::is_digit_only_magnitude`] predicate — the
4398        // same source of truth the four peer typed-magnitude codec
4399        // sites share.
4400        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4401        if !digit_only {
4402            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4403            if numeric {
4404                return Err(format!(
4405                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4406                     canonical authoring form for `:politicas :rate-limit` is \
4407                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4408                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4409                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4410                     through `render` to a *different* canonical form (`\"1/s\"`, \
4411                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4412                     THEORY.md Part V render-determinism contract every typed slot \
4413                     carries. Pick an integer rate that fits the desired window \
4414                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4415                ));
4416            }
4417            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4418        }
4419        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4420        // (4eeae98's predecessor) on the same canonical-form
4421        // render-determinism axis. The digit-only gate accepts
4422        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4423        // them losslessly (= 100, 0, 7), but `render` emits the
4424        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4425        // a *different* canonical string on the next emit, breaking
4426        // the THEORY.md Part V render-determinism contract the same
4427        // way `"+100/s"` did before the leading-`+` arm landed. The
4428        // single-byte magnitude `"0"` itself round-trips losslessly
4429        // through `render` (`render(0)` emits `"0/s"`) — the
4430        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4431        // what refuses rate-zero authoring, so `"0/s"` stays in the
4432        // accepted set at this codec layer and the diagnostic
4433        // partitioning between canonical-form drift (this arm) and
4434        // semantic-zero (the downstream gate) remains stable.
4435        // Peer with the future leading-zero arms on the three peer
4436        // typed-magnitude codecs the trajectory acknowledges:
4437        // `supervisor::duration_codec`, `limits::parse_duration`,
4438        // `limits::parse_byte_size` — each carries the same
4439        // canonical-form-drift class today; this gate lands the
4440        // discipline on the fourth typed-magnitude codec in
4441        // caixa-core first because the peer `"+100/s"` arm above is
4442        // the closest predecessor on the trajectory.
4443        //
4444        // Routed through the lifted
4445        // [`crate::render::is_leading_zero_padded_magnitude`]
4446        // predicate — the same source of truth the four peer
4447        // typed-magnitude codec sites share.
4448        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4449            return Err(format!(
4450                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4451                 canonical authoring form for `:politicas :rate-limit` is \
4452                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4453                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4454                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4455                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4456                 first serialize — breaking the THEORY.md Part V render-determinism \
4457                 contract every typed slot carries. Strip the leading zeros (write \
4458                 `\"100/s\"` instead of `\"0100/s\"`)"
4459            ));
4460        }
4461        // The digit-only gate guarantees every byte is `[0-9]`, and
4462        // the leading-zero arm above guarantees the magnitude is
4463        // either the single byte `"0"` or starts with `[1-9]`, so
4464        // the only way `u32::from_str` can fail here is overflow
4465        // (the magnitude exceeds `u32::MAX`). Surface that with an
4466        // overflow-shaped wording so the diagnostic names the
4467        // offending magnitude verbatim rather than collapsing onto
4468        // the non-canonical arm. Same shape
4469        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4470        // duration-codec axis.
4471        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4472            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4473        })?;
4474        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4475        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4476        // arm reads the `&str → Duration` projection through the
4477        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4478        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4479        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4480        // module-private `rate_limit_window_from_unit` free helper the
4481        // predecessor 61421a6 left as the last unlifted delegate on this
4482        // axis. One typed dispatch on the substrate primitive instead of
4483        // one runtime call through the free-helper delegate; the sole
4484        // production consumer of the `&str → Duration` axis (this parse
4485        // arm) now reaches for exactly one typed method on the closed-set
4486        // enum, sibling to the codec's render arm's
4487        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4488        // `Duration → RateLimitUnit` axis and to the validate gate's
4489        // [`super::RateLimit::canonical_unit`] shape-probe on the
4490        // canonical-window axis. A future rate-limit-unit addition (a
4491        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4492        // daily-bucket support, a `"ms"` sub-second window once
4493        // high-throughput per-edge policies come into scope per
4494        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4495        // on the closed-set enum, and the compiler enforces exhaustiveness
4496        // on every consumer's `match self` arms — this parse arm's
4497        // accepted-suffix set, the render arm's emitted-suffix set, the
4498        // validate gate's canonical-window set, and every future
4499        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4500        // by construction.
4501        let unit = unit.trim();
4502        let window = RateLimitUnit::window_from_suffix(unit)
4503            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4504        Ok(RateLimit { rate, window })
4505    }
4506
4507    fn render(rl: RateLimit) -> String {
4508        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4509        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4510        // this render arm reads the `Duration → RateLimitUnit` projection
4511        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4512        // (returns `None` on every non-canonical window — the sub-second /
4513        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4514        // formats the returned typed enum through its
4515        // [`std::fmt::Display`] impl (which routes through
4516        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4517        // the substrate primitive instead of one runtime `find_map`
4518        // walk through the free-helper delegate chain
4519        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4520        // sole production consumer was this arm; every other consumer of
4521        // the `Duration → unit` axis — the validate gate below and the
4522        // future M4 per-Aplicacao Envoy config reconciler — now reads
4523        // the same typed method).
4524        //
4525        // A future rate-limit-unit addition (a `"d"` day suffix once
4526        // Envoy's `rate_limit_action` grows daily-bucket support) is
4527        // one variant + one arm per method on the closed-set enum, and
4528        // the compiler enforces exhaustiveness on every consumer's
4529        // `match self` arms — the codec's `parse` accepted-suffix set,
4530        // this render arm's emitted-suffix set, the validate gate's
4531        // canonical-window set, and every future per-`:contratos`-edge
4532        // rate-limit-override overlay all pick it up by construction.
4533        if let Some(unit) = rl.canonical_unit() {
4534            format!("{}/{unit}", rl.rate())
4535        } else {
4536            // Defensive fallback for non-canonical windows. Note:
4537            // [`AplicacaoSpec::validate_politicas`] rejects any
4538            // non-canonical `:rate-limit :window` via
4539            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4540            // a validated `RateLimit` never reaches this branch. The
4541            // emitted `<n>/<k>s` form is *not* round-trippable through
4542            // [`parse`] (which accepts only the closed-set
4543            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4544            // explicit count) — the validate gate is what makes the
4545            // round-trip a structural property; this branch exists only
4546            // so a programmatic non-validated serialize doesn't panic.
4547            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4548        }
4549    }
4550}
4551
4552// ── placement strategy ───────────────────────────────────────────────
4553
4554/// How the Aplicacao distributes across clusters. Three options:
4555///
4556/// - `SingleNode` — one cluster runs the app at a time; takeover on
4557///   death (Erlang/OTP distributed-app semantics).
4558/// - `Replicated` — every named cluster runs an instance (active-active).
4559/// - `Sharded` — entities distribute by hash key across clusters
4560///   (Akka cluster sharding).
4561#[derive(
4562    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4563)]
4564pub enum PlacementStrategy {
4565    SingleNode,
4566    Replicated,
4567    Sharded,
4568}
4569
4570/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
4571/// distribution-strategy default for the `:placement :estrategia` axis —
4572/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
4573/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
4574/// so every substrate-side consumer that resolves "what
4575/// [`PlacementStrategy`] variant does an author-omitted `:placement
4576/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
4577/// primitive [`PlacementStrategy`].
4578///
4579/// The `:placement :estrategia` default axis has three production
4580/// consumers on the substrate side today: the [`Default for
4581/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
4582/// impl's struct-literal `estrategia` field, and the serde-side
4583/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
4584/// author-omitted `:placement :estrategia` scalar through the [`Default
4585/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
4586/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
4587/// impl and implicit `PlacementStrategy::default()` routes at the sibling
4588/// consumers, with no compile-time link back to the paired
4589/// [`crate::manifest::Caixa::aplicacao_view`] fold's
4590/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
4591/// production consumer that resolves an author-omitted `:placement` slot
4592/// (entirely omitted, not just the `:estrategia` scalar within a declared
4593/// `:placement` block) through [`Placement::default`] which then routes
4594/// through this same discriminator. A future coherent rebrand of the
4595/// `:placement :estrategia` default (a widening to `Sharded` once the
4596/// substrate discovers hash-keyed distribution as the more common
4597/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
4598/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
4599/// names, a per-cluster overlay the operator pins through a future
4600/// `:placement-overrides` slot) would have had to migrate a lifted
4601/// discriminator on one path and open-coded discriminators on the peers
4602/// in lockstep or the four consumers would silently drift out of
4603/// pairing. Lifting the resolution rule to a typed `pub const` on the
4604/// substrate primitive means the M3-mesh-canonical `:placement
4605/// :estrategia` default migrates as one unit on any future axis change.
4606///
4607/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
4608/// §II.2's active-active-across-every-named-cluster arm — the closest
4609/// canonical M3 production reference the substrate carries, matching the
4610/// caixa-mesh default axis every M3 renderer already keys off (a
4611/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
4612/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
4613/// under the substrate's fleet-programs aggregator without an explicit
4614/// `:placement :estrategia` override). The two alternatives the closed
4615/// [`PlacementStrategy::ALL`] accept-set carries
4616/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
4617/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
4618/// Akka-style hash-keyed distribution across clusters,
4619/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
4620/// postures an author declares explicitly, never a posture an omitted
4621/// slot should silently assume.
4622///
4623/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
4624/// exactly one source of truth on the `:placement :estrategia` axis, on
4625/// the same substrate-primitive lift discipline the sibling M2
4626/// per-supervisor default set carries
4627/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
4628/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
4629/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
4630/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
4631/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
4632/// ([`crate::render::DEFAULT_NAMESPACE`],
4633/// [`crate::render::DEFAULT_LIBRARY_NAME`],
4634/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
4635/// the M3 mesh-primitive-defining slot family to converge onto the
4636/// substrate-primitive-lift discipline the M2 supervisor-slot family
4637/// already carries end-to-end.
4638pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
4639
4640impl Default for PlacementStrategy {
4641    fn default() -> Self {
4642        // Route the [`Default for PlacementStrategy`] impl through the
4643        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
4644        // `pub const` rather than a raw `Self::Replicated` arm — one
4645        // source of truth for the M3-mesh-canonical active-active-
4646        // across-every-named-cluster `:placement :estrategia` default
4647        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
4648        // lift discipline the sibling M2 per-supervisor default set
4649        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
4650        // paired halves) carries end-to-end. Pinned by
4651        // `placement_strategy_default_routes_through_lifted_default`.
4652        PLACEMENT_ESTRATEGIA_DEFAULT
4653    }
4654}
4655
4656impl PlacementStrategy {
4657    /// Exhaustive iteration surface for every consumer that reads the
4658    /// full closed-set (the future M4 admission-webhook's accepted-
4659    /// strategy listing in its rejection body, a future `feira app
4660    /// placement --list` CLI-side surfacing of the accepted arm-set,
4661    /// any future round-trip fuzz harness). A future variant addition
4662    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4663    /// names as a trajectory item) extends this slice as a single edit
4664    /// and every consumer picks up the new entry by construction — the
4665    /// compiler-checked exhaustiveness on the sibling method `match`
4666    /// arms is the build-time guarantee that no arm forgets to grow.
4667    /// Same shape as the sibling closed-set typed enums'
4668    /// [`RateLimitUnit::ALL`] (6bce03d) and
4669    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4670    /// surfaces — the third closed-set typed enum on the caixa surface
4671    /// to converge onto the same discipline.
4672    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4673
4674    /// Canonical camelCase-schema discriminator scalar this variant
4675    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4676    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4677    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4678    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4679    /// every substrate consumer that dispatches on the strategy (the
4680    /// `lareira-fleet-programs` aggregator, the future `app-operator`
4681    /// reconciler, the M3 Adaptive compression pass) reads the same
4682    /// byte-string the `Serialize` derive emits — the pin test in
4683    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4684    /// asserts the two paths agree.
4685    #[must_use]
4686    pub const fn as_str(self) -> &'static str {
4687        match self {
4688            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4689            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4690            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4691        }
4692    }
4693
4694    /// Substrate-canonical reverse projection on the `:placement
4695    /// :estrategia` closed-set axis — parses the camelCase-schema
4696    /// discriminator scalar back to the typed variant, or `None` when
4697    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4698    /// emits. Dispatches on the same lifted
4699    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4700    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4701    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4702    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4703    /// the round-trip migrate through one caixa-core edit on any future
4704    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4705    /// §II.5 hint names as a trajectory item lands one variant + one
4706    /// arm per method and the compiler enforces exhaustiveness on every
4707    /// consumer's `match self` arms).
4708    ///
4709    /// Prior to this lift the substrate carried only the forward
4710    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4711    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4712    /// derive that emits the same byte-string under
4713    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4714    /// consumer that wanted to parse a wire-form strategy scalar had to
4715    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4716    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4717    /// compile-time link back to the typed variant's canonical lifted
4718    /// constant. A future variant rename or a per-arm serde-attribute
4719    /// drift would silently split the wire byte-string one non-serde
4720    /// consumer parsed from the one the emitter wrote, with the
4721    /// failure surfacing at parse time far from the rebrand commit.
4722    ///
4723    /// Same closed-set-reverse-projection discipline the sibling
4724    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4725    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4726    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4727    /// defining `:placement :estrategia` closed-set axis, the third
4728    /// substrate-side closed-set typed enum to converge on the two-way
4729    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4730    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4731    /// and side-step the [`std::str::FromStr`]-collision clippy
4732    /// (`clippy::should_implement_trait`) the plain `from_str` name
4733    /// carries; a future explicit [`std::str::FromStr`] impl can layer
4734    /// on top by delegating to this canonical arm-dispatch method.
4735    ///
4736    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4737    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4738    /// picks the diagnostic form appropriate for its use site — a
4739    /// future `feira app placement --set` CLI-side arg-parse that wants
4740    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4741    /// Sharded)"` diagnostic builds one on top by iterating
4742    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4743    /// path folds `None` onto its per-CR structured refusal body.
4744    #[must_use]
4745    pub fn from_wire(s: &str) -> Option<Self> {
4746        match s {
4747            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4748            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4749            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4750            _ => None,
4751        }
4752    }
4753
4754    /// Substrate-canonical per-arm predicate naming the cross-slot
4755    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
4756    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
4757    /// consumes the paired [`Placement::shard_key`] axis (and therefore
4758    /// requires — and is the only strategy that permits — a non-empty
4759    /// `:shard-key` on the paired slot). Today the accept-set is the
4760    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
4761    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
4762    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
4763    /// distributed-app takeover — §II.1) and `Replicated` (active-active
4764    /// across every named cluster) have no hash-keyed routing axis to
4765    /// consume the slot and refuse a declared-but-inert `:shard-key`
4766    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
4767    ///
4768    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
4769    /// satisfies `placement.shard_key().is_some() ==
4770    /// placement.estrategia().requires_shard_key()` by construction — the
4771    /// cross-slot partition the pin
4772    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
4773    /// locks load-bearing, so every downstream consumer that reaches for
4774    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4775    /// CR materializer's per-CR shard-key resolver, the future
4776    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
4777    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
4778    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
4779    /// shard-key requirement probe, a future author-facing tatara-lisp
4780    /// linter that flags `(:placement (:estrategia Replicated :shard-key
4781    /// "tenantId"))` shapes before `feira lint` reaches
4782    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
4783    /// the substrate primitive — the predicate names *the cross-slot
4784    /// invariant*, not the arm identity.
4785    ///
4786    /// Prior to this lift the "does this strategy consume `:shard-key`"
4787    /// classification lived under the `gen_platform::IsVariant`-derived
4788    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
4789    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
4790    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
4791    /// } else { None }` cascade, the
4792    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
4793    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
4794    /// "tenantId".to_string())` cascade, and the
4795    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
4796    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
4797    /// cascade). Each site conflated two semantically distinct questions:
4798    /// "is the variant `Sharded`?" (arm-identity, what
4799    /// [`Self::is_sharded`] answers) and "does the variant consume
4800    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
4801    /// The two questions land on the same three-way answer under today's
4802    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
4803    /// future arm addition that consumed `:shard-key` under a different
4804    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
4805    /// §II.5 roadmap-hint names that hash-partitions across the cluster
4806    /// pool by client-IP hash rather than an author-declared extractor
4807    /// expression, a hypothetical `WeightedShard` variant that carries a
4808    /// shard-key + per-cluster weight table under a promoted M5
4809    /// adaptive-placement engine) or an addition that did *not* consume
4810    /// `:shard-key` on a semantically Sharded-shaped arm would silently
4811    /// split the two questions. Any consumer that read
4812    /// `.is_sharded().then(…)` for the shard-key requirement gate would
4813    /// silently misclassify the new arm as non-consuming — a fixture
4814    /// builder would omit `:shard-key` where the new arm required one and
4815    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
4816    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
4817    /// commit, a future M4 CR materializer would fall through the
4818    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
4819    /// silently emit an empty extractor at the Akka reconciler layer.
4820    ///
4821    /// Lifting the classification as a substrate-primitive method on the
4822    /// closed-set typed enum names the cross-slot invariant on the
4823    /// primitive that owns the partition: every future arm addition
4824    /// declares its `:shard-key` consumption in one place (this predicate's
4825    /// `match self` arm-set), and every downstream consumer that reaches
4826    /// for the paired shape reads through one typed dispatch. Same
4827    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
4828    /// per-arm predicate on the pre-projection WIT-shape axis and the
4829    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
4830    /// paired predicate on the post-projection typed-view axis — a
4831    /// per-arm semantic-classification predicate paired with the
4832    /// arm-identity predicate the derive already emits, closing the drift
4833    /// footgun on the cross-slot invariant axis.
4834    ///
4835    /// Method-named `requires_shard_key` (not `has_shard_key`, not
4836    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
4837    /// invariant reads as "this strategy *requires* the paired
4838    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
4839    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
4840    /// merely omit it. The `has_*` framing would read as an accessor
4841    /// (returning the presence of an already-carried value) rather than a
4842    /// requirement (naming the invariant the paired slot must satisfy).
4843    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
4844    /// shape as the sibling [`WitContract::is_capability`] /
4845    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
4846    /// arm-family, so every consumer reaches for `.requires_shard_key()`
4847    /// as a drop-in replacement for the `.is_sharded()` conflated read
4848    /// without a return-shape migration.
4849    #[must_use]
4850    pub const fn requires_shard_key(self) -> bool {
4851        match self {
4852            Self::Sharded => true,
4853            Self::SingleNode | Self::Replicated => false,
4854        }
4855    }
4856}
4857
4858// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
4859// cross-slot-invariant per-arm predicate: the module-scope const-eval
4860// assertions below trip at caixa-core build time (not test time) if a
4861// future edit rewires the predicate's arm-set away from the singleton
4862// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
4863// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
4864// runtime pin covers the same truth-table with a more descriptive
4865// diagnostic on failure; these const-eval items add a build-time failure
4866// surface strictly stronger than the runtime pin (a downstream renderer's
4867// `const`-context reader that composed against a rebound predicate would
4868// still surface here before the test suite even ran) and side-step the
4869// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
4870// would otherwise accumulate on the caixa-core module baseline.
4871const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
4872const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
4873const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
4874
4875/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4876/// the pretty-printed byte-string every consumer that formats the strategy
4877/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4878/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4879/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4880/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4881/// admission-webhook rejection body) reaches for the same lifted
4882/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4883/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4884/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4885/// `Serialize` derive already emits under
4886/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4887/// [`PlacementStrategy::as_str`] helper already returns.
4888///
4889/// Until this lift landed the sibling OTP-shape typed enums —
4890/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4891/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4892/// so [`std::fmt::Display`] routes through the same discriminant string
4893/// the wire format emits) — carried a stable [`std::fmt::Display`]
4894/// surface but [`PlacementStrategy`] did not; every consumer reaching
4895/// for a strategy byte-string past the wire format had to pick between
4896/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4897/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4898/// derive), any two of which a future variant rename or
4899/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4900/// desynchronize — with the failure surfacing as a downstream renderer /
4901/// operator's per-strategy dispatch reading one spelling while the wire
4902/// format emitted another, far from the source rebrand commit and with
4903/// no field naming the drift. Routing `Display` through
4904/// [`PlacementStrategy::as_str`] makes the three paths
4905/// (`Debug` for structural inspection, `Display` for user-facing text,
4906/// `Serialize` for the wire format) converge on the same lifted
4907/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4908/// the diagnostic byte-string, and the pretty-printed byte-string move
4909/// as a single unit through one canonical declaration each, by
4910/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4911/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4912/// closes the third path.
4913///
4914/// Pin tests
4915/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4916/// and
4917/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4918/// assert the three paths agree byte-for-byte on every variant, so a
4919/// future variant rename or per-arm serde attribute drift is a build
4920/// error visible at caixa-core test time, not a silent per-consumer
4921/// dispatch miss at apply / reconcile time.
4922impl std::fmt::Display for PlacementStrategy {
4923    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4924        f.write_str(self.as_str())
4925    }
4926}
4927
4928/// Where the Aplicacao runs.
4929#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4930#[serde(rename_all = "camelCase")]
4931pub struct Placement {
4932    /// Distribution strategy.
4933    #[serde(default)]
4934    pub estrategia: PlacementStrategy,
4935
4936    /// Named clusters that host this Aplicacao. Required for
4937    /// `Replicated` and `SingleNode`; for `Sharded` declares the
4938    /// shard pool.
4939    #[serde(default)]
4940    pub clusters: Vec<String>,
4941
4942    /// Optional hint to the placement engine: `"data-locality"`,
4943    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4944    #[serde(default, skip_serializing_if = "Option::is_none")]
4945    pub affinity: Option<String>,
4946
4947    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4948    #[serde(default, skip_serializing_if = "Option::is_none")]
4949    pub shard_key: Option<String>,
4950}
4951
4952impl Placement {
4953    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4954    /// `:shard-key` extractor-expression scalar accessor every consumer
4955    /// of the Aplicacao's hash-keyed distribution routing keys off —
4956    /// returns the author-declared `:placement :shard-key` byte-string
4957    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4958    /// own `Option<String>` storage; `None` when the slot is absent
4959    /// (the canonical shape under `:estrategia Replicated` /
4960    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4961    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4962    /// partition — `validate` refuses any `Placement` past this call
4963    /// that lands `Some` on a non-`Sharded` strategy or `None` on
4964    /// `Sharded`).
4965    ///
4966    /// The `:placement :shard-key` slot carries the Akka-style
4967    /// cluster-sharding entity-id extractor expression
4968    /// (MESH-COMPOSITION §II.4) — validated by
4969    /// [`validate_placement_shard_key`] to be a non-empty printable-
4970    /// ASCII single-token reference (`tenantId`, `$tenantId`,
4971    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4972    /// future M4 Akka-style cluster-sharding reconciler hashes without
4973    /// re-validating at the runtime layer), and every downstream
4974    /// consumer that reads the key keys off this scalar (the
4975    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4976    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4977    /// declared-but-inert refusal diagnostic, the caixa-mesh
4978    /// per-Aplicacao `placement.shardKey` emit path the substrate
4979    /// operator's per-entity hash-routing reader consumes, the future
4980    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4981    /// per-shard-key resolver).
4982    ///
4983    /// Prior to this lift the `.shard_key` field was accessed inline at
4984    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4985    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4986    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4987    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4988    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4989    /// — two open-coded field-accesses that expressed no compile-time
4990    /// link back to the typed slot. A future extension of the
4991    /// `:placement :shard-key` axis to a richer author surface — a
4992    /// per-cluster override the operator pins through a future
4993    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4994    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4995    /// alias table the M4 CR materializer resolves per-CR, a
4996    /// per-Aplicacao dynamic `:shard-key` derivation the future
4997    /// adaptive placement engine computes from `:affinity` weights —
4998    /// would have had to be threaded through both open-coded copies in
4999    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5000    /// arm refusal would silently disagree on which extractor
5001    /// expression a given Placement resolves to. Lifting the resolution
5002    /// rule to a typed method on the substrate primitive means every
5003    /// downstream consumer of the Aplicacao's per-`:placement`
5004    /// hash-key surface reaches for exactly one typed dispatch — the
5005    /// resolver's accept-set migrates as a unit on any future axis
5006    /// addition.
5007    ///
5008    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5009    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5010    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5011    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5012    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5013    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5014    /// typed dispatch on the substrate primitive, thin projections at
5015    /// each consumer" discipline extended onto the per-`:placement`
5016    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5017    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5018    /// — opens the "optional per-slot scalar" projection pattern the
5019    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5020    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5021    /// match the storage field's name; the accessor's identity name
5022    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5023    /// slot's docstring already carries.
5024    #[must_use]
5025    pub fn shard_key(&self) -> Option<&str> {
5026        self.shard_key.as_deref()
5027    }
5028
5029    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5030    /// compression-hint scalar accessor every weighting-consumer of the
5031    /// Aplicacao's per-hint routing surface keys off — returns the
5032    /// author-declared `:placement :affinity` byte-string verbatim as
5033    /// an `Option<&str>`, borrowed from the typed slot's own
5034    /// `Option<String>` storage; `None` when the slot is absent (the
5035    /// canonical shape of an Aplicacao that leaves the compression
5036    /// weighting up to the placement engine's cluster-default arm — no
5037    /// author-authored `data-locality` / `low-latency` / etc. hint
5038    /// biases the routing).
5039    ///
5040    /// The `:placement :affinity` slot carries the M3 Adaptive-
5041    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5042    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5043    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5044    /// K8s-conformant label-selector shape every apiserver-side pod-
5045    /// affinity / node-affinity materializer already gates on
5046    /// admission), and every downstream consumer that reads the hint
5047    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5048    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5049    /// `placement.affinity` overlay emit path the substrate operator's
5050    /// per-hint weighting-consumer reads, the future M4
5051    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5052    /// pod-affinity / node-affinity selector resolver).
5053    ///
5054    /// Prior to this lift the `.affinity` field was accessed inline at
5055    /// the sole caixa-core site — the
5056    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5057    /// `if let Some(a) = &self.placement.affinity { …
5058    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5059    /// field-access that expressed no compile-time link back to the
5060    /// typed slot. A future extension of the `:placement :affinity`
5061    /// axis to a richer author surface — a per-cluster override the
5062    /// operator pins through a future `:placement :affinity-overrides`
5063    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5064    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5065    /// a per-Aplicacao dynamic `:affinity` derivation the future
5066    /// adaptive placement engine computes from `:clusters` topology —
5067    /// would have had to be threaded through the open-coded copy in
5068    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5069    /// materializer reader that landed on the axis, or the per-hint
5070    /// value-shape gate and its downstream weighting consumers would
5071    /// silently disagree on which hint a given Placement resolves to.
5072    /// Lifting the resolution rule to a typed method on the substrate
5073    /// primitive means every downstream consumer of the Aplicacao's
5074    /// per-`:placement` compression-hint surface reaches for exactly
5075    /// one typed dispatch — the resolver's accept-set migrates as a
5076    /// unit on any future axis addition.
5077    ///
5078    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5079    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5080    /// optional-scalar axis — same "one typed dispatch on the substrate
5081    /// primitive, thin projections at each consumer" discipline extended
5082    /// onto the per-`:placement` M3-Adaptive-compression-hint
5083    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5084    /// return accessor on the M3 mesh-slot family; closes the last
5085    /// un-lifted per-`:placement` `Option<String>` axis. Named
5086    /// `affinity()` to match the storage field's name; the accessor's
5087    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5088    /// vocabulary the slot's docstring already carries.
5089    #[must_use]
5090    pub fn affinity(&self) -> Option<&str> {
5091        self.affinity.as_deref()
5092    }
5093
5094    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5095    /// strategy scalar accessor every consumer that dispatches on the
5096    /// Aplicacao's per-cluster distribution shape keys off — returns the
5097    /// author-declared `:placement :estrategia` variant verbatim as a
5098    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5099    /// `PlacementStrategy` storage.
5100    ///
5101    /// The `:placement :estrategia` slot carries the closed-set
5102    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5103    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5104    /// `Replicated` — active-active across every named cluster; `Sharded`
5105    /// — Akka-style hash-keyed entity distribution across the cluster pool
5106    /// per §II.4) that every downstream consumer of the Aplicacao's
5107    /// per-cluster fan-out shape keys off. Validated by
5108    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5109    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5110    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5111    /// [`Placement::shard_key`] accessor's docstring pins), and every
5112    /// downstream consumer that reads the strategy keys off this scalar
5113    /// (the [`AplicacaoSpec::validate_placement`]
5114    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5115    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5116    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5117    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5118    /// declared-but-inert refusal's
5119    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5120    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5121    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5122    /// emit path the substrate operator's per-strategy fan-out reader
5123    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5124    /// materializer's per-strategy admission-webhook resolver).
5125    ///
5126    /// Prior to this lift the `.estrategia` field was accessed inline at
5127    /// four sites — the [`AplicacaoSpec::validate_placement`]
5128    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5129    /// `estrategia: self.placement.estrategia`, the same method's
5130    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5131    /// partition dispatch, the non-`Sharded`-arm
5132    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5133    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5134    /// per-Aplicacao strategy print line at
5135    /// `println!("… {} …", spec.placement.estrategia, …)`
5136    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5137    /// expressed no compile-time link back to the typed slot. A future
5138    /// extension of the `:placement :estrategia` axis to a richer author
5139    /// surface (a per-cluster override the operator pins through a future
5140    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5141    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5142    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5143    /// derivation the future adaptive placement engine computes from
5144    /// `:affinity` + `:clusters` topology) would have had to be threaded
5145    /// through every open-coded copy in lockstep — one consumer reading
5146    /// the raw variant while a peer read the operator-resolved variant
5147    /// would silently split the `PlacementWithoutClusters` /
5148    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5149    /// partition-dispatch input, a two-consumer split at the validator
5150    /// far from the source `caixa.lisp` with no field naming the
5151    /// strategy-drift root cause. Lifting the resolution rule to a typed
5152    /// method on the substrate primitive means every downstream consumer
5153    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5154    /// reaches for exactly one typed dispatch — the resolver's accept-set
5155    /// migrates as a unit on any future axis addition.
5156    ///
5157    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5158    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5159    /// same "one typed dispatch on the substrate primitive, thin
5160    /// projections at each consumer" discipline extended onto the
5161    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5162    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5163    /// family; first `Copy`-return accessor on the M3 mesh-slot
5164    /// `Placement` type — companion to the sibling per-`:placement`
5165    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5166    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5167    /// optional-scalar axes, closing the last unlifted per-`:placement`
5168    /// scalar-value axis (the closed-set `PlacementStrategy`
5169    /// distribution-strategy discriminator) so every downstream
5170    /// per-`:placement` reader now routes through a typed dispatch on
5171    /// the substrate primitive. Named `estrategia()` to match the storage
5172    /// field's name; the accessor's identity name maps onto the
5173    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5174    /// already carries. Declared `pub const fn` (matching the peer M3
5175    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5176    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5177    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5178    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5179    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5180    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5181    /// [`RateLimit`] — every one a `pub const fn`) so every future
5182    /// substrate-side `const`-context consumer of the resolved
5183    /// distribution-strategy variant (a `const _: () = assert!(…)`
5184    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5185    /// a future M4 admission-webhook `const fn` resolver over a typed
5186    /// [`Placement`], any `const fn` composer that fans on the strategy
5187    /// at compile time) reaches through the same typed dispatch on the
5188    /// substrate primitive at const-eval time as at runtime. Pinned by
5189    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5190    /// const-eval posture at module scope via `const _:() = …` items so
5191    /// any future accidental downgrade to non-`const` trips at caixa-core
5192    /// build time.
5193    #[must_use]
5194    pub const fn estrategia(&self) -> PlacementStrategy {
5195        self.estrategia
5196    }
5197
5198    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5199    /// per-cluster distribution-target slice accessor every consumer that
5200    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5201    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5202    /// `&[String]` slice-view, borrowed from the typed slot's own
5203    /// `Vec<String>` storage (a zero-copy slice-view over the same
5204    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5205    /// through). Non-optional: the empty slice is the load-bearing
5206    /// pre-validation sentinel every downstream consumer of the paired
5207    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5208    /// off — every strategy in the closed
5209    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5210    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5211    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5212    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5213    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5214    /// `.is_empty()` probe is the shared pre-condition every
5215    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5216    ///
5217    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5218    /// 1123-label per-cluster distribution-target list — the same
5219    /// set-not-multiset shape the sibling `:membros :caixa` /
5220    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5221    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5222    /// pins the shape). Every downstream consumer that fans on the list
5223    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5224    /// pre-flight `.is_empty()` probe that trips
5225    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5226    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5227    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5228    /// that materializes the list verbatim onto every
5229    /// programs.yaml entry the substrate operator's per-cluster
5230    /// `placement.clusters | contains .Values.cluster` filter reads,
5231    /// the `feira app graph` per-Aplicacao cluster print line, the
5232    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5233    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5234    /// placement engine's cluster-topology reader).
5235    ///
5236    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5237    /// inline at three production sites — the
5238    /// [`AplicacaoSpec::validate_placement`] pre-flight
5239    /// `self.placement.clusters.is_empty()` refusal probe, the same
5240    /// method's per-cluster validate loop's
5241    /// `for c in &self.placement.clusters` traversal head, and the
5242    /// `feira app graph` per-Aplicacao print line's
5243    /// `spec.placement.clusters` `{:?}` formatter argument
5244    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5245    /// that expressed no compile-time link back to the typed slot. A
5246    /// future extension of the `:placement :clusters` axis to a richer
5247    /// author surface (a per-tenant cluster-pool overlay the operator
5248    /// pins through a future `:placement :clusters-overrides` slot the
5249    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5250    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5251    /// the future M5 adaptive-placement engine computes from
5252    /// `:affinity` weights + live cluster-topology probes, a promotion
5253    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5254    /// partition once the substrate operator's cluster-membership
5255    /// reconciler comes into typed scope) would have had to be threaded
5256    /// through all three open-coded copies in lockstep or one consumer
5257    /// would silently disagree with the peers on which cluster-pool a
5258    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5259    /// reading the raw slot while the peer per-cluster validate loop
5260    /// read an operator-resolved slot would silently split the paired
5261    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5262    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5263    /// input from the pre-flight input, a three-consumer split at the
5264    /// validator and formatter far from the source `caixa.lisp` with
5265    /// no field naming the cluster-pool-drift root cause. Lifting the
5266    /// resolution rule to a typed method on the substrate primitive
5267    /// means every downstream consumer of the Aplicacao's
5268    /// per-`:placement` cluster-pool surface reaches for exactly one
5269    /// typed dispatch — the resolver's accept-set migrates as a unit
5270    /// on any future axis addition.
5271    ///
5272    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5273    /// slot — sibling to the seed M2
5274    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5275    /// slice-return accessor on the peer per-`:supervisor` static-
5276    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5277    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5278    /// primitive, thin projections at each consumer" discipline. The
5279    /// three peer `Vec`-carry axes still unlifted at the time of this
5280    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5281    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5282    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5283    /// [`crate::UpgradeFromEntry::instructions`]
5284    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5285    /// — inherit this accessor's discipline as future compounding runs
5286    /// migrate their consumers onto the shared slice-return shape.
5287    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5288    /// type, sibling to the two `Option<&str>`-return
5289    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5290    /// (74ec2d3) accessors and the `Copy`-return
5291    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5292    /// unlifted per-`:placement` field axis (the `Vec<String>`
5293    /// distribution-target-list carrier) so every downstream
5294    /// per-`:placement` reader now routes through a typed dispatch on
5295    /// the substrate primitive. Named `clusters()` to match the storage
5296    /// field's name verbatim and the tatara-lisp author-surface term
5297    /// (`:clusters`) the field's own docstring already carries; the
5298    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5299    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5300    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5301    /// downstream consumer of the cluster list treats it as a read-only
5302    /// sequence — the slice-view is the narrowest borrow that supports
5303    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5304    /// `.len()`) without leaking the backing `Vec`'s
5305    /// grow/push/reserve surface that no consumer of the typed view
5306    /// reaches for (the storage-side `Vec` remains reachable through
5307    /// the `pub clusters` field for the mutation-carrying serde
5308    /// round-trip and per-test fixture-mutation paths).
5309    #[must_use]
5310    pub fn clusters(&self) -> &[String] {
5311        self.clusters.as_slice()
5312    }
5313}
5314
5315impl Default for Placement {
5316    fn default() -> Self {
5317        Self {
5318            // Route the struct-literal `estrategia` default arm through
5319            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5320            // typed `pub const` rather than the transitively-derived
5321            // [`PlacementStrategy::default`] route — one source of truth
5322            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5323            // active-active-across-every-named-cluster arm
5324            // (MESH-COMPOSITION §II.2) that both this struct-literal
5325            // altitude and the sibling [`Default for PlacementStrategy`]
5326            // impl already key off through the same substrate primitive.
5327            // Pinned by
5328            // `placement_default_estrategia_routes_through_lifted_default`.
5329            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5330            clusters: Vec::new(),
5331            affinity: None,
5332            shard_key: None,
5333        }
5334    }
5335}
5336
5337// ── external entry point ─────────────────────────────────────────────
5338
5339/// External entry point — what an outside caller sees. Renders to a
5340/// Gateway / Ingress + a route to the named member Servico.
5341#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5342#[serde(rename_all = "camelCase")]
5343pub struct Entrada {
5344    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5345    pub host: String,
5346
5347    /// Member Servico the gateway routes to. Must be in `:membros`.
5348    pub para: String,
5349
5350    /// Optional path filter — if set, only matching paths route to
5351    /// this Aplicacao (the rest fall through to other route rules).
5352    #[serde(default)]
5353    pub paths: Vec<String>,
5354
5355    /// Default port on the destination Servico (the trigger.service.port).
5356    #[serde(default = "default_port")]
5357    pub port: u16,
5358}
5359
5360impl Entrada {
5361    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5362    /// every HTTPRoute-aware renderer keys off — returns the author-
5363    /// declared `:entrada :paths` list verbatim when non-empty, and the
5364    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5365    /// all fallback otherwise (so an Aplicacao author who declares an
5366    /// external `:entrada` block but no per-path rule surface still
5367    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5368    /// request under the paired
5369    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5370    ///
5371    /// Prior to this lift the "if `:entrada :paths` is empty use the
5372    /// substrate catch-all; else return each declared path verbatim"
5373    /// cascade lived inline at
5374    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5375    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5376    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5377    /// substrate ships today, with no typed method on the substrate
5378    /// primitive that named the rule. A future path-resolution axis
5379    /// addition — a per-cluster `:entrada :default-path` override the
5380    /// operator pins through a future `:placement`-scoped slot, an
5381    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5382    /// admission-webhook floor that materializes the catch-all before
5383    /// the CR lands, a future per-`:entrada :paths` overlay from a
5384    /// per-cluster policy the future `feira app deploy` pipeline
5385    /// consumes — would have to be threaded through every renderer's
5386    /// inline copy of the cascade in lockstep or one consumer would
5387    /// silently disagree with the peers on which path list a given
5388    /// `:entrada` block resolves to. Lifting the rule to a typed
5389    /// method on the substrate primitive means every downstream
5390    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5391    /// per-cluster overlay resolver, every future per-Aplicacao
5392    /// snapshot renderer) reaches for exactly one typed dispatch —
5393    /// the resolver's accept-set moves as a unit on any future axis
5394    /// addition.
5395    ///
5396    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5397    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5398    /// per-`:entrada` scalar-value axes — extends the "one typed
5399    /// dispatch on the substrate primitive, thin projections at each
5400    /// consumer" discipline onto the per-`:entrada` path-list
5401    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5402    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5403    /// sibling `:politicas` primitive — one typed method on the
5404    /// substrate primitive that names the cascade every renderer
5405    /// otherwise re-inlines.
5406    #[must_use]
5407    pub fn resolved_paths(&self) -> Vec<&str> {
5408        // Route the internal cascade-head + per-entry projection reads
5409        // through the lifted [`Self::paths`] slice accessor rather than
5410        // the raw `self.paths` field access — the substrate-primitive
5411        // per-`:entrada` path-list resolver's two internal reads now
5412        // key off the canonical raw-slot surface every downstream
5413        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5414        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5415        // entrada summary line's `{:?}` Debug print) routes through, so
5416        // any future rebrand on the typed slot's raw-slot reader lands
5417        // at exactly one place. Same two-consumer coherence discipline
5418        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5419        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5420        if self.paths().is_empty() {
5421            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5422        } else {
5423            self.paths().iter().map(String::as_str).collect()
5424        }
5425    }
5426
5427    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5428    /// accessor every Gateway-API `Listener.hostname` reader keys off
5429    /// — returns the author-declared `:entrada :host` byte-string
5430    /// verbatim as a `&str`, borrowed from the typed slot's own
5431    /// [`String`] storage.
5432    ///
5433    /// Named the "singular" half of the DNS-hostname resolver pair on
5434    /// the substrate primitive: the parent-Gateway per-listener
5435    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5436    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5437    /// hostname per listener), and this accessor is the typed dispatch
5438    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5439    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5440    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5441    /// per-Aplicacao ingress-hostname surface projects onto.
5442    ///
5443    /// Prior to this lift the `entrada.host.clone()` byte-string was
5444    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5445    /// per-listener singular `hostname:` axis
5446    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5447    /// per-HTTPRoute plural `spec.hostnames[]` axis
5448    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5449    /// consumers read the same `entrada.host` field but the two-site
5450    /// duplication expressed no compile-time contract that the singular
5451    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5452    /// stay in lockstep on future extensions of the `:entrada` slot to
5453    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5454    /// overlay, a per-cluster SNI fan-out the operator pins through a
5455    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5456    /// Aplicacao` CR materializer's per-listener virtual-host filter
5457    /// admission-webhook overlay). Any such extension would have to be
5458    /// threaded through every renderer's inline copy of the resolution
5459    /// in lockstep or the Gateway listener's `hostname:` filter would
5460    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5461    /// — a Gateway-API-conformance divergence whose apply-time symptom
5462    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5463    /// `NoMatchingParent` — the API server rejects the route because
5464    /// its `hostnames[]` filter doesn't intersect the parent listener's
5465    /// `hostname` filter) is far from the source `caixa.lisp` and never
5466    /// surfaces in the emitted YAML. Lifting the singular and plural
5467    /// resolvers to typed methods on the substrate primitive means
5468    /// every consumer of the Aplicacao's ingress-hostname surface
5469    /// reaches for exactly one typed dispatch, and the pair-invariant
5470    /// `hostnames() == vec![hostname()]` pinned by the sibling
5471    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5472    /// keeps the two axes in lockstep by construction.
5473    ///
5474    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5475    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5476    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5477    /// the substrate primitive, thin projections at each consumer"
5478    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5479    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5480    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5481    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5482    /// `:entrada` scalar-value + list-value axes.
5483    #[must_use]
5484    pub fn hostname(&self) -> &str {
5485        self.host.as_str()
5486    }
5487
5488    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5489    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5490    /// keys off — returns the singleton `[hostname()]` list under
5491    /// today's single-hostname-per-Aplicacao author surface, and the
5492    /// authoritative multi-hostname list under a future
5493    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5494    ///
5495    /// Plural half of the DNS-hostname resolver pair — see the
5496    /// companion [`Entrada::hostname`] docstring for the two-consumer
5497    /// lift + pair-invariant discipline (`hostnames() ==
5498    /// vec![hostname()]`, pinned load-bearing by the sibling
5499    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5500    /// test).
5501    ///
5502    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5503    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5504    /// per-rule path-list axis — same `Vec<&str>` shape, same
5505    /// substrate-primitive-owns-the-resolver discipline extended to
5506    /// the per-HTTPRoute virtual-host filter-list axis.
5507    #[must_use]
5508    pub fn hostnames(&self) -> Vec<&str> {
5509        vec![self.hostname()]
5510    }
5511
5512    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5513    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5514    /// the author-declared `:entrada :para` byte-string verbatim as a
5515    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5516    ///
5517    /// The `:entrada :para` slot names the single member Servico the
5518    /// external Gateway routes to (validated by
5519    /// [`AplicacaoSpec::validate`] to be a
5520    /// [`Membro::caixa`] the Aplicacao declares — a stray
5521    /// `:para` that doesn't name a member is
5522    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5523    /// backend-attachment miss at cluster-apply time). Under today's
5524    /// single-destination author surface `:entrada :para` is the ingress
5525    /// apex Servico's canonical identity; under a hypothetical
5526    /// future multi-backend author surface (a `:entrada
5527    /// :split :backends` weighted-fan-out overlay for canary /
5528    /// blue-green traffic-split rollouts, per-path override for
5529    /// path-based per-Servico routing beyond the single-apex model,
5530    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5531    /// per-CR admission-webhook that promotes the scalar to a
5532    /// weighted list) this accessor is the substrate primitive's typed
5533    /// dispatch every downstream `HTTPRoute`-aware consumer routes
5534    /// through, so the resolution shape migrates as a unit on one
5535    /// caixa-core edit rather than a coordinated rewrite across every
5536    /// renderer's inline field-access.
5537    ///
5538    /// Prior to this lift the `entrada.para` byte-string was accessed
5539    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5540    /// `metadata.name` composer's per-destination discriminator arg
5541    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5542    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5543    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5544    /// (`entrada.para.clone()`,
5545    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5546    /// consumers read the same `entrada.para` field but the two-site
5547    /// duplication expressed no compile-time contract that the HTTPRoute
5548    /// name-discriminator and the per-rule backend name stay in
5549    /// lockstep on future extensions of the `:entrada` slot to a
5550    /// multi-destination author surface. Any such extension would have
5551    /// to be threaded through every renderer's inline copy of the
5552    /// destination projection in lockstep or the HTTPRoute
5553    /// `metadata.name` would silently reference a different destination
5554    /// than its own `backendRefs[]` — an operator-side
5555    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5556    /// grep-by-name lookup would land on a route whose `backendRefs[]`
5557    /// silently point at a peer Servico, dropping every external
5558    /// `:entrada` flow at the gateway with the destination-drift root
5559    /// cause invisible in the emitted YAML.
5560    ///
5561    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5562    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5563    /// the per-listener singular / per-HTTPRoute plural filter axes and
5564    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5565    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5566    /// typed dispatch on the substrate primitive, thin projections at
5567    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5568    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5569    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5570    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5571    /// sibling per-`:entrada` scalar-value + list-value axes — this
5572    /// accessor closes the last unlifted per-`:entrada` scalar axis
5573    /// (the destination-Servico byte-string) so every downstream
5574    /// per-`:entrada` reader now routes through a typed dispatch on
5575    /// the substrate primitive.
5576    #[must_use]
5577    pub fn destination(&self) -> &str {
5578        self.para.as_str()
5579    }
5580
5581    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5582    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5583    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5584    /// reader keys off — returns the author-declared `:entrada :port`
5585    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5586    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5587    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5588    /// [`AplicacaoError::EntradaPortZero`], not a silent
5589    /// admission-webhook rejection at cluster-apply time).
5590    ///
5591    /// The `:entrada :port` slot carries the destination Servico's
5592    /// canonical in-cluster L4 listener port (`trigger.service.port` on
5593    /// the `pleme-computeunit` library chart), and every downstream
5594    /// consumer that reads the port keys off this scalar (the
5595    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5596    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5597    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5598    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5599    /// CR materializer's per-Aplicacao gateway port resolver).
5600    ///
5601    /// Prior to this lift the `.port` field was accessed inline at two
5602    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5603    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5604    /// the [`AplicacaoSpec::port_for_destination`] resolver's
5605    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5606    /// open-coded field-accesses that expressed no compile-time link
5607    /// back to the typed slot. A future extension of the `:entrada :port`
5608    /// axis to a richer author surface — a per-cluster override the
5609    /// operator pins through a future `:placement :default-port` slot the
5610    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5611    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5612    /// heterogeneous listener ports, an M4
5613    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5614    /// admission-webhook floor that promotes the scalar to a
5615    /// per-destination map — would have had to be threaded through both
5616    /// open-coded copies in lockstep or the structural-floor validator
5617    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5618    /// silently disagree on which port a given [`Entrada`] resolves to.
5619    /// Lifting the resolution rule to a typed method on the substrate
5620    /// primitive means every downstream consumer of the Aplicacao's
5621    /// per-`:entrada` L4-port surface reaches for exactly one typed
5622    /// dispatch — the resolver's accept-set migrates as a unit on any
5623    /// future axis addition.
5624    ///
5625    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5626    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5627    /// accessors on the per-`:entrada` scalar-value axis — same "one
5628    /// typed dispatch on the substrate primitive, thin projections at
5629    /// each consumer" discipline extended onto the per-`:entrada`
5630    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5631    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5632    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5633    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5634    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5635    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5636    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5637    /// storage field's name; the accessor's identity name maps onto the
5638    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5639    /// already carries. Declared `pub const fn` (matching the peer M3
5640    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5641    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5642    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5643    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5644    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5645    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5646    /// [`RateLimit`], and the sibling per-`:placement`
5647    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
5648    /// enum scalar axis — every one a `pub const fn`) so every future
5649    /// substrate-side `const`-context consumer of the resolved
5650    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
5651    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
5652    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
5653    /// admission-webhook `const fn` per-CR gateway-port floor over a
5654    /// typed [`Entrada`], any `const fn` composer that fans on the port
5655    /// at compile time) reaches through the same typed dispatch on the
5656    /// substrate primitive at const-eval time as at runtime. Pinned by
5657    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
5658    /// const-eval posture at module scope via `const _:() = …` items so
5659    /// any future accidental downgrade to non-`const` trips at caixa-core
5660    /// build time.
5661    #[must_use]
5662    pub const fn port(&self) -> u16 {
5663        self.port
5664    }
5665
5666    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5667    /// slice accessor every HTTPRoute-aware renderer keys off when it
5668    /// wants the raw author-declared path-list (not the fallback-
5669    /// applied projection [`Self::resolved_paths`] returns) — returns
5670    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5671    /// borrowed from the typed slot's own [`Vec<String>`] storage.
5672    ///
5673    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5674    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5675    /// (1449891) closes the fallback-applying arm every per-Aplicacao
5676    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5677    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5678    /// catch-all; non-empty slot → per-entry verbatim projection); this
5679    /// accessor closes the raw-slot arm every consumer that must see the
5680    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5681    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5682    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5683    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5684    /// external-gateway summary line's `{:?}` Debug print — which must
5685    /// name the author's declaration, not the substrate's fallback, so
5686    /// an author reading their graph output can grep their caixa.lisp
5687    /// for the exact list they authored) routes through.
5688    ///
5689    /// Prior to this lift the `.paths` field was accessed inline at four
5690    /// production sites: the two internal reads in [`Self::resolved_paths`]
5691    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5692    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5693    /// value-shape gate's `for p in &e.paths` traversal head, and the
5694    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5695    /// Debug print — four open-coded field-accesses that expressed no
5696    /// compile-time link back to the typed slot. A future extension of
5697    /// the `:entrada :paths` axis to a richer author surface — a
5698    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5699    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5700    /// spec supports through `matches[].method`), a per-path per-header
5701    /// filter overlay (`matches[].headers[]`), a per-cluster override
5702    /// the operator pins through a future `:placement :path-overlay`
5703    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5704    /// per-CR admission-webhook that normalized the list at admission
5705    /// time — would have had to be threaded through every open-coded
5706    /// copy in lockstep or the validator's per-entry gate would silently
5707    /// disagree with the renderer's per-entry emit on which list a given
5708    /// `:entrada` block resolves to. Lifting the resolution to a typed
5709    /// method on the substrate primitive means every downstream consumer
5710    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5711    /// exactly one typed dispatch — the resolver's accept-set migrates
5712    /// as a unit on any future axis addition.
5713    ///
5714    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5715    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5716    /// carry axis — same "one typed dispatch on the substrate primitive,
5717    /// thin projections at each consumer" discipline extended onto the
5718    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5719    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5720    /// carrier) so every downstream per-`:entrada` reader now routes
5721    /// through a typed dispatch on the substrate primitive. Returns
5722    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5723    /// treats the list as a read-only sequence — the slice-view is the
5724    /// narrowest borrow that supports every present + roadmapped consumer
5725    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5726    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5727    /// view reaches for (the storage-side `Vec` remains reachable through
5728    /// the `pub paths` field for the mutation-carrying serde round-trip
5729    /// and per-test fixture-mutation paths).
5730    #[must_use]
5731    pub fn paths(&self) -> &[String] {
5732        self.paths.as_slice()
5733    }
5734}
5735
5736/// Canonical default L4 port every typed Servico exposes on its
5737/// in-cluster K8s Service (the `trigger.service.port` axis the
5738/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5739/// surface defaults to when the author omits the slot, and the
5740/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5741/// `:entrada` block matches the per-`:contratos` destination Servico).
5742/// The single source of truth all three typed-port consumers reach for:
5743///
5744///   - [`Entrada::port`]'s serde default (via the
5745///     [`default_port`] helper this constant feeds); the author surface
5746///     `(:entrada (:host … :para …))` without an explicit `:port` slot
5747///     reads back as a typed [`Entrada`] carrying this exact value;
5748///   - the
5749///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5750///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5751///     fallback, fired when the typed `:entrada` block doesn't name
5752///     the per-`:contratos` destination Servico — the typed
5753///     `:contratos` graph carries no per-destination port axis (the
5754///     destination port is the destination Servico's
5755///     `lareira-<nome>` chart's `trigger.service.port`, which the
5756///     Aplicacao-level renderer has no visibility into without a
5757///     resolver round-trip), so the renderer falls back to the
5758///     substrate's canonical Servico-port assumption — by
5759///     construction the same value the destination's own
5760///     `pleme-computeunit` chart emits, the same value the
5761///     destination's own typed `:entrada :port` slot defaults to;
5762///   - every future per-Servico renderer the absorption-roadmap
5763///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5764///     CR materializer's per-edge port resolver, the future
5765///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5766///     emitter's per-route bucket key, the future caixa-otel
5767///     collector-pipeline emitter's per-Servico scrape port).
5768///
5769/// Until this lift landed the value `8080` lived at two production-code
5770/// call-sites: the [`default_port`] helper at
5771/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5772/// and the `.unwrap_or(8080)` literal at
5773/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5774/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5775/// resolver). A future Servico-port rebrand — the substrate moving the
5776/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5777/// gateway grows direct `:80` listeners, to `8443` once the substrate
5778/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5779/// override the operator pins through a future
5780/// `:placement :default-port` slot — without a coordinated edit on
5781/// both sides would silently emit Servicos listening on one port and
5782/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5783/// The CNP's apply-time symptom (the policy is admitted but every L4
5784/// flow on the destination Servico's actual port silently drops because
5785/// it doesn't match the whitelisted port) is far from the rebrand
5786/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5787/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5788/// a shared constant closes the drift footgun structurally — both
5789/// consumers read from the same `u16`, so any rebrand reaches both
5790/// sites by construction.
5791///
5792/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5793/// per-renderer canonical-K8s-axis constant — the namespace string
5794/// and the canonical Servico port both lived as duplicated literals
5795/// across caixa-core / caixa-mesh / caixa-flux before their respective
5796/// lifts. Same "the typed constant lives in one place" discipline the
5797/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5798/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5799/// shared-string axes.
5800///
5801/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5802pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5803
5804/// Structural floor for the typed `:entrada :port` axis — every
5805/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5806/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5807///
5808/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5809/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5810/// interprets as "let the kernel pick a free port at bind time", not a
5811/// well-defined destination the substrate's per-`:entrada` Gateway API
5812/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5813/// carrying `port: 0` degenerates to a nominal-only routing target: the
5814/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5815/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5816/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5817/// at build time rather than at `kubectl apply` time), and the
5818/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5819/// (caixa-mesh/src/lib.rs:2657 through
5820/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5821/// [`Entrada::port`] typed value — silently emits a policy whose
5822/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5823/// actual listener, dropping every L4 flow at the eBPF data plane far
5824/// from the source caixa.lisp with no field naming the port-zero-drift
5825/// root cause.
5826///
5827/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5828/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5829/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5830/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5831/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5832/// well below `u32::MAX` and therefore need explicit typed caps).
5833///
5834/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5835/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5836/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5837/// `:port` inherits through the serde default hook; this constant names
5838/// the accept-set floor every declared port must satisfy. The pair is
5839/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5840/// substrate's default must satisfy its own accept-set floor by
5841/// construction) — a future rebrand that accidentally moved
5842/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5843/// negative-cast typo, a per-cluster override the operator pins through
5844/// a future `:placement :default-port` slot that lands out-of-range)
5845/// would silently invalidate the serde-default emission at every
5846/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5847/// invariant pin
5848/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5849/// closes the drift footgun at caixa-core build time.
5850///
5851/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5852/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5853/// has exactly one source of truth — the future M4
5854/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5855/// gateway resolver, the future per-Servico
5856/// `computeunit.trigger.service.port` renderer's per-CR port-value
5857/// validator, and every downstream test-fixture navigator asserting
5858/// the accept-set floor all read from one place. Same shape every
5859/// other typed bracket-floor / bracket-ceiling in this crate carries
5860/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5861/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5862/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5863/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5864/// [`POLICY_RATE_LIMIT_MAX`]).
5865pub const SERVICO_PORT_MIN: u16 = 1;
5866
5867const fn default_port() -> u16 {
5868    DEFAULT_SERVICO_PORT
5869}
5870
5871// ── the typed view ───────────────────────────────────────────────────
5872
5873/// Typed composition view of the flat Aplicacao slots on
5874/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5875/// validation + downstream renderer consumption.
5876#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5877#[serde(rename_all = "camelCase")]
5878pub struct AplicacaoSpec {
5879    pub membros: Vec<Membro>,
5880    pub contratos: Vec<WitContract>,
5881    pub politicas: MeshPolicy,
5882    pub placement: Placement,
5883    pub entrada: Option<Entrada>,
5884}
5885
5886impl AplicacaoSpec {
5887    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5888    /// per-Aplicacao member-list slice-return accessor every
5889    /// per-Aplicacao member-list reader keys off — returns the author-
5890    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5891    /// over the same backing buffer the raw `self.membros.as_slice()`
5892    /// field access borrows from.
5893    ///
5894    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5895    /// member list — the load-bearing identity of the application graph
5896    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5897    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5898    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5899    /// accessor) with a `:versao` semver-requirement string (through
5900    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5901    /// and every downstream consumer that fans on the member-set keys
5902    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5903    /// membership-lookup `HashSet<&str>` seed's collect input, the
5904    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5905    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5906    /// per-member DNS-1123 / semver-requirement / duplicate-detection
5907    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5908    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5909    /// programs.yaml per-`:membros` fan-out emitter's per-entry
5910    /// mapping-composition loop, the `feira app graph` per-Aplicacao
5911    /// member-count print line and per-member tree traversal,
5912    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5913    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5914    /// placement engine's per-member weight-topology reader).
5915    ///
5916    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5917    /// inline at six production sites — the [`AplicacaoSpec::validate`]
5918    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5919    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5920    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5921    /// probe, the same method's per-member `for m in &self.membros`
5922    /// validate-loop traversal head, the
5923    /// [`AplicacaoSpec::detect_sync_cycles`]'s
5924    /// `for m in &self.membros` adjacency-list seed, the
5925    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5926    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5927    /// paired with the peer `for m in &spec.membros` per-entry fan-out
5928    /// loop, and the `feira app graph` per-Aplicacao print line's
5929    /// `spec.membros.len()` count formatter argument paired with the
5930    /// peer `for m in &spec.membros` per-member tree traversal — six
5931    /// open-coded field-accesses that expressed no compile-time link
5932    /// back to the typed slot. A future extension of the `:membros`
5933    /// axis to a richer author surface (a per-cluster member-set
5934    /// overlay the operator pins through a future
5935    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5936    /// roadmap acknowledges, a per-tenant member-alias table the M4
5937    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5938    /// CR at admission time, a per-Aplicacao dynamic member-set
5939    /// derivation the future adaptive-placement engine computes from
5940    /// weighted membership topology, a promotion of the plain
5941    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5942    /// Orleans-style virtual-actor dynamic-membership comes into typed
5943    /// scope) would have had to be threaded through all six open-coded
5944    /// copies in lockstep or one consumer would silently disagree with
5945    /// the peers on which member-set a given Aplicacao resolves to —
5946    /// the `HashSet<&str>` name-set seed reading the raw slot while
5947    /// the peer `.is_empty()` refusal probe read an operator-resolved
5948    /// slot would silently split the `:contratos` membership-lookup
5949    /// input from the pre-flight-refusal input, a six-consumer split
5950    /// at the validator + programs.yaml emitter + graph printer far
5951    /// from the source `caixa.lisp` with no field naming the member-
5952    /// set-drift root cause. Lifting the resolution rule to a typed
5953    /// method on the substrate primitive means every downstream
5954    /// consumer of the Aplicacao's per-`:membros` member-list surface
5955    /// reaches for exactly one typed dispatch — the resolver's accept-
5956    /// set migrates as a unit on any future axis addition.
5957    ///
5958    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5959    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5960    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5961    /// static-child-list `Vec`-carry axis, and to the M3
5962    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5963    /// on the peer per-`:placement` distribution-target-list `Vec`-
5964    /// carry axis. Same "one typed dispatch on the substrate primitive,
5965    /// thin projections at each consumer" discipline. The two peer
5966    /// `Vec`-carry axes still unlifted at the time of this lift —
5967    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5968    /// WIT-typed edge list) and
5969    /// [`crate::UpgradeFromEntry::instructions`]
5970    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5971    /// — inherit this accessor's discipline as future compounding runs
5972    /// migrate their consumers onto the shared slice-return shape.
5973    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5974    /// `AplicacaoSpec` type itself, extending the discipline beyond
5975    /// the inner per-slot types ([`crate::Placement`],
5976    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5977    /// view every renderer consumes. Named `membros()` to match the
5978    /// storage field's name verbatim and the tatara-lisp author-
5979    /// surface term (`:membros`) the field's own docstring already
5980    /// carries; the accessor's identity maps onto the canonical
5981    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5982    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5983    /// every downstream consumer of the member list treats it as a
5984    /// read-only sequence — the slice-view is the narrowest borrow
5985    /// that supports every present + roadmapped consumer
5986    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5987    /// backing `Vec`'s grow/push/reserve surface that no consumer of
5988    /// the typed view reaches for (the storage-side `Vec` remains
5989    /// reachable through the `pub membros` field for the mutation-
5990    /// carrying serde round-trip and per-test fixture-mutation paths).
5991    #[must_use]
5992    pub fn membros(&self) -> &[Membro] {
5993        self.membros.as_slice()
5994    }
5995
5996    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5997    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5998    /// accessor every per-Aplicacao contract-list reader keys off —
5999    /// returns the author-declared `:contratos` list verbatim as a
6000    /// `&[WitContract]` slice-view over the same backing buffer the raw
6001    /// `self.contratos.as_slice()` field access borrows from.
6002    ///
6003    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6004    /// WIT-typed edge list — the load-bearing set of directed edges
6005    /// on the application graph whose nodes are the `:membros` entries
6006    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6007    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6008    /// six-tuple is the edge identity every downstream duplicate gate
6009    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6010    /// Servico caller name + a `:para` destination-Servico callee name
6011    /// (through the lifted [`WitContract::source`] +
6012    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6013    /// caller/callee-Servico axis) with a `:wit` world-reference
6014    /// (through the lifted [`WitContract::world_ref`] (0804823)
6015    /// accessor) and the target-shape-appropriate payload-carrier
6016    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6017    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6018    /// (ed22b66) accessor on the per-target-shape payload-carrier
6019    /// axis). Every downstream consumer that fans on the edge-set
6020    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6021    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6022    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6023    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6024    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6025    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6026    /// count print line and per-contract tree traversal, every future
6027    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6028    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6029    /// mesh-policy overlay resolver's per-contract typed-edge weight
6030    /// reader).
6031    ///
6032    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6033    /// accessed inline at four production sites — the
6034    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6035    /// per-edge validate-loop traversal head (which drives every
6036    /// per-edge name-set membership lookup, self-edge check,
6037    /// target-shape dispatch, and dedup `HashSet` insert), the
6038    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6039    /// `for c in &self.contratos` adjacency-list seed head (which
6040    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6041    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6042    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6043    /// `BTreeMap` grouping loop head (which drives every per-CNP
6044    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6045    /// line's `spec.contratos.len()` count formatter argument paired
6046    /// with the peer `for c in &spec.contratos` per-contract tree
6047    /// traversal — four open-coded field-accesses that expressed no
6048    /// compile-time link back to the typed slot. A future extension
6049    /// of the `:contratos` axis to a richer author surface (a
6050    /// per-cluster contract overlay the operator pins through a
6051    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6052    /// federation roadmap acknowledges, a per-tenant edge-policy
6053    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6054    /// materializer resolves per-CR at admission time, a per-edge
6055    /// weight scalar the future adaptive-placement engine reads to
6056    /// bias sync-subgraph routing, a promotion of the plain
6057    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6058    /// once virtual-actor-style dynamic-edge composition comes into
6059    /// typed scope) would have had to be threaded through all four
6060    /// open-coded copies in lockstep or one consumer would silently
6061    /// disagree with the peers on which edge-set a given Aplicacao
6062    /// resolves to — the validator's per-edge dedup `HashSet` seed
6063    /// reading the raw slot while the peer sync-cycle adjacency-list
6064    /// seed read an operator-resolved slot would silently split the
6065    /// build-time edge-set gate from the runtime deadlock-detection
6066    /// gate, a four-consumer split at the validator, the cycle
6067    /// detector, the CNP emitter, and the graph printer far from
6068    /// the source `caixa.lisp` with no field naming the edge-set-
6069    /// drift root cause. Lifting the resolution rule to a typed method on the
6070    /// substrate primitive means every downstream consumer of the
6071    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6072    /// exactly one typed dispatch — the resolver's accept-set
6073    /// migrates as a unit on any future axis addition.
6074    ///
6075    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6076    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6077    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6078    /// static-child-list `Vec`-carry axis, to the M3
6079    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6080    /// on the peer per-`:placement` distribution-target-list `Vec`-
6081    /// carry axis, and to the immediately-adjacent sibling M3
6082    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6083    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6084    /// per-`:contratos` edge-list accessor is the natural pair of
6085    /// the per-`:membros` node-list accessor (graph edges over graph
6086    /// nodes; every graph-shaped consumer reads both). Same "one
6087    /// typed dispatch on the substrate primitive, thin projections
6088    /// at each consumer" discipline. The last remaining `Vec`-carry
6089    /// axis still unlifted at the time of this lift —
6090    /// [`crate::UpgradeFromEntry::instructions`]
6091    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6092    /// list) — inherits this accessor's discipline as future
6093    /// compounding runs migrate its consumers onto the shared slice-
6094    /// return shape. Second `&[T]`-return accessor on the top-level
6095    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6096    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6097    /// `:contratos` are the two `Vec` fields on the outer typed
6098    /// composition view — `:politicas`, `:placement`, `:entrada` are
6099    /// scalar/option-shaped and already route through their per-slot
6100    /// accessor families). Named `contratos()` to match the storage
6101    /// field's name verbatim and the tatara-lisp author-surface term
6102    /// (`:contratos`) the field's own docstring already carries; the
6103    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6104    /// §III.1 vocabulary the slot's docstring already reaches for.
6105    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6106    /// every downstream consumer of the contract list treats it as a
6107    /// read-only sequence — the slice-view is the narrowest borrow
6108    /// that supports every present + roadmapped consumer
6109    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6110    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6111    /// the typed view reaches for (the storage-side `Vec` remains
6112    /// reachable through the `pub contratos` field for the mutation-
6113    /// carrying serde round-trip and per-test fixture-mutation paths).
6114    #[must_use]
6115    pub fn contratos(&self) -> &[WitContract] {
6116        self.contratos.as_slice()
6117    }
6118
6119    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6120    /// per-Aplicacao mesh-policy composite-reference accessor every
6121    /// per-Aplicacao policy-block reader keys off — returns the author-
6122    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6123    /// reference over the same backing storage the raw `&self.politicas`
6124    /// field access borrows from.
6125    ///
6126    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6127    /// mesh-policy composite — the load-bearing container of every
6128    /// mesh-level operational-policy axis every downstream mesh-artifact
6129    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6130    /// mesh-policy overlay is the single typed surface a
6131    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6132    /// from). Every per-`:politicas` axis threads through a lifted
6133    /// per-slot accessor on the [`MeshPolicy`] type: the
6134    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6135    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6136    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6137    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6138    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6139    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6140    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6141    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6142    /// accessor. Every downstream consumer that reaches for a policy
6143    /// axis first passes through this outer accessor onto the composite
6144    /// and then dispatches onto the per-axis accessor — the two-level
6145    /// dispatch means every per-`:politicas` reader now routes through
6146    /// a typed dispatch on the substrate primitive at both altitudes.
6147    ///
6148    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6149    /// accessed inline at four production sites — the
6150    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6151    /// &self.politicas;` traversal seed (which drives every per-axis
6152    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6153    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6154    /// `p.rate_limit()` on the axis-level lifted accessors), the
6155    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6156    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6157    /// chain (which drives every per-`(:de, :para)` CNP
6158    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6159    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6160    /// timeout + retry overlay emitter's paired
6161    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6162    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6163    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6164    /// open-coded outer-field accesses that expressed no compile-time
6165    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6166    /// future extension of the `:politicas` outer axis to a richer
6167    /// author surface (a per-cluster policy overlay the operator pins
6168    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6169    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6170    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6171    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6172    /// policy-composite derivation the future adaptive-placement engine
6173    /// computes from a per-cluster load-topology reader, a promotion of
6174    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6175    /// partition once virtual-actor-style dynamic-mesh-policy
6176    /// composition comes into typed scope) would have had to be threaded
6177    /// through all four open-coded copies in lockstep or one consumer
6178    /// would silently disagree with the peers on which mesh-policy
6179    /// composite a given Aplicacao resolves to — the validator's
6180    /// per-axis bracket-dispatch seed reading the raw slot while the
6181    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6182    /// would silently split the build-time policy-shape gate from the
6183    /// runtime CNP-emission gate, a four-consumer split at the
6184    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6185    /// the source `caixa.lisp` with no field naming the policy-drift
6186    /// root cause. Lifting the resolution rule to a typed method on the
6187    /// substrate primitive means every downstream consumer of the
6188    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6189    /// reaches for exactly one typed dispatch — the resolver's accept-
6190    /// set migrates as a unit on any future axis addition.
6191    ///
6192    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6193    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6194    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6195    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6196    /// close the two `Vec`-carry axes on the outer typed composition
6197    /// view; the outer `:politicas` composite-reference axis is the
6198    /// natural pair to the paired outer `Vec`-carry accessors on the
6199    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6200    /// emitter reads all four axes as one unit (graph nodes + graph
6201    /// edges + mesh policy + placement pool). Peer to the same
6202    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6203    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6204    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6205    /// `restart_window`, `children`) already routes through the M2
6206    /// `SupervisorSpec` accessor family — this lift extends the same
6207    /// "one typed dispatch on the substrate primitive at the outer
6208    /// composition altitude" discipline to the M3 mesh-slot
6209    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6210    /// remaining peer outer-composite axes still unlifted at the time
6211    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6212    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6213    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6214    /// inherit this accessor's discipline as future compounding runs
6215    /// migrate their consumers onto the shared reference-return shape.
6216    /// Named `politicas()` to match the storage field's name verbatim
6217    /// and the tatara-lisp author-surface term (`:politicas`) the
6218    /// field's own docstring already carries; the accessor's identity
6219    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6220    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6221    /// (not the owning composite by copy or clone) because every
6222    /// downstream consumer of the mesh-policy composite treats it as a
6223    /// read-only per-axis dispatch source — the reference-view is the
6224    /// narrowest borrow that supports every present + roadmapped
6225    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6226    /// emptiness probe) without cloning the composite through every
6227    /// consumer's fast path.
6228    #[must_use]
6229    pub fn politicas(&self) -> &MeshPolicy {
6230        &self.politicas
6231    }
6232
6233    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6234    /// per-Aplicacao distribution-composite composite-reference accessor
6235    /// every per-Aplicacao placement-block reader keys off — returns the
6236    /// author-declared `:placement` composite verbatim as a `&Placement`
6237    /// reference over the same backing storage the raw `&self.placement`
6238    /// field access borrows from.
6239    ///
6240    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6241    /// distribution composite — the load-bearing container of every
6242    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6243    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6244    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6245    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6246    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6247    /// `:affinity` hint). Every per-`:placement` axis threads through a
6248    /// lifted per-slot accessor on the [`Placement`] type: the
6249    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6250    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6251    /// per-cluster distribution-target slice-return accessor, the
6252    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6253    /// optional-scalar accessor, and the [`Placement::shard_key`]
6254    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6255    /// downstream consumer that reaches for a placement axis first passes
6256    /// through this outer accessor onto the composite and then dispatches
6257    /// onto the per-axis accessor — the two-level dispatch means every
6258    /// per-`:placement` reader now routes through a typed dispatch on the
6259    /// substrate primitive at both altitudes.
6260    ///
6261    /// Prior to this lift the `.placement` `Placement` composite was
6262    /// accessed inline at three production sites — the
6263    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6264    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6265    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6266    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6267    /// cluster `.clusters()` validate-loop traversal head, the per-
6268    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6269    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6270    /// paired with the shape-gate cascade's `.shard_key()` /
6271    /// `.estrategia()` diagnostic-carry pair), the
6272    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6273    /// per-entry placement-block emitter's outer
6274    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6275    /// seed (which fans onto every per-cluster `programs[]` entry as a
6276    /// self-describing distribution overlay the aggregator filters by),
6277    /// and the `feira app graph` per-Aplicacao print line's paired
6278    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6279    /// then-inner-accessor chains (which drive the human-readable
6280    /// distribution summary of the typed Aplicacao view) — three open-
6281    /// coded outer-field accesses that expressed no compile-time link
6282    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6283    /// extension of the `:placement` outer axis to a richer author surface
6284    /// (a per-cluster placement overlay the operator pins through a
6285    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6286    /// federation roadmap acknowledges, a per-tenant placement-alias
6287    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6288    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6289    /// placement-composite derivation the future M5 adaptive-placement
6290    /// engine computes from a per-cluster load-topology reader, a
6291    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6292    /// partition once Orleans-style virtual-actor dynamic-placement comes
6293    /// into typed scope) would have had to be threaded through all three
6294    /// open-coded copies in lockstep or one consumer would silently
6295    /// disagree with the peers on which placement composite a given
6296    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6297    /// seed reading the raw slot while the peer
6298    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6299    /// would silently split the build-time distribution-shape gate from
6300    /// the runtime programs.yaml distribution-annotation gate, a three-
6301    /// consumer split at the validator, the programs.yaml emitter, and
6302    /// the `feira app graph` printer far from the source `caixa.lisp`
6303    /// with no field naming the placement-drift root cause. Lifting the
6304    /// resolution rule to a typed method on the substrate primitive
6305    /// means every downstream consumer of the Aplicacao's per-
6306    /// `:placement` distribution composite surface reaches for exactly
6307    /// one typed dispatch — the resolver's accept-set migrates as a unit
6308    /// on any future axis addition.
6309    ///
6310    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6311    /// `AplicacaoSpec` type itself — sibling to the seed
6312    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6313    /// composite-reference accessor on the peer per-`:politicas` outer-
6314    /// composite axis, and to the paired slice-return accessors
6315    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6316    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6317    /// the two `Vec`-carry axes on the outer typed composition view; the
6318    /// outer `:placement` composite-reference axis is the natural pair
6319    /// to the peer `:politicas` composite-reference axis on the two
6320    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6321    /// how-to-run policy overlay, `:placement` carries the where-to-run
6322    /// distribution composite — every whole-Aplicacao mesh-artifact
6323    /// emitter reads both as one unit). Same "one typed dispatch on the
6324    /// substrate primitive, thin projections at each consumer"
6325    /// discipline the peer per-`:politicas` composite-reference axis
6326    /// already routes through. The one remaining outer-composite axis
6327    /// still unlifted at the time of this lift —
6328    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6329    /// external-gateway composite) — inherits this accessor's discipline
6330    /// as the next compounding run migrates its consumers onto the shared
6331    /// reference-return shape, closing the outer-composite altitude on
6332    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6333    /// field's name verbatim and the tatara-lisp author-surface term
6334    /// (`:placement`) the field's own docstring already carries; the
6335    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6336    /// vocabulary the slot's docstring already reaches for. Returns
6337    /// `&Placement` (not the owning composite by copy or clone) because
6338    /// every downstream consumer of the placement composite treats it as
6339    /// a read-only per-axis dispatch source — the reference-view is the
6340    /// narrowest borrow that supports every present + roadmapped consumer
6341    /// (per-axis accessor dispatch, serde composite-serialization) without
6342    /// cloning the composite through every consumer's fast path.
6343    #[must_use]
6344    pub fn placement(&self) -> &Placement {
6345        &self.placement
6346    }
6347
6348    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6349    /// per-Aplicacao external-gateway composite optional-composite-
6350    /// reference accessor every per-Aplicacao gateway-block reader
6351    /// keys off — returns the author-declared `:entrada` composite
6352    /// verbatim as an `Option<&Entrada>` reference over the same
6353    /// backing storage the raw `self.entrada.as_ref()` field access
6354    /// borrows from, with `None` naming the internal-only mesh shape
6355    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6356    /// gateway_routes emitter treats as "emit nothing" and the peer
6357    /// `feira app graph` printer treats as "internal-only mesh").
6358    ///
6359    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6360    /// external-gateway composite — the load-bearing container of
6361    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6362    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6363    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6364    /// hostname axis, §III.4 for the `:para` destination-Servico
6365    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6366    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6367    /// axis threads through a lifted per-slot accessor on the
6368    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6369    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6370    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6371    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6372    /// backendRefs destination-Servico scalar accessor, the
6373    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6374    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6375    /// scalar accessor. Every downstream consumer that reaches for
6376    /// an entrada axis first passes through this outer accessor onto
6377    /// the composite and then dispatches onto the per-axis accessor
6378    /// — the two-level dispatch means every per-`:entrada` reader
6379    /// now routes through a typed dispatch on the substrate primitive
6380    /// at both altitudes.
6381    ///
6382    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6383    /// was accessed inline at four production sites — the
6384    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6385    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6386    /// (which drives every per-axis refusal on the composite: the
6387    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6388    /// `EntradaMemberMissing` membership lookup against the
6389    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6390    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6391    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6392    /// per-path shape gate on each entry of `e.paths`), the
6393    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6394    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6395    /// composite-projection seed (which drives the destination-
6396    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6397    /// backendRefs port emitter fans on), the
6398    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6399    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6400    /// early-return seed (which drives the "no `:entrada` ⇒ no
6401    /// external artifacts" partition on the whole-Aplicacao Gateway-
6402    /// API emitter's fan-out), and the `feira app graph` per-
6403    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6404    /// external-gateway summary emitter (which drives the human-
6405    /// readable `entrada: host → para (paths=…, port=…)` /
6406    /// `entrada: (internal-only mesh)` partition on the typed
6407    /// Aplicacao view) — four open-coded outer-field accesses that
6408    /// expressed no compile-time link back to the typed slot at the
6409    /// [`AplicacaoSpec`] altitude. A future extension of the
6410    /// `:entrada` outer axis to a richer author surface (a
6411    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6412    /// at admission time so an Aplicacao can expose a public-web +
6413    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6414    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6415    /// operator can pin a per-cluster hostname override without
6416    /// re-authoring the `caixa.lisp`, a promotion of the plain
6417    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6418    /// the multi-`:entrada` roadmap lands) would have had to be
6419    /// threaded through all four open-coded copies in lockstep or one
6420    /// consumer would silently disagree with the peers on which
6421    /// entrada composite a given Aplicacao resolves to — the
6422    /// validator's per-axis bracket-dispatch seed reading the raw
6423    /// slot while the peer `gateway_routes` emitter read an
6424    /// operator-resolved slot would silently split the build-time
6425    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6426    /// emission gate, a four-consumer split at the validator, the
6427    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6428    /// emitter, and the `feira app graph` printer far from the
6429    /// source `caixa.lisp` with no field naming the entrada-drift
6430    /// root cause. Lifting the resolution rule to a typed method on
6431    /// the substrate primitive means every downstream consumer of
6432    /// the Aplicacao's per-`:entrada` external-gateway composite
6433    /// surface reaches for exactly one typed dispatch — the
6434    /// resolver's accept-set migrates as a unit on any future axis
6435    /// addition.
6436    ///
6437    /// Third and final `&Composite`-return accessor on the top-level
6438    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6439    /// unlifted outer-composite axis on the outer typed composition
6440    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6441    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6442    /// accessor on the per-`:politicas` outer-composite axis and to
6443    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6444    /// distribution-composite composite-reference accessor on the
6445    /// per-`:placement` outer-composite axis; extends the outer-
6446    /// composite reference-return discipline the two peers already
6447    /// route through onto the last unlifted per-`AplicacaoSpec`
6448    /// outer-composite axis. The `:entrada` outer-composite axis is
6449    /// the natural pair to the two peer outer-composite axes on the
6450    /// three operationally-symmetric M3 mesh-slot outer composites
6451    /// (`:politicas` carries the how-to-run policy overlay,
6452    /// `:placement` carries the where-to-run distribution composite,
6453    /// `:entrada` carries the who-can-reach-it external-gateway
6454    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6455    /// all three as one unit). Same "one typed dispatch on the
6456    /// substrate primitive, thin projections at each consumer"
6457    /// discipline the peer outer-composite axes already route through.
6458    /// Named `entrada()` to match the storage field's name verbatim
6459    /// and the tatara-lisp author-surface term (`:entrada`) the
6460    /// field's own docstring already carries; the accessor's
6461    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6462    /// vocabulary the slot's docstring already reaches for. Returns
6463    /// `Option<&Entrada>` (not the owning composite by copy or
6464    /// clone) because every downstream consumer of the entrada
6465    /// composite treats it as a read-only per-axis dispatch source
6466    /// — the reference-view is the narrowest borrow that supports
6467    /// every present + roadmapped consumer (per-axis accessor
6468    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6469    /// port-fallback projection, early-return partition on the
6470    /// `None` arm) without cloning the composite through every
6471    /// consumer's fast path. The `Option` half of the return-type
6472    /// preserves the load-bearing "author-omitted `:entrada` ⇒
6473    /// internal-only mesh" partition (not a default composite the
6474    /// downstream must reject on emptiness) — the accessor projects
6475    /// the raw `Option<Entrada>` slot's presence bit through the
6476    /// reference-return unchanged.
6477    #[must_use]
6478    pub fn entrada(&self) -> Option<&Entrada> {
6479        self.entrada.as_ref()
6480    }
6481
6482    /// Validate the typed shape:
6483    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6484    ///     and a non-empty `:versao`; no two entries share the same
6485    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6486    ///     not a multiset)
6487    ///   - every `:contratos` :de + :para must be in `:membros`
6488    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6489    ///     contract is an inter-Servico edge, so a Servico contracting
6490    ///     with itself is a build error under every WIT shape
6491    ///     (MESH-COMPOSITION §III.1)
6492    ///   - no two `:contratos` entries agree on
6493    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6494    ///     edges are a set, not a multiset (peer of the `:membros` /
6495    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6496    ///   - `:entrada :para` must be in `:membros`
6497    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6498    ///     `:placement Replicated`/`SingleNode` must NOT declare
6499    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6500    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6501    ///     between strategy and shard-key is symmetric: every validated
6502    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6503    ///     Sharded`
6504    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6505    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6506    ///     the shard pool (MESH-COMPOSITION §III.1)
6507    ///   - every `:clusters` entry is non-empty and unique
6508    ///   - `:placement :affinity`, when set, is non-empty
6509    ///   - the synchronous-`:contratos` subgraph is acyclic
6510    ///     (MESH-COMPOSITION §III.3)
6511    ///   - every declared `:politicas` value is operationally meaningful
6512    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6513    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6514    ///     omit the field instead to express "no policy on this axis")
6515    pub fn validate(&self) -> Result<(), AplicacaoError> {
6516        self.validate_membros()?;
6517        let names: std::collections::HashSet<&str> =
6518            self.membros().iter().map(Membro::nome).collect();
6519
6520        // Identity key for the typed-edge duplicate gate below: every
6521        // field that distinguishes one contract from another. Two
6522        // entries that agree on all six are *the same edge declared
6523        // twice*, the typed-graph analogue of duplicate `:membros` /
6524        // `:placement :clusters` / `:entrada :paths` entries (which
6525        // are already build errors at this layer). Rejecting it at the
6526        // validate gate closes a renderer-side footgun: caixa-mesh's
6527        // `cilium_network_policies` keys each emitted policy by
6528        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6529        // (de, para) and identical payload would land as two K8s
6530        // objects with colliding `metadata.name`, rejected at apply
6531        // time far from the source caixa.lisp.
6532        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6533            std::collections::HashSet::new();
6534        for c in self.contratos() {
6535            // Per-axis value-shape gate on every `:contratos` name
6536            // reference, before any graph-membership lookup. Empty +
6537            // DNS-1123-malformed `:de`/`:para` values silently fell
6538            // through to `ContratoMemberMissing` at the lookup arm
6539            // because every `:membros :caixa` is shape-validated
6540            // (3f9d7a0), so the `names` set structurally cannot contain
6541            // an empty / malformed string and the membership-lookup
6542            // diagnostic always misframed the root cause as
6543            // "this caixa is not in `:membros`". The shape gate runs
6544            // ahead of the lookup so structurally-impossible-to-match
6545            // inputs route through the narrower self-locating
6546            // diagnostic, preserving the legitimate "well-shaped
6547            // phantom reference" arm. `:de` runs before `:para` per
6548            // the canonical edge-direction order the existing
6549            // membership lookup, self-edge check, target dispatch,
6550            // and diagnostic strings already use.
6551            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6552            // + the paired [`AplicacaoError::ContratoMemberMissing`]
6553            // diagnostic's `caixa:` carrier through the lifted
6554            // [`WitContract::source`] / [`WitContract::destination`]
6555            // scalar accessors rather than the raw `&c.de` / `&c.para`
6556            // `&String`-borrow arg site + the raw `c.de.clone()` /
6557            // `c.para.clone()` field-access `String`-carry sites — the
6558            // last unlifted per-`:contratos` raw-field-access sites in
6559            // the M3 mesh-slot validator's per-edge per-arm shape-gate
6560            // arg + phantom-name diagnostic wrap-envelope emit surface.
6561            // `c.source()` is byte-identical to `&c.de` (pinned by the
6562            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6563            // + `wit_contract_source_borrows_from_de_storage` accessor
6564            // tests) and `c.destination()` is byte-identical to `&c.para`
6565            // (pinned by the sibling
6566            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6567            // + `wit_contract_destination_borrows_from_para_storage`
6568            // accessor tests) — so a future rebrand of either underlying
6569            // storage flows through the accessor's one body without a
6570            // coordinated per-consumer rewrite across the M3 mesh
6571            // validator's per-edge shape-gate + phantom-name refusal
6572            // arms. Peer of the sibling per-`:contratos` self-loop
6573            // arm's `.source().to_string()` / `.world_ref().to_string()`
6574            // `String`-carry sites the earlier convergence lifted onto
6575            // the same accessor pair.
6576            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6577            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6578            if !names.contains(c.source()) {
6579                return Err(AplicacaoError::ContratoMemberMissing {
6580                    caixa: c.source().to_string(),
6581                });
6582            }
6583            if !names.contains(c.destination()) {
6584                return Err(AplicacaoError::ContratoMemberMissing {
6585                    caixa: c.destination().to_string(),
6586                });
6587            }
6588            // A `:contratos` entry is an *inter*-Servico contract
6589            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6590            // typed edge between two distinct graph nodes. An edge whose
6591            // `:de` equals its `:para` is a Servico contracting with
6592            // itself — a degenerate edge under every WIT shape. The
6593            // synchronous shapes were caught only incidentally, and with
6594            // a misleading diagnostic: `detect_sync_cycles` reported
6595            // `cart → cart` as a `ContratoCycle` whose path is
6596            // `["cart", "cart"]` — framing a self-edge as a multi-node
6597            // deadlock. The pub-sub shape slipped through entirely
6598            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6599            // `nats:pub-sub` edge from a member to itself silently
6600            // validated, then rendered a `CiliumNetworkPolicy` whose
6601            // endpointSelector and fromEndpoints both name the same
6602            // program — a self-allow rule that is a no-op, since
6603            // intra-pod traffic never traverses the mesh). A self-edge's
6604            // runtime meaning is an in-process call, which doesn't go
6605            // through the mesh at all, so no `:contratos` edge can carry
6606            // it. Firing the gate before the `:wit`/`target()` shape
6607            // checks means the structural "this edge can't exist" error
6608            // precedes the narrower payload-shape diagnostics, and shape-
6609            // agnostically covers all four `WitTarget` arms (HTTP / Store
6610            // / Capability / PubSub) at one point — closing the pub-sub
6611            // hole and replacing the misleading cycle diagnostic in one
6612            // gate. Peer of the duplicate-`:contratos` / duplicate-
6613            // `:membros` set gates: both reject a structurally
6614            // ill-formed graph at the typed surface, before the renderer
6615            // emits a K8s object that fails or no-ops far from the source
6616            // caixa.lisp.
6617            // Route the per-`:contratos` structural self-edge probe
6618            // through the lifted [`WitContract::is_self_loop`] typed
6619            // predicate rather than the raw `c.de == c.para` field-
6620            // equality check — the one production consumer of the per-
6621            // `:contratos` caller-equals-callee endpoint-equality axis
6622            // now keys off exactly one typed dispatch on the substrate
6623            // primitive, so any future rebrand of the axis (an M4-typed-
6624            // caller enum whose identity comparison rule the predicate
6625            // could route through, a per-cluster caller/callee-alias
6626            // table the M4 CR materializer resolves per-CR before the
6627            // equality probe) migrates as a single caixa-core edit
6628            // rather than a coordinated rewrite of the gate + every
6629            // downstream self-edge consumer. Peer of the sibling
6630            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6631            // [`WitContract::is_store`] shape-predicate routing on the
6632            // `:wit` world-ref axis, extended onto the per-edge
6633            // endpoint-equality axis.
6634            //
6635            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6636            // diagnostic's `caixa:` / `wit:` carriers through the
6637            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6638            // scalar accessors rather than the raw `c.de.clone()` /
6639            // `c.wit.clone()` field-access `String`-carry sites — the
6640            // last unlifted per-`:contratos` raw-field-access
6641            // `.clone()` sites in the M3 mesh-slot validator's self-
6642            // edge refusal arm. `.source().to_string()` is byte-
6643            // identical to `.de.clone()` (pinned by the sibling
6644            // `source_returns_de_byte_equal_across_permutations` accessor
6645            // test), and `.world_ref().to_string()` is byte-identical
6646            // to `.wit.clone()` (pinned by the sibling
6647            // `world_ref_returns_wit_byte_equal_across_permutations`
6648            // accessor test) — so a future rebrand of either underlying
6649            // storage flows through the accessor's one body without a
6650            // coordinated per-consumer rewrite across the M3 mesh
6651            // validator.
6652            if c.is_self_loop() {
6653                return Err(AplicacaoError::ContratoSelfLoop {
6654                    caixa: c.source().to_string(),
6655                    wit: c.world_ref().to_string(),
6656                });
6657            }
6658            if c.world_ref().is_empty() {
6659                let (de, para) = c.edge_pair();
6660                return Err(AplicacaoError::EmptyWit { de, para });
6661            }
6662            // Shape ↔ target consistency — surfaces "HTTP wit without
6663            // :endpoint", "NATS wit with :endpoint set", etc. as named
6664            // build errors instead of silent renderer drops. Threaded
6665            // through the duplicate-edge diagnostic below (via
6666            // [`WitTarget::label`]) so the "which typed target arm did
6667            // the duplicate carry" question is answered by the typed
6668            // enum's variant discriminator, not by re-probing the raw
6669            // `Option<String>` payload fields.
6670            let target_view = c.target()?;
6671            // Contract identity: (de, para, wit, endpoint, subject, slot).
6672            // Two contracts that match on all six are the same typed edge
6673            // declared twice — author error, not a legitimate variant of
6674            // "same caller-callee pair, different payload" (e.g.
6675            // cart→catalog at /products vs /search), which keeps distinct
6676            // identity keys via the differing endpoint payloads.
6677            //
6678            // Route the six-axis dedup key through the lifted
6679            // [`WitContract::identity`] composite-projection accessor
6680            // rather than the inline six-tuple builder — the two
6681            // substrate primitives on the per-`:contratos` identity axis
6682            // (the [`ContratoIdentity`] type alias's six axes, this
6683            // dedup-key's six tuple arms) now migrate as a unit on any
6684            // future axis addition. Peer of the sibling per-`:contratos`
6685            // composite-projection [`WitContract::edge_pair`] /
6686            // [`WitContract::edge_triple`] accessors on the
6687            // caller-callee / caller-callee-wit prefix axes; extends
6688            // the discipline onto the full-identity axis that carries
6689            // the three payload-shape arms too.
6690            let key = c.identity();
6691            crate::render::insert_first_seen(&mut seen_contracts, key, || {
6692                // Route the per-`:contratos` duplicate-gate diagnostic's
6693                // `(de, para, wit)` triple through the lifted
6694                // [`WitContract::edge_triple`] typed accessor rather
6695                // than pairing `edge_pair()` for the `(de, para)` prefix
6696                // with a raw `c.wit.clone()` for the `wit:` tail — the
6697                // paired-with-raw-field-access shape was the last
6698                // per-`:contratos` diagnostic constructor bypassing the
6699                // substrate-primitive composite projection, sibling to
6700                // the eight [`AplicacaoError::Contrato*`] triple-
6701                // carrying constructors [`WitContract::target`]'s edge
6702                // closure feeds through the same accessor.
6703                let (de, para, wit) = c.edge_triple();
6704                AplicacaoError::ContratoDuplicate {
6705                    de,
6706                    para,
6707                    wit,
6708                    target: target_view.label(),
6709                }
6710            })?;
6711        }
6712
6713        // Cycles in the synchronous-edge subgraph are build errors
6714        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6715        // are "acyclic by construction" because the publisher fires
6716        // and forgets, so no caller blocks on a downstream that loops
6717        // back to it.
6718        self.detect_sync_cycles()?;
6719
6720        if let Some(e) = self.entrada() {
6721            // Route the per-`:entrada` composite-reference read
6722            // through the lifted [`AplicacaoSpec::entrada`] accessor
6723            // rather than the raw `&self.entrada` field access — the
6724            // shape-and-membership gate's traversal head is now the
6725            // canonical read-side surface every per-Aplicacao entrada
6726            // consumer routes through, closing the fourth of four
6727            // open-coded outer-field accesses on the per-`:entrada`
6728            // outer-composite axis.
6729            //
6730            // Shape gate on `:entrada :para` runs ahead of the
6731            // membership lookup. Every `:membros :caixa` past
6732            // `validate_membro_caixa` is a valid DNS-1123 label
6733            // (3f9d7a0), so the `names` set structurally cannot
6734            // contain an empty / malformed string and the membership-
6735            // lookup diagnostic always misframed the root cause as
6736            // "this caixa is not in `:membros`". The shape gate
6737            // routes structurally-impossible-to-match inputs through
6738            // the narrower self-locating diagnostic, preserving the
6739            // legitimate "well-shaped phantom reference" arm — the
6740            // same trajectory the peer `:membros :caixa` (3f9d7a0),
6741            // `:placement :clusters` (6c8c00b), and `:contratos :de`
6742            // / `:para` (8d5af6b) axes already follow. This closes
6743            // the fourth and last Aplicacao-level Servico-name
6744            // reference axis on the canonical DNS-1123 floor.
6745            // Route the per-`:entrada :para` byte-string reads through
6746            // the lifted [`Entrada::destination`] accessor rather than
6747            // the raw `e.para` field access — the three
6748            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6749            // (shape-gate `validate_entrada_para` arg, membership
6750            // lookup, `EntradaMemberMissing` diagnostic carry) now key
6751            // off exactly one typed dispatch on the substrate
6752            // primitive, closing the last unlifted per-`:entrada :para`
6753            // raw-field-access axis on the M3 mesh-slot validator.
6754            // The `.destination().to_string()` at the diagnostic site
6755            // is byte-identical to `.para.clone()` — pinned by the
6756            // sibling `destination_returns_entrada_para_byte_equal` +
6757            // `destination_borrows_from_entrada_para_storage` accessor
6758            // tests — so a future rebrand of the underlying `:para`
6759            // storage (a lift from `String` to a typed
6760            // `ServicoName(String)` newtype, a per-Aplicacao interning
6761            // arena the M4 CR materializer authors, a
6762            // `smol_str::SmolStr` inline-buffer swap) flows through
6763            // the accessor's one body without a coordinated
6764            // per-consumer rewrite across the M3 mesh validator.
6765            validate_entrada_para(e.destination())?;
6766            if !names.contains(e.destination()) {
6767                return Err(AplicacaoError::EntradaMemberMissing {
6768                    para: e.destination().to_string(),
6769                });
6770            }
6771            // Route the per-`:entrada :host` byte-string reads through
6772            // the lifted [`Entrada::hostname`] accessor rather than
6773            // the raw `e.host` field access — the emptiness gate and
6774            // the shape-gate `validate_entrada_host` arg now key off
6775            // exactly one typed dispatch on the substrate primitive,
6776            // closing the last unlifted per-`:entrada :host` raw-
6777            // field-access axis on the M3 mesh-slot validator. Peer
6778            // of the sibling per-`:entrada :para` convergence above
6779            // and pinned by the existing
6780            // `hostname_returns_entrada_host_byte_equal` +
6781            // `hostnames_returns_singleton_of_hostname_accessor`
6782            // accessor tests, so any future
6783            // Gateway-API-shaped host renormalization (a wildcard-
6784            // label lift, a trailing-`.` FQDN substitution, an IDNA
6785            // Punycode round-trip the SNI fan-out overlay authors)
6786            // flows through the accessor's one body without a
6787            // coordinated per-consumer rewrite across the M3 mesh
6788            // validator.
6789            if e.hostname().is_empty() {
6790                return Err(AplicacaoError::EmptyEntradaHost);
6791            }
6792            // The `:host` lands verbatim as a K8s Gateway API v1
6793            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6794            // both apiserver-validated against the same restrictive
6795            // pattern: lowercase RFC 1123 DNS subdomain, optional
6796            // single leading wildcard label (`*.`), max length 253,
6797            // per-label max length 63, no IP literals, no scheme,
6798            // no port. Until this gate landed `validate()` only
6799            // refused the empty string (`EmptyEntradaHost`); a
6800            // structurally invalid hostname (`"https://example.com"`,
6801            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6802            // `"_underscored.example.com"`, `"FOO.example.com"`,
6803            // `"checkout.quero.cloud."`) silently passed validate
6804            // and the apiserver `field is invalid` error surfaced at
6805            // `kubectl apply` time, far from the source caixa.lisp.
6806            // Lifting the gate to caixa-build time mirrors the
6807            // `:entrada :paths` value-shape trajectory (eb3456d) and
6808            // closes the last unstructured `:entrada` axis.
6809            validate_entrada_host(e.hostname())?;
6810            // Structural-floor gate on `:entrada :port`: every
6811            // validated `Entrada::port` past this gate lies in
6812            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6813            // type-inferred ceiling closes the top edge, so no companion
6814            // upper-cap arm is needed here — unlike the peer capped-
6815            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6816            // `require_positive_bounded_u32` bracket covers both edges).
6817            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6818            // accept-set-floor const rather than the prior inline
6819            // `if e.port == 0` byte-check so a future rebrand of the
6820            // accept-set floor (a hypothetical unprivileged-only
6821            // migration lifting the floor to `1024`, a per-cluster
6822            // scoping the operator pins through a future
6823            // `:placement :port-floor` slot as the M4 typed-slot
6824            // trajectory adds it, the future
6825            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6826            // per-Aplicacao gateway resolver reaching for the same
6827            // floor) is a one-line edit on the canonical
6828            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6829            // rewrite across the emit site + the pin test + every
6830            // future per-target renderer the substrate adds.
6831            if e.port() < SERVICO_PORT_MIN {
6832                return Err(AplicacaoError::EntradaPortZero);
6833            }
6834            // Each `:entrada :paths` entry becomes a K8s Gateway API
6835            // HTTPRoute `matches[].path.value`. The Gateway API rejects
6836            // values that don't start with `/` for `type: PathPrefix`,
6837            // and an empty value is meaningless. Surface those as build
6838            // errors (MESH-COMPOSITION §III.3) rather than apply-time
6839            // failures. Empty `:paths` itself is fine — caixa-mesh
6840            // falls back to a single `/` catch-all.
6841            let mut seen = std::collections::HashSet::new();
6842            // Route the per-entry value-shape gate's traversal head
6843            // through the lifted [`Entrada::paths`] slice accessor
6844            // rather than the raw `&e.paths` field access — the
6845            // per-Aplicacao `:entrada :paths` validate loop now keys
6846            // off the canonical raw-slot surface every downstream
6847            // per-`:entrada` path-list consumer (the sibling
6848            // [`Entrada::resolved_paths`] fallback-applying resolver
6849            // internal reads, `feira app graph`'s per-Aplicacao entrada
6850            // summary line's `{:?}` Debug print) routes through, so any
6851            // future rebrand on the typed slot's raw-slot reader lands
6852            // at exactly one place. Same convergence discipline as the
6853            // sibling [`Placement::clusters`] (a6e18d7) reader-site
6854            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6855            // axis.
6856            for p in e.paths() {
6857                if p.is_empty() {
6858                    return Err(AplicacaoError::EntradaPathEmpty);
6859                }
6860                if !p.starts_with('/') {
6861                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6862                }
6863                // Per-entry value-shape gate: the path lands verbatim
6864                // as a K8s Gateway API HTTPRoute `matches[].path.value`
6865                // (caixa-mesh/src/lib.rs:498), apiserver-validated
6866                // against `maxLength: 1024` + the Gateway API webhook's
6867                // path-grammar rules (no `//`, no `/./`, no `/../`, no
6868                // query/fragment separators, no whitespace, no control
6869                // characters, no non-ASCII bytes). Until this gate
6870                // landed `validate` only refused the empty string and
6871                // missing-leading-slash (eb3456d); a structurally
6872                // invalid path (`"/api?q=1"`, `"/api#frag"`,
6873                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6874                // 1025-byte URL-shaped slug) silently passed validate
6875                // and the failure surfaced at `kubectl apply` time as
6876                // a Gateway API webhook rejection, far from the source
6877                // caixa.lisp, with no field naming the offending
6878                // `:paths` entry. Lifting the gate to caixa-build time
6879                // mirrors the `:entrada :host` value-shape trajectory
6880                // (c7d05ec) on the sibling axis — every author surface
6881                // that emits a Gateway API field now matches the
6882                // apiserver's accepted set at validate time.
6883                validate_entrada_path(p)?;
6884                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6885                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6886                })?;
6887            }
6888        }
6889
6890        self.validate_placement()?;
6891
6892        self.validate_politicas()?;
6893
6894        Ok(())
6895    }
6896
6897    /// Reject `:membros` values that are operationally meaningless. The
6898    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6899    /// every entry names a Servico that participates in the Aplicacao,
6900    /// and the rendered programs.yaml fan-out emits one entry per
6901    /// `:membros`. Three authoring footguns are closed here:
6902    ///
6903    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6904    ///     a `programs:` entry whose `name:` is the empty string, which
6905    ///     downstream `lareira-fleet-programs` rejects at template time
6906    ///     with a non-localized error;
6907    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6908    ///     an empty semver constraint, so the failure surfaces far from
6909    ///     the source caixa.lisp;
6910    ///   - duplicate `:caixa` names — two entries with the same name
6911    ///     produce duplicate programs.yaml entries (one silently
6912    ///     overwrites the other in the cluster's HelmRelease values), and
6913    ///     contract membership lookups against `:contratos` collapse the
6914    ///     two onto one node, masking authoring mistakes.
6915    ///
6916    /// Same value-shape discipline as `:placement :clusters` (where empty
6917    /// + duplicate cluster names are rejected) and `:entrada :paths`
6918    /// (where empty + duplicate path entries are rejected). Lifting these
6919    /// invariants to the typed surface mirrors the MESH-COMPOSITION
6920    /// §III.3 promise that the `:membros` set — the load-bearing identity
6921    /// of the application graph — is well-formed by construction.
6922    fn validate_membros(&self) -> Result<(), AplicacaoError> {
6923        if self.membros().is_empty() {
6924            return Err(AplicacaoError::NoMembros);
6925        }
6926        let mut seen = std::collections::HashSet::new();
6927        for m in self.membros() {
6928            // Route the `MembroCaixaEmpty` refusal-arm's per-member
6929            // empty-`:caixa` shape-gate through the typed
6930            // [`Membro::nome`] accessor rather than the raw `.caixa`
6931            // field access — the last un-lifted `.caixa` production-
6932            // code read site on the per-`:membros` member-caixa `:nome`
6933            // axis, sibling to the six caixa-core validator read sites
6934            // (member-set collector, per-member value-shape gate,
6935            // duplicate dedup key, cycle-detector adjacency-map seed,
6936            // self-loop gate) the 4a32abf lift already routed through
6937            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6938            // per-`programs[]` entry-`name:` `String`-carry converge.
6939            // Prior to this converge the `MembroCaixaEmpty` refusal
6940            // arm was the solitary consumer bypassing the typed
6941            // dispatch — the same-loop iteration's very next call
6942            // `validate_membro_caixa(m.nome())` already routed through
6943            // the accessor, so an author landing an empty-`:caixa`
6944            // entry hit the accessor on the shape-gate line but
6945            // bypassed it on the emptiness line one line above. A
6946            // future extension of the `:membros :caixa` axis to a
6947            // richer author surface (a per-cluster alias table pinned
6948            // through a future `:placement`-scoped slot, a namespace-
6949            // qualified rewrite the M4 CR materializer applies per-CR,
6950            // a per-member overlay from the future `:membros
6951            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6952            // that lands on the accessor would silently disagree
6953            // between the emptiness gate and every peer consumer —
6954            // an author-declared `:caixa "checkout"` value the
6955            // accessor rewrote to `""` under a future alias arm would
6956            // pass the raw `.is_empty()` gate here while the peer
6957            // `validate_membro_caixa(m.nome())` call one line below
6958            // (and every downstream emit-side consumer routing through
6959            // the accessor) tripped on the empty-value shape far from
6960            // this diagnostic. Pinned by the drift-detection test
6961            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6962            // below.
6963            if m.nome().is_empty() {
6964                return Err(AplicacaoError::MembroCaixaEmpty);
6965            }
6966            // Every emitted cluster artifact's `metadata.name` derives
6967            // from a `:membros :caixa` value verbatim — the rendered
6968            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6969            // the [`crate::LABEL_PROGRAM`] label value on every CNP
6970            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6971            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6972            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6973            // `metadata.name` when the member is the `:entrada :para`
6974            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6975            // schema enforces the DNS-1123 label rule on admission;
6976            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6977            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6978            // mistaken-identity slug) silently passes the prior empty-/
6979            // duplicate-only gate and the failure surfaces at `kubectl
6980            // apply` time as a `metadata.name: Invalid value` rejection,
6981            // far from the source caixa.lisp, with no field naming the
6982            // offending `:membros` entry. Lifting the gate to caixa-build
6983            // time mirrors the `:entrada :host` value-shape trajectory
6984            // (c7d05ec) on the peer axis — every author surface that
6985            // emits a K8s name now matches the apiserver's accepted set
6986            // at validate time.
6987            validate_membro_caixa(m.nome())?;
6988            // The author surface for `:versao` is the same Cargo-shaped
6989            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6990            // `"*"`) every `:deps` entry carries — and the lacre pipeline
6991            // resolves both axes through the same
6992            // [`crate::version::parse_requirement`] entry-point. The
6993            // shared [`crate::render::require_valid_versao_requirement`]
6994            // helper brackets the empty-first + parse cascade both peer
6995            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6996            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6997            // route through, so drift between the three axes' accepted
6998            // requirement sets is structurally impossible and the parse-
6999            // side no-op the empty-first arm closes (semver's empty
7000            // parse yields an implicit `*`) lives in exactly one
7001            // predicate.
7002            crate::render::require_valid_versao_requirement(
7003                m.versao_requirement(),
7004                || AplicacaoError::MembroVersaoEmpty {
7005                    caixa: m.nome().to_string(),
7006                },
7007                |reason| AplicacaoError::MembroVersaoInvalid {
7008                    caixa: m.nome().to_string(),
7009                    versao: m.versao_requirement().to_string(),
7010                    reason,
7011                },
7012            )?;
7013            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7014                AplicacaoError::MembroDuplicate {
7015                    caixa: m.nome().to_string(),
7016                }
7017            })?;
7018        }
7019        Ok(())
7020    }
7021
7022    /// Reject `:placement` values that are operationally meaningless or
7023    /// internally contradictory. Each strategy variant has the same
7024    /// invariants on `:clusters` (non-empty list, non-empty unique
7025    /// entries) — the §III.1 author surface is uniform on this axis,
7026    /// even though the *meaning* of the list differs by strategy
7027    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7028    /// shard pool).
7029    ///
7030    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7031    /// are the same authoring footgun closed for `:politicas` zero
7032    /// values and `:entrada` empty paths: the field is *declared* but
7033    /// carries no meaning, so downstream renderers either skip it
7034    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7035    /// or apply it literally and fail at admission time. Lifting both
7036    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7037    /// violation is a build error" promise.
7038    ///
7039    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7040    /// is required exactly when `:estrategia Sharded` (hash-keyed
7041    /// distribution, Akka cluster-sharding convention, §II.4) and
7042    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7043    /// hash-keyed routing axis consumes it). The partition closes the
7044    /// "I think I configured sharding" footgun where an author writes
7045    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7046    /// the typed slot's value silently vanishes at the renderer layer
7047    /// — every validated `Placement` past this call satisfies
7048    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7049    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7050        // Every strategy needs at least one named cluster: `Replicated`
7051        // and `SingleNode` use the list as hosting/takeover candidates
7052        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7053        // §II.1), while `Sharded` uses it as the shard pool
7054        // (Akka cluster-sharding convention — §II.4). An empty list is
7055        // meaningless under any of the three.
7056        //
7057        // Route the paired pre-flight `.is_empty()` refusal probe and
7058        // the per-cluster validate loop's traversal head through the
7059        // lifted [`Placement::clusters`] slice-return accessor rather
7060        // than the raw `self.placement.clusters` field access — the
7061        // two production consumers of the per-`:placement` cluster-
7062        // pool `Vec`-carry now key off exactly one typed dispatch on
7063        // the substrate primitive, so any future rebrand on the axis
7064        // (a per-tenant cluster-pool overlay the operator pins through
7065        // a future `:placement :clusters-overrides` slot, a per-
7066        // Aplicacao dynamic cluster-pool derivation the future M5
7067        // adaptive-placement engine computes from `:affinity` weights)
7068        // migrates as a single caixa-core edit rather than a
7069        // coordinated rewrite of the paired arms — sibling of the
7070        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7071        // arm migration on the per-`:supervisor` static-child-list
7072        // `Vec`-carry axis.
7073        //
7074        // Route the per-`:placement` outer-composite reference read
7075        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7076        // rather than the raw `&self.placement` field access — the
7077        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7078        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7079        // axis-level lifted accessor family) now routes through the
7080        // substrate-primitive typed dispatch at the outer composition
7081        // altitude, the same shape the peer caixa-mesh
7082        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7083        // and the sibling `feira app graph` per-Aplicacao print line
7084        // now key off after this accessor lift.
7085        let p = self.placement();
7086        if p.clusters().is_empty() {
7087            return Err(AplicacaoError::PlacementWithoutClusters {
7088                estrategia: p.estrategia(),
7089            });
7090        }
7091        let mut seen = std::collections::HashSet::new();
7092        for c in p.clusters() {
7093            // Per-entry value-shape gate: the cluster name lands in
7094            // every K8s context / `lareira-fleet-programs` aggregator
7095            // filter / future M4 CR materializer's per-cluster axis
7096            // a validated `:clusters` entry passes through, each
7097            // enforcing the DNS-1123 label rule on admission. Same
7098            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7099            // on the peer name axis — both axes' validated values
7100            // are guaranteed-accepted by the apiserver without
7101            // re-validation at any downstream renderer or admission
7102            // layer.
7103            validate_placement_cluster(c)?;
7104            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7105                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7106            })?;
7107        }
7108        // Route the per-`:placement :affinity` per-hint value-shape
7109        // gate through the typed [`Placement::affinity`] accessor rather
7110        // than the raw `&self.placement.affinity` field access — the
7111        // sole open-coded field-access site on the per-`:placement`
7112        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7113        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7114        // the accessor's `Option<&str>` return type;
7115        // [`validate_placement_affinity`]'s `&str` parameter accepts
7116        // the narrower borrow without a re-allocation, so the routing
7117        // change is byte-for-byte in the pass arm and remains
7118        // byte-for-byte in every failure diagnostic
7119        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7120        // String` field is populated inside
7121        // [`validate_placement_affinity`] via the peer `.to_string()`
7122        // path on the same borrowed slice). Peer of the sibling
7123        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7124        // routing through [`Placement::shard_key`] at the caixa-core
7125        // site above — extends the "read `:placement` optional-scalars
7126        // through the typed accessor" discipline to the second
7127        // `Option<String>`-shape slot on the M3 mesh-slot family.
7128        //
7129        // Per-hint value-shape gate: the `:affinity` value lands
7130        // verbatim in the M3 Adaptive compression overlay
7131        // (caixa-mesh's `placement.affinity` emission) and every
7132        // future M4 placement-engine routing axis keying off the
7133        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7134        // selector — each enforces the DNS-1123 label rule on
7135        // admission. Same typed-shape trajectory as `:placement
7136        // :clusters` (6c8c00b) on the sibling slot and the four
7137        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7138        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7139        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7140        // on the Aplicacao surface to land on the canonical
7141        // [`crate::render::is_dns_1123_label`] floor.
7142        if let Some(a) = p.affinity() {
7143            validate_placement_affinity(a)?;
7144        }
7145        match p.estrategia() {
7146            // Route the `Sharded`-arm shape-gate cascade through the
7147            // typed [`Placement::shard_key`] accessor rather than the
7148            // raw `&self.placement.shard_key` field access — one of the
7149            // two open-coded field-access sites on the per-`:placement`
7150            // Akka-cluster-sharding-key axis the accessor lift now
7151            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7152            // `&str` under the accessor's `Option<&str>` return type;
7153            // `str::is_empty` and [`validate_placement_shard_key`]'s
7154            // `&str` parameter both accept the narrower borrow without
7155            // a re-allocation.
7156            PlacementStrategy::Sharded => match p.shard_key() {
7157                None => return Err(AplicacaoError::ShardedWithoutKey),
7158                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7159                // Per-axis value-shape gate on the Akka-cluster-sharding
7160                // `:shard-key` extractor expression. The shape gate runs
7161                // after the more self-locating `ShardedKeyEmpty` arm so
7162                // a `:shard-key ""` surfaces the narrower empty
7163                // diagnostic first; every non-empty `:shard-key` past
7164                // this call is guaranteed to be a printable-ASCII
7165                // single-token reference the future M4 Akka-style
7166                // cluster-sharding reconciler can hash without
7167                // re-validating at the runtime layer. Mirrors the
7168                // payload-axis shape gates on the peer `:contratos`
7169                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7170                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7171                // intersection-floor to a caixa-build-time gate.
7172                Some(k) => validate_placement_shard_key(k)?,
7173            },
7174            // `:shard-key` is the Akka-cluster-sharding axis
7175            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7176            // across the cluster pool. `Replicated` (active-active across
7177            // every named cluster) and `SingleNode` (Erlang/OTP
7178            // distributed-app takeover/failover, §II.1) have no hash-keyed
7179            // routing axis to consume the slot; downstream renderers
7180            // (caixa-mesh's `placement.shardKey` overlay at
7181            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7182            // sharding reconciler) ignore `:shard-key` outside the
7183            // `Sharded` arm by construction. Until this gate landed an
7184            // author who wrote `:placement (:estrategia Replicated
7185            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7186            // copy-paste from a Sharded sibling caixa, the "I think I
7187            // configured sharding" footgun) silently passed validate and
7188            // the typed slot's value vanished at the renderer layer with
7189            // no diagnostic — the canonical "declared-but-inert" footgun
7190            // the empty-:affinity / empty-shard-key / zero-:politicas /
7191            // empty-:contratos-target gates already close on every other
7192            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7193            // Lifting the rejection to a build-time gate closes the
7194            // Sharded ↔ non-Sharded partition over the typed
7195            // `:placement` slot: every validated `Placement` past this
7196            // call has `shard_key.is_some()` iff `estrategia ==
7197            // Sharded`, structurally — the future Akka reconciler can
7198            // reach for `placement.shard_key` knowing it's `Some` exactly
7199            // when the strategy consumes it, without re-deriving the
7200            // partition from inline strategy probes.
7201            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7202                // Route the non-`Sharded`-arm declared-but-inert refusal
7203                // through the typed [`Placement::shard_key`] accessor —
7204                // the second of the two open-coded field-access sites the
7205                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7206                // from `&String` to `&str`; the `AplicacaoError::
7207                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7208                // materializes the owned `String` via `k.to_string()`
7209                // (peer to the sibling per-Membro `String`-carry sites
7210                // 4127bb6 routed through `m.nome().to_string()` /
7211                // `m.versao_requirement().to_string()`), so the whole
7212                // `Sharded` ↔ non-`Sharded` partition on the
7213                // `:shard-key` axis now flows through the same typed
7214                // dispatch as the sibling `Sharded`-arm shape gate.
7215                if let Some(k) = p.shard_key() {
7216                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7217                        estrategia: p.estrategia(),
7218                        shard_key: k.to_string(),
7219                    });
7220                }
7221            }
7222        }
7223        Ok(())
7224    }
7225
7226    /// Reject `:politicas` values that are operationally meaningless.
7227    /// Each axis is optional — omitting it expresses "no policy on this
7228    /// axis". Carrying a *zero* value for a declared axis is the bug
7229    /// this function rejects: zero is either
7230    ///
7231    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7232    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7233    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7234    ///     "every Aplicacao declares :politicas :timeout (no infinite
7235    ///     blocking)", or
7236    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7237    ///     first call; a 0-rate rate-limit denies every request).
7238    ///
7239    /// Lifting these "0 means the opposite of what you think" idioms to
7240    /// the typed Aplicacao surface as build errors mirrors the §III.3
7241    /// promise that contract drift, capability leaks, and cycles are all
7242    /// build errors — not runtime surprises.
7243    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7244        // Route the per-`:politicas` composite-reference read through
7245        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7246        // than the raw `&self.politicas` field access — the per-axis
7247        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7248        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7249        // the substrate-primitive typed dispatch at the outer
7250        // composition altitude AND at every per-axis altitude, matching
7251        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7252        // timeout/retry-overlay emitters that already key off the same
7253        // per-axis accessor family. The four-axis fan-out is now
7254        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7255        // `p.retries` field-access sites (co-resident with the peer
7256        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7257        // b0e741a / 21a6c3b already lifted) now route through
7258        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7259        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7260        // access axis on the M3 mesh-slot family.
7261        let p = self.politicas();
7262        if let Some(t) = p.timeout() {
7263            // Zero-floor + integer-millisecond canonical-form +
7264            // upper-cap bracket on the typed `:timeout` axis. See
7265            // [`crate::render::require_positive_canonical_bounded_duration`]
7266            // for the full three-arm ordering discipline (zero-floor
7267            // strictly precedes the canonical-form arm so
7268            // `Duration::ZERO` surfaces the self-locating
7269            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7270            // remediation; canonical-form strictly precedes the cap
7271            // arm so a sub-millisecond above-cap `Duration` surfaces
7272            // the more fundamental round-trip-shape diagnostic first)
7273            // and the four peer typed-`Duration` sites that now share
7274            // this canonical bracket. Every validated value lies in
7275            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7276            // granularity — the same top-and-bottom-edge discipline
7277            // [`POLICY_RETRIES_MAX`] and
7278            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7279            // capped-`u32` `:politicas` axes.
7280            crate::render::require_positive_canonical_bounded_duration(
7281                t,
7282                POLICY_TIMEOUT_MAX,
7283                || AplicacaoError::PolicyTimeoutZero,
7284                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7285                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7286            )?;
7287        }
7288        if let Some(r) = p.retries() {
7289            // Zero-floor + upper-cap bracket on the typed `:retries`
7290            // axis. See [`crate::render::require_positive_bounded_u32`]
7291            // for the ordering discipline (zero-floor arm strictly
7292            // precedes cap arm so `Some(0)` surfaces the self-locating
7293            // `PolicyRetriesZero` diagnostic with its omit-axis
7294            // remediation directly named, not the misleading
7295            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7296            // this bracket landed the top edge ran all the way to
7297            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7298            // Some(100_000), .. }` (or the equivalent author-surface
7299            // `(:retries 100000)` / `(:retries 4294967295)` typo
7300            // landing in the slot) silently passed validate. The
7301            // runtime substrate consuming the value (Envoy's
7302            // `retry_policy.num_retries`, the future
7303            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7304            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7305            // policy into a thundering-herd amplification vector —
7306            // the caller's one request fans out to `retries`
7307            // server-side calls per edge per traversal, multiplying
7308            // load by `(retries+1)^depth` across the
7309            // synchronous-`:contratos` subgraph at the precise moment
7310            // the substrate is already failing (transient failure is
7311            // the trigger), exactly the failure mode AWS App Mesh's
7312            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7313            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7314            // the sibling capped-`u32` `:politicas` axes
7315            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7316            // `u32` axes in `:supervisor :max-restarts` +
7317            // `:limits :cpu`; all five now route through the same
7318            // canonical bracket helper.
7319            crate::render::require_positive_bounded_u32(
7320                r,
7321                POLICY_RETRIES_MAX,
7322                || AplicacaoError::PolicyRetriesZero,
7323                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7324            )?;
7325        }
7326        if let Some(cb) = p.circuit_breaker() {
7327            // Zero-floor + upper-cap bracket on the typed
7328            // `:max-failures` axis. See
7329            // [`crate::render::require_positive_bounded_u32`] for the
7330            // ordering discipline (zero-floor arm strictly precedes
7331            // cap arm so `max_failures == 0` surfaces the
7332            // self-locating `PolicyBreakerZeroFailures` diagnostic
7333            // with its omit-axis remediation directly named, not the
7334            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7335            // false` cap-arm miss). Until this bracket landed the top
7336            // edge ran all the way to `u32::MAX` and a struct-literal
7337            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7338            // equivalent author-surface `(:max-failures 100000)` /
7339            // `(:max-failures 4294967295)` typo landing in the slot)
7340            // silently passed validate. The runtime substrate
7341            // consuming the value (Envoy's
7342            // `outlier_detection.consecutive_5xx`, the future
7343            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7344            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7345            // breaker policy into a no-op — the trip threshold is
7346            // structurally so high that no realistic
7347            // failures-per-`:window` traffic shape can reach it, the
7348            // breaker never trips, and every typed-slot consumer
7349            // emits an Envoy / Cilium L7 overlay carrying a
7350            // protection that is structurally never enforced. The
7351            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7352            // peer with `retries` and `rate_limit.rate` on the same
7353            // helper.
7354            crate::render::require_positive_bounded_u32(
7355                cb.max_failures(),
7356                POLICY_BREAKER_MAX_FAILURES_MAX,
7357                || AplicacaoError::PolicyBreakerZeroFailures,
7358                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7359            )?;
7360            // Zero-floor + integer-millisecond canonical-form +
7361            // upper-cap bracket on the typed `:window` axis. See
7362            // [`crate::render::require_positive_canonical_bounded_duration`]
7363            // for the full three-arm ordering discipline (peer to the
7364            // `:timeout` site immediately above); every validated
7365            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7366            // (1ms..=1h), integer-millisecond granularity — the same
7367            // top-and-bottom-edge discipline
7368            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7369            // duration-typed `:politicas :timeout` axis.
7370            crate::render::require_positive_canonical_bounded_duration(
7371                cb.window(),
7372                POLICY_BREAKER_WINDOW_MAX,
7373                || AplicacaoError::PolicyBreakerZeroWindow,
7374                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7375                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7376            )?;
7377        }
7378        if let Some(rl) = p.rate_limit() {
7379            // Zero-floor + upper-cap bracket on the typed
7380            // `:rate-limit` rate axis. See
7381            // [`crate::render::require_positive_bounded_u32`] for the
7382            // ordering discipline (zero-floor arm strictly precedes
7383            // cap arm so `rl.rate == 0` surfaces the self-locating
7384            // `PolicyRateLimitZero` diagnostic with its omit-axis
7385            // remediation directly named, not the misleading
7386            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7387            // Until this bracket landed the top edge ran all the way
7388            // to `u32::MAX` and a struct-literal
7389            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7390            // author-surface `(:rate-limit "4294967295/s")` /
7391            // `(:rate-limit "100000000/m")` typo landing in the slot)
7392            // silently passed validate. The runtime substrate
7393            // consuming the value (Envoy's
7394            // `local_rate_limit.token_bucket.max_tokens`, the future
7395            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7396            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7397            // rate-limit policy into a no-op limiter: the bucket
7398            // capacity is structurally so high that no realistic
7399            // per-edge traffic shape can drain it, the limiter never
7400            // trips, and every typed-slot consumer emits a "rate
7401            // declared" L7 overlay carrying enforcement that is
7402            // structurally never reached — the canonical
7403            // declared-but-inert footgun the sibling
7404            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7405            // the peer no-op-breaker shape. The bracket set is
7406            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7407            // `max_failures` on the same helper. The rate bracket
7408            // strictly precedes the window-canonical gate so a
7409            // structurally absurd rate magnitude surfaces the more
7410            // fundamental amplification-shape diagnostic before the
7411            // narrower codec-round-trip-shape diagnostic on `:window`.
7412            crate::render::require_positive_bounded_u32(
7413                rl.rate(),
7414                POLICY_RATE_LIMIT_MAX,
7415                || AplicacaoError::PolicyRateLimitZero,
7416                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7417            )?;
7418            // The `:rate-limit` author surface is the canonical
7419            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7420            // accepts exactly the three-unit set (1s/60s/3600s) the
7421            // [`rate_limit_codec::render`] formatter emits the canonical
7422            // unit suffix for. A `RateLimit` whose `:window` is anything
7423            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7424            // programmatically (struct literals in Rust + the typed
7425            // `Duration` field) but renders to a `<n>/<k>s` fragment
7426            // (the codec's fall-through) the parser then rejects on
7427            // round-trip — silently breaking the THEORY.md §V.2.7
7428            // render-determinism contract for any consumer that
7429            // serializes-then-deserializes the typed slot. Lifting the
7430            // canonical-window invariant to a build-time gate at
7431            // `validate_politicas` makes the codec's round-trip property
7432            // a structural property of the validated typed value:
7433            // every `RateLimit` past `AplicacaoSpec::validate` has a
7434            // window the codec round-trips losslessly, so the next
7435            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7436            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7437            // §III.2 #3) reaches for `rate_limit.window` knowing the
7438            // value is in the codec's accepted set without re-validating
7439            // at the renderer layer. Same trajectory as c4213a4 (typed
7440            // WitContract endpoint/subject/slot value-shape gates) and
7441            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7442            // the typed slot's valid set matches its codec's accepted
7443            // set, structurally.
7444            // Route the canonical-window shape-gate through the substrate
7445            // primitive [`RateLimit::canonical_unit`] rather than the free
7446            // module-private [`is_canonical_rate_limit_window`] predicate:
7447            // both projections resolve `Duration → Option<RateLimitUnit>`
7448            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7449            // arm on the closed-set typed enum), but the accessor is the
7450            // typed method every downstream consumer of the validated slot
7451            // ([`rate_limit_codec::render`]'s canonical arm above, the
7452            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7453            // per-`:politicas :rate-limit` admission webhook, the future
7454            // per-`:contratos`-edge rate-limit-override overlay
7455            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7456            // production consumers of the canonical-unit axis (the codec
7457            // render and this validate gate) now key off exactly one typed
7458            // dispatch on the substrate primitive, so any future extension
7459            // to `canonical_unit` (a per-cluster canonical-window overlay
7460            // the operator pins through a future `:contratos :rate-limit
7461            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7462            // CR materializer resolves per-CR) reaches both consumers by
7463            // construction rather than a coordinated rewrite of every
7464            // free-helper call site.
7465            if rl.canonical_unit().is_none() {
7466                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7467                    window: rl.window(),
7468                });
7469            }
7470        }
7471        Ok(())
7472    }
7473
7474    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7475    /// A synchronous edge is any contract whose typed [`WitTarget`] is
7476    /// `Http`, `Store`, or `Capability` — the caller blocks on the
7477    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7478    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7479    /// block on its subscribers, so they can never close a sync loop.
7480    ///
7481    /// Iterative DFS with three-coloring; the reported cycle is the
7482    /// path of caixa names traversed from the back-edge target around
7483    /// to itself, in declaration order. Adjacency lists and DFS roots
7484    /// are visited in `BTreeMap` key order so the diagnostic is
7485    /// deterministic across runs.
7486    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7487        use std::collections::{BTreeMap, BTreeSet};
7488
7489        #[derive(Clone, Copy, PartialEq, Eq)]
7490        enum Mark {
7491            White,
7492            Gray,
7493            Black,
7494        }
7495
7496        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7497        for m in self.membros() {
7498            adj.entry(m.nome()).or_default();
7499        }
7500        for c in self.contratos() {
7501            // target() was already called by validate(); re-running here
7502            // keeps detect_sync_cycles self-contained for callers that
7503            // reuse it (M4 per-edge policy resolver) without revalidating.
7504            //
7505            // The pub-sub-arm check routes through the lifted
7506            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7507            // arm-discriminator predicate rather than a raw `matches!(…,
7508            // WitTarget::PubSub { .. })` on the variant so a future
7509            // rebrand on the axis (an M4 per-edge WIT registry split of
7510            // [`WitTarget::PubSub`] into shape-specific peers, a
7511            // per-consumer rename that the accept-set already carries)
7512            // reaches this call site through the derive rather than a
7513            // scattered per-arm `matches!` rewrite — same
7514            // `IsVariant`-derived-arm-discriminator discipline the
7515            // peer closed-set typed enums ([`crate::CaixaKind`] via
7516            // f5bba80, [`PlacementStrategy`] via 766ec63,
7517            // [`crate::supervisor::RestartStrategy`] +
7518            // [`crate::supervisor::RestartPolicy`],
7519            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7520            // already route through on the substrate's other typed-enum
7521            // arm-discriminator axes.
7522            if c.target()?.is_pubsub() {
7523                continue;
7524            }
7525            adj.entry(c.source()).or_default().insert(c.destination());
7526        }
7527
7528        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7529        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7530
7531        // Stable DFS root order — BTreeMap iteration is sorted by key.
7532        let roots: Vec<&str> = adj.keys().copied().collect();
7533
7534        // Frame: (node, sorted-neighbours snapshot, next-edge index).
7535        for root in roots {
7536            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7537                continue;
7538            }
7539            let root_neighbors: Vec<&str> = adj
7540                .get(root)
7541                .map(|s| s.iter().copied().collect())
7542                .unwrap_or_default();
7543            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7544            color.insert(root, Mark::Gray);
7545
7546            loop {
7547                // Read+advance the top frame in one borrow scope so we
7548                // can later mutate the stack (push/pop) without holding
7549                // a borrow across.
7550                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7551                    let node = top.0;
7552                    if top.2 >= top.1.len() {
7553                        (node, None)
7554                    } else {
7555                        let nxt = top.1[top.2];
7556                        top.2 += 1;
7557                        (node, Some(nxt))
7558                    }
7559                });
7560                let Some((node, nxt_opt)) = step else { break };
7561                let Some(nxt) = nxt_opt else {
7562                    color.insert(node, Mark::Black);
7563                    stack.pop();
7564                    continue;
7565                };
7566                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7567                match nxt_color {
7568                    Mark::Gray => {
7569                        // Reconstruct the cycle from `node` back through
7570                        // the parent chain to `nxt`, then close.
7571                        let mut cycle = Vec::new();
7572                        let mut cur = node;
7573                        cycle.push(cur.to_string());
7574                        while cur != nxt {
7575                            match parent.get(cur).copied() {
7576                                Some(p) => {
7577                                    cur = p;
7578                                    cycle.push(cur.to_string());
7579                                }
7580                                None => break,
7581                            }
7582                        }
7583                        cycle.reverse();
7584                        cycle.push(nxt.to_string());
7585                        return Err(AplicacaoError::ContratoCycle { cycle });
7586                    }
7587                    Mark::White => {
7588                        parent.insert(nxt, node);
7589                        color.insert(nxt, Mark::Gray);
7590                        let nxt_neighbors: Vec<&str> = adj
7591                            .get(nxt)
7592                            .map(|s| s.iter().copied().collect())
7593                            .unwrap_or_default();
7594                        stack.push((nxt, nxt_neighbors, 0));
7595                    }
7596                    Mark::Black => {}
7597                }
7598            }
7599        }
7600        Ok(())
7601    }
7602
7603    /// Substrate-canonical destination-facing TCP port every emitted
7604    /// per-Aplicacao artifact must key `destination`-shaped port axes
7605    /// off. Returns the typed `:entrada :port` scalar when this
7606    /// Aplicacao's `:entrada` block names `destination` under its
7607    /// `:para` axis (the destination Servico *is* the ingress apex, so
7608    /// the substrate honors the author-declared listener port
7609    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7610    /// fallback otherwise (every non-apex destination — the internal
7611    /// mesh Servicos `:contratos` reach across, the future per-edge
7612    /// policy resolver's per-destination probe targets, the
7613    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7614    /// L4 port resolver — reads the same substrate-canonical port floor
7615    /// by construction).
7616    ///
7617    /// Prior to this lift the "if :entrada matches this destination use
7618    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7619    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7620    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7621    /// prior to this lift), with no typed method on the substrate primitive
7622    /// that named the rule. A future per-destination port axis addition
7623    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7624    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7625    /// per-Servico listener ports land, a per-cluster override the operator
7626    /// pins through a future `:placement :default-port` slot — would have
7627    /// to be threaded through every renderer's inline cascade in lockstep
7628    /// or one consumer would silently disagree on which port a given
7629    /// destination Servico's ingress lands at. Lifting the rule to a
7630    /// typed method on the substrate primitive means the M4 CR
7631    /// materializer, the future per-edge policy resolver, and every
7632    /// downstream test-fixture navigator reach for exactly one typed
7633    /// dispatch — the resolver's accept-set moves as a unit on any
7634    /// future axis addition.
7635    ///
7636    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7637    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7638    /// the typed primitive, thin projections at each consumer"
7639    /// discipline lifts on the sibling `:contratos` payload / `:politicas
7640    /// :rate-limit` unit-suffix axes; extends the discipline onto the
7641    /// destination-facing port-resolution axis every per-Aplicacao
7642    /// L4-fallback renderer consumes.
7643    #[must_use]
7644    pub fn port_for_destination(&self, destination: &str) -> u16 {
7645        // Route the per-`:entrada` composite-reference read through
7646        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7647        // the raw `self.entrada.as_ref()` field access — the
7648        // per-destination L4-port fallback resolver's composite-
7649        // projection seed is now the canonical read-side surface
7650        // every per-Aplicacao entrada consumer routes through, peer
7651        // of the sibling `validate` per-`:entrada` shape-and-
7652        // membership gate migration on the same outer-composite
7653        // axis.
7654        // Route the per-`:entrada` apex-destination membership probe
7655        // through the lifted [`Entrada::destination`] accessor rather
7656        // than the raw `e.para == destination` field access — the last
7657        // un-lifted `.para` production-code read site on the per-
7658        // `:entrada` `:para` axis, sibling to the four caixa-core
7659        // consumer sites the peer 15ddd8c converge already routed
7660        // through the accessor (the three
7661        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7662        // membership gate sites: the `validate_entrada_para` DNS-1123
7663        // shape gate, the per-`:membros` membership lookup, and the
7664        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7665        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7666        // `entrada.para`-projection converge at
7667        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7668        // route-name projection site). Prior to this converge the
7669        // `port_for_destination` resolver was the solitary consumer
7670        // bypassing the typed dispatch on the `.para` axis — the two
7671        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7672        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7673        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7674        // reach through the same accessor family compose with this
7675        // resolver at the emit boundary via the apex-identity
7676        // invariant `spec.port_for_destination(entrada.destination())
7677        // == entrada.port` the sibling
7678        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7679        // pin pins across four permutations. A future extension of the
7680        // `:entrada :para` axis to a richer author surface (a per-
7681        // cluster alias overlay the operator pins through a future
7682        // `:placement`-scoped slot, a namespace-qualified rewrite the
7683        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7684        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7685        // §III.2 acknowledges) that lands on the accessor would silently
7686        // disagree between this resolver and the two `caixa-mesh` emit
7687        // sites — an author-declared `:para "cart"` value the accessor
7688        // rewrote to `"cart-v2"` under a future canary arm would leave
7689        // the resolver's membership arm falling through to
7690        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7691        // `.para`) while the peer emit-site consumers landed on the
7692        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7693        // silently disagreed on which destination port a given typed
7694        // `:entrada` resolves to at cluster-apply time. Pinned by the
7695        // drift-detection test
7696        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7697        // below.
7698        self.entrada()
7699            .filter(|e| e.destination() == destination)
7700            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7701    }
7702}
7703
7704/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7705/// entry may name the Aplicacao's own `:nome`.
7706///
7707/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7708/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7709/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7710/// Servicos that compose the app; an Aplicacao is never its own constituent),
7711/// and the lacre pipeline's closure-resolution would otherwise be handed a
7712/// node that is its own parent: a one-node cycle it either rejects far from
7713/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7714/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7715/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7716/// label + lacre closure root), a member whose `:caixa` equals the
7717/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7718/// peer.
7719///
7720/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7721/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7722/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7723/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7724/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7725/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7726/// (the Aplicacao :membros set; the supervision-tree :children list was the
7727/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7728/// every validated Supervisor's children are distinct from its `:nome`,
7729/// every validated Aplicacao's membros are distinct from its `:nome`. The
7730/// transitive consequence is that `:entrada :para` and `:contratos`
7731/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7732/// name the Aplicacao itself, without re-deriving the partition.
7733pub fn validate_no_self_membership(
7734    membros: &[Membro],
7735    parent_nome: &str,
7736) -> Result<(), AplicacaoError> {
7737    for m in membros {
7738        if m.nome() == parent_nome {
7739            return Err(AplicacaoError::MembroIsSelfAplicacao {
7740                caixa: parent_nome.to_string(),
7741            });
7742        }
7743    }
7744    Ok(())
7745}
7746
7747#[derive(Debug, Error, PartialEq, Eq)]
7748pub enum AplicacaoError {
7749    #[error("Aplicacao must declare at least one :membros entry")]
7750    NoMembros,
7751    #[error(
7752        ":membros entry has empty :caixa (every member must name a Servico; \
7753         omit the entry instead of carrying an empty name)"
7754    )]
7755    MembroCaixaEmpty,
7756    #[error(
7757        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7758         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7759         name / label value the member name lands in; use a lowercase \
7760         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7761    )]
7762    MembroCaixaInvalid { caixa: String, reason: String },
7763    #[error(
7764        ":membros entry {caixa:?} has empty :versao (every member must pin a \
7765         semver constraint that resolves through the lacre pipeline)"
7766    )]
7767    MembroVersaoEmpty { caixa: String },
7768    #[error(
7769        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7770         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7771         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7772         carries; the lacre pipeline resolves both through the same parser)"
7773    )]
7774    MembroVersaoInvalid {
7775        caixa: String,
7776        versao: String,
7777        reason: String,
7778    },
7779    #[error(
7780        ":membros entry {caixa:?} appears more than once (the graph node set \
7781         is a set, not a multiset; duplicate members produce duplicate \
7782         programs.yaml entries and ambiguous :contratos membership lookups)"
7783    )]
7784    MembroDuplicate { caixa: String },
7785    #[error(
7786        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7787         never its own constituent Servico (the application graph is a DAG rooted \
7788         at the Aplicacao; :membros names the *other* caixas that compose the \
7789         app, not the app itself). Since every :nome is a globally-unique \
7790         substrate identity, a member naming the Aplicacao's own :nome is a \
7791         one-node lacre-closure recursion, not a coincidentally-named peer; \
7792         drop the self-referential :membros entry or rename it to the actual \
7793         constituent caixa."
7794    )]
7795    MembroIsSelfAplicacao { caixa: String },
7796    #[error(
7797        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7798         caixa declared in :membros; omit the contract or fill the {slot} field with a \
7799         member name)"
7800    )]
7801    ContratoCaixaEmpty { slot: &'static str },
7802    #[error(
7803        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7804         :contratos {slot} value names a member of :membros, which is itself a \
7805         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7806         object the member name lands in — Service, Pod, identity-based Cilium \
7807         selector; use a lowercase alphanumeric + hyphen identifier like \
7808         `\"checkout\"` or `\"cart-v2\"`)"
7809    )]
7810    ContratoCaixaInvalid {
7811        slot: &'static str,
7812        caixa: String,
7813        reason: String,
7814    },
7815    #[error("contrato references caixa {caixa:?} not declared in :membros")]
7816    ContratoMemberMissing { caixa: String },
7817    #[error(
7818        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7819         entry is an inter-Servico contract whose :de and :para must name distinct \
7820         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7821         the contract, or point :para at the member it actually calls)"
7822    )]
7823    ContratoSelfLoop { caixa: String, wit: String },
7824    #[error("contrato {de:?} → {para:?} has empty :wit")]
7825    EmptyWit { de: String, para: String },
7826    #[error(
7827        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7828         {reason} (the substrate dispatches `:wit` values on the canonical \
7829         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7830         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7831         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7832         kebab-case identifier per segment)"
7833    )]
7834    ContratoWitInvalid {
7835        de: String,
7836        para: String,
7837        wit: String,
7838        reason: String,
7839    },
7840    #[error(
7841        ":entrada :para is empty (every :entrada must route to a caixa declared in \
7842         :membros; fill the :para field with a member name)"
7843    )]
7844    EntradaParaEmpty,
7845    #[error(
7846        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7847         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7848         label per the K8s apiserver's `metadata.name` rule on every object the \
7849         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7850         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7851         `\"checkout\"` or `\"cart-v2\"`)"
7852    )]
7853    EntradaParaInvalid { para: String, reason: String },
7854    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7855    EntradaMemberMissing { para: String },
7856    #[error(":entrada must declare a non-empty :host")]
7857    EmptyEntradaHost,
7858    #[error(
7859        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7860         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7861         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7862         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7863    )]
7864    EntradaHostInvalid { host: String, reason: String },
7865    #[error(":entrada :port must be in 1..=65535, got 0")]
7866    EntradaPortZero,
7867    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7868    EntradaPathEmpty,
7869    #[error(
7870        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7871    )]
7872    EntradaPathNotAbsolute { path: String },
7873    #[error(
7874        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7875         value: {reason} (the K8s apiserver enforces the same shape on \
7876         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7877         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7878         requires percent-encoding `%XX` for non-ASCII and whitespace)"
7879    )]
7880    EntradaPathInvalid { path: String, reason: String },
7881    #[error(":entrada :paths entry {path:?} appears more than once")]
7882    EntradaPathDuplicate { path: String },
7883    #[error(
7884        ":placement {estrategia} requires at least one :clusters entry \
7885         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7886    )]
7887    PlacementWithoutClusters { estrategia: PlacementStrategy },
7888    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7889    PlacementClusterEmpty,
7890    #[error(
7891        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7892         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7893         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7894         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7895         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7896         identifier like `\"rio\"` or `\"mar-east\"`)"
7897    )]
7898    PlacementClusterInvalid { cluster: String, reason: String },
7899    #[error(":placement :clusters entry {cluster:?} appears more than once")]
7900    PlacementClusterDuplicate { cluster: String },
7901    #[error(
7902        ":placement :affinity must be non-empty when set (omit :affinity to express \
7903         `no placement hint`)"
7904    )]
7905    PlacementAffinityEmpty,
7906    #[error(
7907        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7908         (placement hints land verbatim in the M3 Adaptive compression overlay's \
7909         `placement.affinity` field and in every future M4 placement-engine routing \
7910         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7911         selector — both enforce the DNS-1123 label rule on admission; use a \
7912         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7913         `\"low-latency\"`, or `\"anti-affinity\"`)"
7914    )]
7915    PlacementAffinityInvalid { affinity: String, reason: String },
7916    #[error(":placement Sharded requires :shard-key")]
7917    ShardedWithoutKey,
7918    #[error(
7919        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7920         hashes every entity onto the same shard, defeating sharding entirely)"
7921    )]
7922    ShardedKeyEmpty,
7923    #[error(
7924        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7925         entity-id extractor expression: {reason} (the future M4 Akka-style \
7926         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7927         as a single-token property reference and hashes the extracted entity ID \
7928         to compute shard placement; use a printable-ASCII extractor expression \
7929         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7930         `\"${{tenant}}\"`)"
7931    )]
7932    ShardKeyInvalid { shard_key: String, reason: String },
7933    #[error(
7934        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7935         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7936         convention); :estrategia Replicated runs every cluster active-active and \
7937         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7938         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7939         to :estrategia Sharded if hash-keyed routing is the intent"
7940    )]
7941    ShardKeyOnNonSharded {
7942        estrategia: PlacementStrategy,
7943        shard_key: String,
7944    },
7945    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7946    ContratoMissingTarget {
7947        de: String,
7948        para: String,
7949        wit: String,
7950        expected: &'static str,
7951    },
7952    #[error(
7953        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7954         expected `:{expected}` only"
7955    )]
7956    ContratoWrongTarget {
7957        de: String,
7958        para: String,
7959        wit: String,
7960        expected: &'static str,
7961    },
7962    #[error(
7963        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7964         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7965         that matches no traffic and silently drops every request)"
7966    )]
7967    ContratoEndpointEmpty { de: String, para: String },
7968    #[error(
7969        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7970         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7971         :entrada :paths)"
7972    )]
7973    ContratoEndpointNotAbsolute {
7974        de: String,
7975        para: String,
7976        endpoint: String,
7977    },
7978    #[error(
7979        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7980         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7981         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7982         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7983         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7984         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7985         and whitespace)"
7986    )]
7987    ContratoEndpointInvalid {
7988        de: String,
7989        para: String,
7990        endpoint: String,
7991        reason: String,
7992    },
7993    #[error(
7994        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7995         subject is a no-op subscribe; omit :subject only if the WIT world is not \
7996         pub-sub-shaped)"
7997    )]
7998    ContratoSubjectEmpty { de: String, para: String },
7999    #[error(
8000        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8001         NATS subject: {reason} (the NATS server's subject parser enforces the \
8002         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8003         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8004         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8005         `\"orders.*.completed\"` — a malformed subject silently drops every \
8006         message at runtime far from the source caixa.lisp)"
8007    )]
8008    ContratoSubjectInvalid {
8009        de: String,
8010        para: String,
8011        subject: String,
8012        reason: String,
8013    },
8014    #[error(
8015        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8016         addresses the bucket root, defeating the per-key isolation the slot exists \
8017         for; omit :slot only if the WIT world is not store-shaped)"
8018    )]
8019    ContratoSlotEmpty { de: String, para: String },
8020    #[error(
8021        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8022         WASI keyvalue store slot template: {reason} (the substrate enforces \
8023         the printable-ASCII intersection-floor every kv backend admits — \
8024         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8025         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8026         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8027         slot either gets rejected on write by strict backends or silently \
8028         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8029    )]
8030    ContratoSlotInvalid {
8031        de: String,
8032        para: String,
8033        slot: String,
8034        reason: String,
8035    },
8036    #[error(
8037        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8038         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8039        cycle.join(" → ")
8040    )]
8041    ContratoCycle { cycle: Vec<String> },
8042    #[error(
8043        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8044         than once (the typed graph edges are a set, not a multiset; duplicate \
8045         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8046         values that K8s admission rejects far from the source caixa.lisp)"
8047    )]
8048    ContratoDuplicate {
8049        de: String,
8050        para: String,
8051        wit: String,
8052        target: String,
8053    },
8054    #[error(
8055        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8056         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8057         express `no per-call deadline on this axis`"
8058    )]
8059    PolicyTimeoutZero,
8060    #[error(
8061        ":politicas :retries must be > 0 when set; omit :retries to express \
8062         `no retries on transient failure`"
8063    )]
8064    PolicyRetriesZero,
8065    #[error(
8066        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8067         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8068         retry policy into a thundering-herd amplification vector on transient \
8069         failure (one caller request fans out to `(retries+1)^depth` server-side \
8070         calls across the synchronous-:contratos subgraph), exactly the failure \
8071         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8072         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8073         or omit :retries to disable retries entirely"
8074    )]
8075    PolicyRetriesExceedsCap { retries: u32 },
8076    #[error(
8077        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8078         breaker trips on the first call); omit :circuit-breaker to disable it"
8079    )]
8080    PolicyBreakerZeroFailures,
8081    #[error(
8082        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8083         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8084         above this cap turns the typed breaker policy into a no-op: the trip \
8085         threshold is structurally so high that no realistic failures-per-:window \
8086         traffic shape can reach it, so the breaker never trips and every typed-slot \
8087         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8088         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8089         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8090         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8091         omit :circuit-breaker to disable the breaker entirely"
8092    )]
8093    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8094    #[error(
8095        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8096         tracks no failures); omit :circuit-breaker to disable it"
8097    )]
8098    PolicyBreakerZeroWindow,
8099    #[error(
8100        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8101         request); omit :rate-limit to disable rate limiting"
8102    )]
8103    PolicyRateLimitZero,
8104    #[error(
8105        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8106         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8107         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8108         structurally so high that no realistic per-edge traffic shape can drain it, \
8109         so the limiter never trips and every typed-slot consumer (the future \
8110         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8111         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8112         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8113         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8114         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8115         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8116         to disable rate limiting entirely"
8117    )]
8118    PolicyRateLimitExceedsCap { rate: u32 },
8119    #[error(
8120        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8121         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8122         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8123         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8124         three canonical windows)"
8125    )]
8126    PolicyRateLimitWindowNotCanonical { window: Duration },
8127    #[error(
8128        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8129         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8130         duration codec round-trips losslessly; got {timeout:?} which carries a \
8131         sub-millisecond residue that either truncates to a different `Duration` on \
8132         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8133         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8134         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8135         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8136    )]
8137    PolicyTimeoutNotCanonical { timeout: Duration },
8138    #[error(
8139        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8140         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8141         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8142         overlays carry a deadline so long no realistic synchronous-:contratos \
8143         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8144         CSE invariant degenerates to enforcement only at the per-Servico \
8145         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8146         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8147         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8148         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8149         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8150         `no per-call deadline on this axis` (the synchronous-call deadline then \
8151         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8152    )]
8153    PolicyTimeoutExceedsCap { timeout: Duration },
8154    #[error(
8155        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8156         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8157         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8158         sub-millisecond residue that either truncates to a different `Duration` on \
8159         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8160         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8161    )]
8162    PolicyBreakerWindowNotCanonical { window: Duration },
8163    #[error(
8164        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8165         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8166         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8167         is structurally so long that transient failures are never forgotten, the breaker \
8168         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8169         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8170         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8171         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8172         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8173         the breaker entirely"
8174    )]
8175    PolicyBreakerWindowExceedsCap { window: Duration },
8176}
8177
8178#[cfg(test)]
8179mod tests {
8180    use super::*;
8181
8182    fn membro(name: &str, ver: &str) -> Membro {
8183        Membro {
8184            caixa: name.into(),
8185            versao: ver.into(),
8186        }
8187    }
8188
8189    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8190        WitContract {
8191            de: de.into(),
8192            para: para.into(),
8193            wit: "wasi:http/proxy".into(),
8194            endpoint: Some(ep.into()),
8195            subject: None,
8196            slot: None,
8197        }
8198    }
8199
8200    fn three_member_spec() -> AplicacaoSpec {
8201        AplicacaoSpec {
8202            membros: vec![
8203                membro("catalog", "^0.1"),
8204                membro("cart", "^0.1"),
8205                membro("payment", "^0.2"),
8206            ],
8207            contratos: vec![
8208                contract_http("cart", "catalog", "/products/:id"),
8209                contract_http("cart", "payment", "/charge"),
8210            ],
8211            politicas: MeshPolicy {
8212                timeout: Some(Duration::from_secs(30)),
8213                retries: Some(3),
8214                mtls_required: Some(true),
8215                ..Default::default()
8216            },
8217            placement: Placement {
8218                estrategia: PlacementStrategy::Replicated,
8219                clusters: vec!["rio".into(), "mar".into()],
8220                affinity: Some("data-locality".into()),
8221                shard_key: None,
8222            },
8223            entrada: Some(Entrada {
8224                host: "checkout.quero.cloud".into(),
8225                para: "cart".into(),
8226                paths: vec!["/api/cart".into(), "/api/products".into()],
8227                port: 8080,
8228            }),
8229        }
8230    }
8231
8232    #[test]
8233    fn happy_path_validates() {
8234        three_member_spec().validate().unwrap();
8235    }
8236
8237    #[test]
8238    fn rejects_empty_membros() {
8239        let mut s = three_member_spec();
8240        s.membros = vec![];
8241        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8242    }
8243
8244    #[test]
8245    fn rejects_empty_membro_caixa() {
8246        // A `:caixa ""` entry has no name to render into programs.yaml
8247        // and no caixa.lisp to resolve at lacre time.
8248        let mut s = three_member_spec();
8249        s.membros[1].caixa = String::new();
8250        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8251    }
8252
8253    #[test]
8254    fn rejects_empty_membro_versao() {
8255        // A `:versao ""` entry can't pin a semver constraint, so the
8256        // lacre pipeline fails far from the source.
8257        let mut s = three_member_spec();
8258        s.membros[2].versao = String::new();
8259        let err = s.validate().unwrap_err();
8260        assert!(
8261            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8262            "got {err:?}"
8263        );
8264    }
8265
8266    #[test]
8267    fn rejects_duplicate_membro_caixa() {
8268        // Two `:membros` entries with the same `:caixa` collapse to one
8269        // node in the membership HashSet, which masks `:contratos`
8270        // membership errors and produces duplicate programs.yaml entries.
8271        let mut s = three_member_spec();
8272        s.membros.push(membro("cart", "^0.2"));
8273        let err = s.validate().unwrap_err();
8274        assert!(
8275            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8276            "got {err:?}"
8277        );
8278    }
8279
8280    #[test]
8281    fn rejects_invalid_membro_versao_requirement() {
8282        // The fail-before-pass-after pin: a non-empty but malformed
8283        // semver requirement (`"^bad-version"`) silently passed
8284        // `validate()` on every pre-gate codebase because the prior
8285        // shape only refused the empty string. The parse failure
8286        // surfaced far downstream at lacre-resolve time with a
8287        // `semver::Error` that didn't name which `:membros` entry
8288        // carried the typo. The new gate moves the check to caixa-build
8289        // time at the source caixa.lisp.
8290        let mut s = three_member_spec();
8291        s.membros[2].versao = "^bad-version".into();
8292        let err = s.validate().unwrap_err();
8293        assert!(
8294            matches!(
8295                err,
8296                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8297                    if caixa == "payment" && versao == "^bad-version"
8298            ),
8299            "got {err:?}"
8300        );
8301    }
8302
8303    #[test]
8304    fn rejects_membro_versao_with_double_caret_typo() {
8305        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8306        // Cargo-shaped requirement on first glance but fails the parser
8307        // because semver doesn't accept stacked operators. Pin this
8308        // adjacent-shape footgun explicitly so a future relaxation that
8309        // accepts "looks-canonical-but-isn't" forms surfaces here.
8310        let mut s = three_member_spec();
8311        s.membros[0].versao = "^^0.1".into();
8312        let err = s.validate().unwrap_err();
8313        assert!(
8314            matches!(
8315                err,
8316                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8317                    if caixa == "catalog" && versao == "^^0.1"
8318            ),
8319            "got {err:?}"
8320        );
8321    }
8322
8323    #[test]
8324    fn rejects_membro_versao_with_v_prefixed_tag() {
8325        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8326        // semver requirement slot" typo — an author copies the
8327        // publish-side git-tag string verbatim into `:versao`, but
8328        // Cargo's semver parser rejects the leading `v` (only digits +
8329        // canonical operators are valid in the major-version
8330        // position). The gate's diagnostic names which member entry
8331        // carried the v-prefix so the fix is one edit, not a grep
8332        // through every member's `:versao`. (Note: bare `x`-glob
8333        // shorthands like `^0.1.x` are *accepted* by the semver crate
8334        // as an `*` wildcard on the patch axis — they're a Cargo-side
8335        // valid shape, not a typo, so the gate intentionally lets them
8336        // through.)
8337        let mut s = three_member_spec();
8338        s.membros[1].versao = "v0.1".into();
8339        let err = s.validate().unwrap_err();
8340        assert!(
8341            matches!(
8342                err,
8343                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8344                    if caixa == "cart" && versao == "v0.1"
8345            ),
8346            "got {err:?}"
8347        );
8348    }
8349
8350    #[test]
8351    fn accepts_canonical_membro_versao_forms() {
8352        // The four Cargo-shaped requirement forms `:deps :versao`
8353        // already accepts via `crate::parse_requirement` must pass the
8354        // membros gate without re-validating at the resolver layer.
8355        // Pin every leg so a future tightening of the canonical set
8356        // surfaces here as a test failure.
8357        for form in [
8358            "^0.1",      // caret — minor-range pin (the most common shape)
8359            "~0.1.2",    // tilde — patch-range pin
8360            "0.1.0",     // exact — single-version pin
8361            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8362            ">=0.1, <2", // multi-range — comma-separated comparators
8363        ] {
8364            let mut s = three_member_spec();
8365            for m in &mut s.membros {
8366                m.versao = form.into();
8367            }
8368            s.validate()
8369                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8370        }
8371    }
8372
8373    #[test]
8374    fn membro_versao_empty_takes_precedence_over_invalid() {
8375        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8376        // (which doesn't try to parse) fires before the new
8377        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8378        // `:versao` keeps its narrower error message — `parse_requirement`
8379        // would also reject `""`, but the empty-string arm is the more
8380        // self-locating diagnostic for the author.
8381        let mut s = three_member_spec();
8382        s.membros[1].versao = String::new();
8383        let err = s.validate().unwrap_err();
8384        assert!(
8385            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8386            "got {err:?}"
8387        );
8388    }
8389
8390    #[test]
8391    fn membro_versao_invalid_fires_before_duplicate_check() {
8392        // Order pin: a malformed requirement on a non-duplicate entry
8393        // surfaces *its own* diagnostic (which names the offending
8394        // `:versao` string), even when a later entry would otherwise
8395        // collapse onto an earlier name. The per-entry shape gate runs
8396        // inline before the duplicate-key insert, parallel to
8397        // `membros_validation_runs_before_contratos_membership_check`
8398        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8399        let mut s = three_member_spec();
8400        s.membros[0].versao = "^bad".into();
8401        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8402        let err = s.validate().unwrap_err();
8403        assert!(
8404            matches!(
8405                err,
8406                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8407            ),
8408            "got {err:?}"
8409        );
8410    }
8411
8412    #[test]
8413    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8414        // The diagnostic-shape pin: the error names the offending
8415        // `:versao` value verbatim so the author can grep their
8416        // caixa.lisp without re-running the build, and carries a
8417        // non-empty `reason` from `semver::VersionReq::parse` so the
8418        // parser's own wording flows through to the diagnostic.
8419        let mut s = three_member_spec();
8420        s.membros[2].versao = "not-a-req".into();
8421        let err = s.validate().unwrap_err();
8422        let AplicacaoError::MembroVersaoInvalid {
8423            caixa,
8424            versao,
8425            reason,
8426        } = err
8427        else {
8428            panic!("expected MembroVersaoInvalid, got other variant");
8429        };
8430        assert_eq!(caixa, "payment");
8431        assert_eq!(versao, "not-a-req");
8432        assert!(
8433            !reason.is_empty(),
8434            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8435        );
8436    }
8437
8438    #[test]
8439    fn membro_versao_invalid_runs_before_contratos_check() {
8440        // A malformed `:versao` on any member must surface its own
8441        // diagnostic (which names *which* member to fix) before any
8442        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8443        // The `:contratos` gate runs after `validate_membros`, so this
8444        // is structurally guaranteed — pin it explicitly so a future
8445        // refactor that reorders the gates surfaces here.
8446        let mut s = three_member_spec();
8447        s.membros[1].versao = "^^0.1".into();
8448        // Add a contrato whose `:para` doesn't exist — would normally
8449        // raise ContratoMemberMissing at the membership lookup, but
8450        // the membros gate must fire first.
8451        s.contratos
8452            .push(contract_http("cart", "phantom", "/never-reached"));
8453        let err = s.validate().unwrap_err();
8454        assert!(
8455            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8456            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8457        );
8458    }
8459
8460    #[test]
8461    fn membros_validation_runs_before_contratos_membership_check() {
8462        // If `:membros` carries a duplicate, the membership-collapse
8463        // would silently accept a `:contratos :para "phantom"` so long
8464        // as some entry hashes to "phantom". Pinning order: the
8465        // duplicate-membros error fires first, regardless of whether
8466        // contratos reference real members.
8467        let mut s = three_member_spec();
8468        s.membros = vec![
8469            membro("cart", "^0.1"),
8470            membro("cart", "^0.2"),
8471            membro("catalog", "^0.1"),
8472            membro("payment", "^0.1"),
8473        ];
8474        let err = s.validate().unwrap_err();
8475        assert!(
8476            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8477            "got {err:?}"
8478        );
8479    }
8480
8481    #[test]
8482    fn distinct_membros_validate() {
8483        // Pin the happy-path: every `:membros` entry has a non-empty
8484        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8485        // The fixture already satisfies this; this test makes the
8486        // invariant explicit so a future refactor of the fixture can't
8487        // silently break the guarantee.
8488        three_member_spec().validate().unwrap();
8489    }
8490
8491    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8492
8493    #[test]
8494    fn rejects_membro_caixa_with_uppercase() {
8495        // The canonical "I copied the Servico's display name verbatim"
8496        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8497        // but author tools often round-trip a TitleCase or CamelCase
8498        // identifier from an ADR or a sketch. Pin the diagnostic names
8499        // the offending name and suggests the lower-cased fix in one
8500        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8501        // gate's shape (c7d05ec).
8502        let mut s = three_member_spec();
8503        s.membros[1].caixa = "Cart".into();
8504        let err = s.validate().unwrap_err();
8505        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8506            panic!("expected MembroCaixaInvalid, got other variant");
8507        };
8508        assert_eq!(caixa, "Cart");
8509        assert!(
8510            reason.contains("uppercase"),
8511            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8512        );
8513        assert!(
8514            reason.contains("\"cart\""),
8515            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8516        );
8517    }
8518
8519    #[test]
8520    fn rejects_membro_caixa_with_underscore() {
8521        // The canonical "I'm thinking of a Python module / Postgres
8522        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8523        // label schema. K8s rejects `metadata.name: my_cart` at admission
8524        // time with an opaque `field is invalid` (no source-citing
8525        // diagnostic). The gate moves it to caixa-build time.
8526        let mut s = three_member_spec();
8527        s.membros[0].caixa = "my_cart".into();
8528        let err = s.validate().unwrap_err();
8529        assert!(
8530            matches!(
8531                err,
8532                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8533                    if caixa == "my_cart" && reason.contains('_')
8534            ),
8535            "got {err:?}"
8536        );
8537    }
8538
8539    #[test]
8540    fn rejects_membro_caixa_with_dot() {
8541        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8542        // subdomain — even though K8s `metadata.name` itself accepts
8543        // dots (DNS-1123 subdomain rule), this string also lands as a
8544        // K8s Service name (DNS-1035 label — no dots) and as a label
8545        // value on identity-based Cilium selectors. The strictest floor
8546        // among the use sites wins. The "I want to namespace my member
8547        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8548        let mut s = three_member_spec();
8549        s.membros[2].caixa = "team.cart".into();
8550        let err = s.validate().unwrap_err();
8551        assert!(
8552            matches!(
8553                err,
8554                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8555                    if caixa == "team.cart" && reason.contains('.')
8556            ),
8557            "got {err:?}"
8558        );
8559    }
8560
8561    #[test]
8562    fn rejects_membro_caixa_with_leading_hyphen() {
8563        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8564        // with an alphanumeric. The K8s apiserver rejects `-cart`
8565        // outright; the renderer would emit a `metadata.name: "-cart"`
8566        // that fails admission far from the source caixa.lisp.
8567        let mut s = three_member_spec();
8568        s.membros[0].caixa = "-cart".into();
8569        let err = s.validate().unwrap_err();
8570        assert!(
8571            matches!(
8572                err,
8573                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8574                    if caixa == "-cart" && reason.contains("start and end")
8575            ),
8576            "got {err:?}"
8577        );
8578    }
8579
8580    #[test]
8581    fn rejects_membro_caixa_with_trailing_hyphen() {
8582        // The symmetric arm of the boundary rule. Pin separately so
8583        // both ends of the label are covered against a future relaxation
8584        // that only checks one boundary.
8585        let mut s = three_member_spec();
8586        s.membros[1].caixa = "cart-".into();
8587        let err = s.validate().unwrap_err();
8588        assert!(
8589            matches!(
8590                err,
8591                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8592                    if caixa == "cart-"
8593            ),
8594            "got {err:?}"
8595        );
8596    }
8597
8598    #[test]
8599    fn rejects_membro_caixa_with_unicode() {
8600        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8601        // (`xn--…`) by the author before it reaches K8s. The byte-by-
8602        // byte ASCII validity check rejects multi-byte UTF-8 sequences
8603        // by the first byte that fails the `[a-z0-9-]` predicate.
8604        let mut s = three_member_spec();
8605        s.membros[2].caixa = "café".into();
8606        let err = s.validate().unwrap_err();
8607        assert!(
8608            matches!(
8609                err,
8610                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8611                    if caixa == "café"
8612            ),
8613            "got {err:?}"
8614        );
8615    }
8616
8617    #[test]
8618    fn rejects_membro_caixa_with_whitespace() {
8619        // Whitespace is the canonical "I pasted from a sketch / doc"
8620        // footgun. The apiserver rejects every `metadata.name` value
8621        // carrying whitespace; pin the gate fires at the right boundary.
8622        let mut s = three_member_spec();
8623        s.membros[0].caixa = "my cart".into();
8624        let err = s.validate().unwrap_err();
8625        assert!(
8626            matches!(
8627                err,
8628                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8629                    if caixa == "my cart"
8630            ),
8631            "got {err:?}"
8632        );
8633    }
8634
8635    #[test]
8636    fn rejects_membro_caixa_too_long() {
8637        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8638        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8639        // exactly. The gate's reason names both the cap and the actual
8640        // length so the author can shorten in one edit.
8641        let mut s = three_member_spec();
8642        let too_long = "a".repeat(64);
8643        s.membros[1].caixa = too_long.clone();
8644        let err = s.validate().unwrap_err();
8645        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8646            panic!("expected MembroCaixaInvalid");
8647        };
8648        assert_eq!(caixa, too_long);
8649        assert!(
8650            reason.contains("63") && reason.contains("64"),
8651            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8652        );
8653    }
8654
8655    #[test]
8656    fn membro_caixa_max_length_validates() {
8657        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8658        // so a future tightening (e.g. dropping to 62) surfaces here as
8659        // a regression, mirroring `entrada_host_max_length_validates`
8660        // (c7d05ec).
8661        let mut s = three_member_spec();
8662        s.membros[2].caixa = "a".repeat(63);
8663        s.entrada.as_mut().unwrap().para = "a".repeat(63);
8664        // remove contratos referencing the renamed member; they'd
8665        // raise ContratoMemberMissing otherwise
8666        s.contratos
8667            .retain(|c| c.de != "payment" && c.para != "payment");
8668        s.validate().unwrap();
8669    }
8670
8671    #[test]
8672    fn accepts_canonical_membro_caixa_forms() {
8673        // The DNS-1123 label shapes a caixa author is realistically
8674        // going to write: single-word lowercase, hyphen-joined, ending
8675        // in a digit-suffixed version (`cart-v2`), starting with a
8676        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8677        // DNS-1035 which requires a letter at position 0), single-
8678        // character (`a` — boundary). Pin every leg so a future
8679        // tightening that bans (e.g.) digit-start identifiers surfaces
8680        // here.
8681        for form in [
8682            "checkout",
8683            "cart",
8684            "cart-v2",
8685            "a",
8686            "c0",
8687            "3rd-party-shim",
8688            "x-1-2-3-4",
8689        ] {
8690            let mut s = three_member_spec();
8691            // Renaming a member also requires updating downstream refs;
8692            // drop everything else and rebuild a minimal spec around
8693            // just the one renamed member.
8694            s.membros = vec![membro(form, "^0.1")];
8695            s.contratos = vec![];
8696            s.entrada = None;
8697            s.validate()
8698                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8699        }
8700    }
8701
8702    #[test]
8703    fn membro_caixa_empty_takes_precedence_over_invalid() {
8704        // Order pin: the existing `MembroCaixaEmpty` diagnostic
8705        // (which doesn't try to parse) fires before the new
8706        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8707        // `:caixa` keeps its narrower error message — the new gate
8708        // would also reject `""`, but the empty-string arm is the more
8709        // self-locating diagnostic for the author. Mirrors the
8710        // `entrada_host_empty_takes_precedence_over_invalid` pin
8711        // (c7d05ec).
8712        let mut s = three_member_spec();
8713        s.membros[1].caixa = String::new();
8714        let err = s.validate().unwrap_err();
8715        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8716    }
8717
8718    #[test]
8719    fn membro_caixa_invalid_fires_before_versao_check() {
8720        // Order pin: an invalid-shape `:caixa` surfaces *its own*
8721        // diagnostic (which names the offending caixa name), even when
8722        // the same entry's `:versao` is also empty/invalid. The shape
8723        // gate runs first because the diagnostic is more self-locating —
8724        // an empty/invalid `:versao` on an invalid-shape caixa name is
8725        // a downstream-fix-after-the-caixa-rename concern.
8726        let mut s = three_member_spec();
8727        s.membros[1].caixa = "Cart".into();
8728        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8729        let err = s.validate().unwrap_err();
8730        assert!(
8731            matches!(
8732                err,
8733                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8734            ),
8735            "got {err:?}"
8736        );
8737    }
8738
8739    #[test]
8740    fn membro_caixa_invalid_fires_before_duplicate_check() {
8741        // Order pin: a malformed-shape `:caixa` on an earlier entry
8742        // surfaces *its own* diagnostic, even when a later entry would
8743        // otherwise collapse onto a duplicate name. The per-entry shape
8744        // gate runs inline before the duplicate-key insert, parallel
8745        // to `membro_versao_invalid_fires_before_duplicate_check`.
8746        let mut s = three_member_spec();
8747        s.membros[0].caixa = "Catalog".into();
8748        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8749        let err = s.validate().unwrap_err();
8750        assert!(
8751            matches!(
8752                err,
8753                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8754            ),
8755            "got {err:?}"
8756        );
8757    }
8758
8759    #[test]
8760    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8761        // The diagnostic-shape pin: the error names the offending
8762        // `:caixa` value verbatim so the author can grep their
8763        // caixa.lisp without re-running the build, and carries a
8764        // non-empty `reason` naming the specific violation. Same
8765        // shape every typed-shape gate enshrines (c7d05ec's
8766        // `entrada_host_diagnostic_carries_offending_host`,
8767        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8768        let mut s = three_member_spec();
8769        s.membros[2].caixa = "BAD_NAME".into();
8770        let err = s.validate().unwrap_err();
8771        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8772            panic!("expected MembroCaixaInvalid");
8773        };
8774        assert_eq!(caixa, "BAD_NAME");
8775        assert!(
8776            !reason.is_empty(),
8777            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8778        );
8779    }
8780
8781    #[test]
8782    fn rejects_contrato_with_unknown_de() {
8783        let mut s = three_member_spec();
8784        s.contratos.push(contract_http("phantom", "catalog", "/x"));
8785        let err = s.validate().unwrap_err();
8786        assert!(
8787            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8788        );
8789    }
8790
8791    #[test]
8792    fn rejects_contrato_with_unknown_para() {
8793        let mut s = three_member_spec();
8794        s.contratos.push(contract_http("cart", "phantom", "/x"));
8795        let err = s.validate().unwrap_err();
8796        assert!(
8797            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8798        );
8799    }
8800
8801    #[test]
8802    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8803        // The read-path pin: the phantom-`:de` refusal arm's
8804        // `ContratoMemberMissing.caixa` carrier must be observed through
8805        // the lifted [`WitContract::source`] accessor, not the raw
8806        // `.de.clone()` field-access `String`-carry. Peer of the sibling
8807        // per-`:contratos` self-loop arm's `.source().to_string()` /
8808        // `.world_ref().to_string()` `String`-carry sites the earlier
8809        // convergence lifted onto the same accessor pair. A future
8810        // silent detour that reintroduced the raw `.de.clone()` at the
8811        // wrap envelope while the shape-gate and membership lookup
8812        // routed through the accessor would surface here as a byte-equal
8813        // miss between the fired diagnostic's `caixa:` field and the
8814        // offending edge's `.source()` — pinning the accessor as the
8815        // sole read path across the phantom-name refusal arm's arg +
8816        // wrap-envelope emit surface.
8817        let mut s = three_member_spec();
8818        let phantom = contract_http("phantom", "catalog", "/x");
8819        s.contratos.push(phantom.clone());
8820        let err = s.validate().unwrap_err();
8821        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8822            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8823        };
8824        assert_eq!(
8825            caixa,
8826            phantom.source(),
8827            "ContratoMemberMissing.caixa on the phantom-:de arm must \
8828             byte-equal WitContract::source — the wrap envelope must \
8829             route through the lifted accessor rather than the raw \
8830             .de.clone() field-access String-carry"
8831        );
8832    }
8833
8834    #[test]
8835    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8836        // The symmetric read-path pin on the `:para` phantom-name
8837        // refusal arm — same shape as the sibling `:de` pin above but
8838        // on the callee-Servico axis. Pins the wrap envelope's
8839        // `caixa:` field is observed through the lifted
8840        // [`WitContract::destination`] accessor, not the raw
8841        // `.para.clone()` field-access `String`-carry.
8842        let mut s = three_member_spec();
8843        let phantom = contract_http("cart", "phantom", "/x");
8844        s.contratos.push(phantom.clone());
8845        let err = s.validate().unwrap_err();
8846        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8847            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8848        };
8849        assert_eq!(
8850            caixa,
8851            phantom.destination(),
8852            "ContratoMemberMissing.caixa on the phantom-:para arm must \
8853             byte-equal WitContract::destination — the wrap envelope \
8854             must route through the lifted accessor rather than the raw \
8855             .para.clone() field-access String-carry"
8856        );
8857    }
8858
8859    #[test]
8860    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8861        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8862        // refusal arm — the `validate_contrato_caixa` arg must be
8863        // observed through the lifted [`WitContract::source`] accessor,
8864        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8865        // value routes through the shared
8866        // [`crate::render::require_valid_dns_1123_label`] floor with the
8867        // accessor-projected value; the fired
8868        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8869        // the offending edge's `.source()`, pinning that the arg + the
8870        // downstream `caixa: caixa.to_string()` wrap route through the
8871        // same accessor's read path.
8872        let mut s = three_member_spec();
8873        let malformed = contract_http("BAD_NAME", "catalog", "/x");
8874        s.contratos.push(malformed.clone());
8875        let err = s.validate().unwrap_err();
8876        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8877            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8878        };
8879        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8880        assert_eq!(
8881            caixa,
8882            malformed.source(),
8883            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8884             byte-equal WitContract::source — the shape-gate arg + wrap \
8885             envelope must route through the lifted accessor rather \
8886             than the raw &c.de &String-borrow"
8887        );
8888    }
8889
8890    #[test]
8891    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8892        // Symmetric arm to the sibling `:de` malformed-shape pin above,
8893        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8894        // route through the lifted [`WitContract::destination`]
8895        // accessor. `:para` runs after the `:de` shape gate in the
8896        // canonical edge-direction order, so the `:de` value must be
8897        // well-shaped for the `:para` gate to fire — the `cart` :de is
8898        // canonical.
8899        let mut s = three_member_spec();
8900        let malformed = contract_http("cart", "BAD_NAME", "/x");
8901        s.contratos.push(malformed.clone());
8902        let err = s.validate().unwrap_err();
8903        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8904            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8905        };
8906        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8907        assert_eq!(
8908            caixa,
8909            malformed.destination(),
8910            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8911             byte-equal WitContract::destination — the shape-gate arg + \
8912             wrap envelope must route through the lifted accessor \
8913             rather than the raw &c.para &String-borrow"
8914        );
8915    }
8916
8917    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8918
8919    #[test]
8920    fn rejects_contrato_de_empty() {
8921        // `:de ""` previously fell through to `ContratoMemberMissing`
8922        // (with `caixa: ""`) because the validated `:membros :caixa`
8923        // set never contains the empty string. The narrower
8924        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8925        // the offending slot.
8926        let mut s = three_member_spec();
8927        s.contratos.push(contract_http("", "catalog", "/x"));
8928        let err = s.validate().unwrap_err();
8929        assert_eq!(
8930            err,
8931            AplicacaoError::ContratoCaixaEmpty {
8932                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8933            },
8934            "got {err:?}"
8935        );
8936    }
8937
8938    #[test]
8939    fn rejects_contrato_para_empty() {
8940        // Symmetric arm to `:de ""` — `:para ""` previously fell
8941        // through to `ContratoMemberMissing { caixa: "" }`.
8942        let mut s = three_member_spec();
8943        s.contratos.push(contract_http("cart", "", "/x"));
8944        let err = s.validate().unwrap_err();
8945        assert_eq!(
8946            err,
8947            AplicacaoError::ContratoCaixaEmpty {
8948                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8949            },
8950            "got {err:?}"
8951        );
8952    }
8953
8954    #[test]
8955    fn rejects_contrato_de_with_uppercase() {
8956        // The canonical "I copied the Servico's TitleCase display
8957        // name from an ADR" typo. Until this gate landed `:de "Cart"`
8958        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8959        // as "this caixa isn't in `:membros`" when the root cause is
8960        // "this `:de` value's shape can never legitimately match a
8961        // validated member (DNS-1123 labels are lowercase)". The
8962        // narrower diagnostic names the offending slot, the value
8963        // verbatim, and the parser-shaped reason.
8964        let mut s = three_member_spec();
8965        s.contratos.push(contract_http("Cart", "catalog", "/x"));
8966        let err = s.validate().unwrap_err();
8967        let AplicacaoError::ContratoCaixaInvalid {
8968            slot,
8969            caixa,
8970            reason,
8971        } = err
8972        else {
8973            panic!("expected ContratoCaixaInvalid, got other variant");
8974        };
8975        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8976        assert_eq!(caixa, "Cart");
8977        assert!(
8978            reason.contains("uppercase"),
8979            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8980        );
8981    }
8982
8983    #[test]
8984    fn rejects_contrato_para_with_underscore() {
8985        // The canonical "I'm thinking of a Python module" leak —
8986        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8987        // Pin the `:para` axis surfaces the same diagnostic shape as
8988        // the `:de` axis on the underscore violation.
8989        let mut s = three_member_spec();
8990        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8991        let err = s.validate().unwrap_err();
8992        assert!(
8993            matches!(
8994                err,
8995                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8996                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8997            ),
8998            "got {err:?}"
8999        );
9000    }
9001
9002    #[test]
9003    fn rejects_contrato_de_with_dot() {
9004        // A `:contratos :de` value is a single DNS-1123 *label*, not
9005        // a subdomain — mirroring the `:membros :caixa` floor. The
9006        // strictest floor among the use sites wins.
9007        let mut s = three_member_spec();
9008        s.contratos
9009            .push(contract_http("team.cart", "catalog", "/x"));
9010        let err = s.validate().unwrap_err();
9011        assert!(
9012            matches!(
9013                err,
9014                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9015                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9016            ),
9017            "got {err:?}"
9018        );
9019    }
9020
9021    #[test]
9022    fn rejects_contrato_para_with_unicode() {
9023        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9024        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9025        // validity check rejects multi-byte UTF-8 by the first
9026        // non-`[a-z0-9-]` byte.
9027        let mut s = three_member_spec();
9028        s.contratos.push(contract_http("cart", "café", "/x"));
9029        let err = s.validate().unwrap_err();
9030        assert!(
9031            matches!(
9032                err,
9033                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9034                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9035            ),
9036            "got {err:?}"
9037        );
9038    }
9039
9040    #[test]
9041    fn rejects_contrato_de_with_leading_hyphen() {
9042        // DNS-1123 boundary rule: labels must start and end with an
9043        // alphanumeric. K8s rejects `-cart` outright; the narrower
9044        // shape diagnostic now names the violation at caixa-build
9045        // time rather than the misframed membership-lookup arm.
9046        let mut s = three_member_spec();
9047        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9048        let err = s.validate().unwrap_err();
9049        assert!(
9050            matches!(
9051                err,
9052                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9053                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9054            ),
9055            "got {err:?}"
9056        );
9057    }
9058
9059    #[test]
9060    fn contrato_de_empty_takes_precedence_over_invalid() {
9061        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9062        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9063        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9064        // / `validate_entrada_host` already establish on their peer
9065        // name axes. The empty string is a structurally distinct
9066        // authoring footgun (the author left the field blank, vs.
9067        // typed a malformed value), so it gets its own diagnostic.
9068        let mut s = three_member_spec();
9069        s.contratos.push(contract_http("", "catalog", "/x"));
9070        let err = s.validate().unwrap_err();
9071        assert_eq!(
9072            err,
9073            AplicacaoError::ContratoCaixaEmpty {
9074                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9075            }
9076        );
9077    }
9078
9079    #[test]
9080    fn contrato_de_shape_fires_before_para_shape() {
9081        // Per-axis order pin: within one `:contratos` entry, the `:de`
9082        // shape gate fires before the `:para` shape gate — same
9083        // edge-direction order the existing `ContratoMemberMissing` /
9084        // `ContratoSelfLoop` / target-dispatch checks use, so the
9085        // diagnostic for a contract with both `:de` and `:para`
9086        // malformed is stable. Authors fixing the surfaced `:de`
9087        // first will see `:para`'s diagnostic on re-run.
9088        let mut s = three_member_spec();
9089        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9090        let err = s.validate().unwrap_err();
9091        assert!(
9092            matches!(
9093                err,
9094                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9095                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9096            ),
9097            "got {err:?}"
9098        );
9099    }
9100
9101    #[test]
9102    fn contrato_shape_fires_before_membership_lookup() {
9103        // The load-bearing pin: an invalid-shape `:de` surfaces its
9104        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9105        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9106        // an invalid-shape `:de` could never legitimately match any
9107        // member — the prior `ContratoMemberMissing` diagnostic was
9108        // a structural impossibility framed as a graph-membership
9109        // failure. The shape gate now routes every such input through
9110        // the narrower self-locating diagnostic.
9111        let mut s = three_member_spec();
9112        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9113        let err = s.validate().unwrap_err();
9114        assert!(
9115            matches!(
9116                err,
9117                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9118            ),
9119            "got {err:?}"
9120        );
9121        // And the symmetric case: an invalid-shape `:para` surfaces
9122        // its own diagnostic too, even when `:de` is well-shaped.
9123        let mut s = three_member_spec();
9124        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9125        let err = s.validate().unwrap_err();
9126        assert!(
9127            matches!(
9128                err,
9129                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9130            ),
9131            "got {err:?}"
9132        );
9133    }
9134
9135    #[test]
9136    fn contrato_shape_fires_before_self_edge_check() {
9137        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9138        // bugs: the shape violation (uppercase) and the self-edge
9139        // violation. The narrower per-axis shape diagnostic surfaces
9140        // first because fixing the shape may reveal that the author
9141        // also meant to point `:para` at a different member — the
9142        // self-edge framing is only useful once both endpoints have
9143        // valid shape.
9144        let mut s = three_member_spec();
9145        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9146        let err = s.validate().unwrap_err();
9147        assert!(
9148            matches!(
9149                err,
9150                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9151                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9152            ),
9153            "got {err:?}"
9154        );
9155    }
9156
9157    #[test]
9158    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9159        // Strict-improvement pin: a well-shaped `:de` that simply
9160        // isn't in `:membros` (a phantom reference — author meant
9161        // to add the member but didn't, or renamed and missed an
9162        // update) still surfaces `ContratoMemberMissing`, unchanged.
9163        // The shape gate only intercepts inputs that could never
9164        // legitimately match a validated member; legitimately-shaped
9165        // phantom references remain on the graph-membership axis.
9166        let mut s = three_member_spec();
9167        s.contratos
9168            .push(contract_http("phantom-shim", "catalog", "/x"));
9169        let err = s.validate().unwrap_err();
9170        assert!(
9171            matches!(
9172                err,
9173                AplicacaoError::ContratoMemberMissing { ref caixa }
9174                    if caixa == "phantom-shim"
9175            ),
9176            "got {err:?}"
9177        );
9178    }
9179
9180    #[test]
9181    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9182        // The diagnostic-shape pin: the error names the offending
9183        // slot (`:de` or `:para`) verbatim and the offending value
9184        // verbatim plus a non-empty parser-shaped reason, so the
9185        // author can grep their caixa.lisp for `:de "<name>"` /
9186        // `:para "<name>"` and fix it in one edit. Same diagnostic
9187        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9188        // `PlacementClusterInvalid` (6c8c00b).
9189        let mut s = three_member_spec();
9190        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9191        let err = s.validate().unwrap_err();
9192        let AplicacaoError::ContratoCaixaInvalid {
9193            slot,
9194            caixa,
9195            reason,
9196        } = err
9197        else {
9198            panic!("expected ContratoCaixaInvalid, got {err:?}");
9199        };
9200        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9201        assert_eq!(caixa, "BAD_NAME");
9202        assert!(
9203            !reason.is_empty(),
9204            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9205        );
9206    }
9207
9208    #[test]
9209    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9210        // Scalar-value pin: the two author-facing kebab-case labels the
9211        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9212        // admits on the `:contratos` per-entry endpoint-shape axis,
9213        // one arm per typed sub-slot. Mirrors the peer scalar-value
9214        // pin the sibling top-level M2 / M3 / Supervisor
9215        // author-facing-label consts carry
9216        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9217        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9218        // slot itself), so every altitude of the typed-slot algebra
9219        // shares the same "one canonical byte-string per arm"
9220        // discipline. A future rebrand (`:de` → `:from` matching the
9221        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9222        // sibling, `:para` → `:to` matching the same, or
9223        // `:de`/`:para` → `:source`/`:target` matching the WIT
9224        // world's `import`/`export` half-vocabulary) lands as an
9225        // edit to exactly one const, and every consumer that reaches
9226        // for the label picks it up at build time rather than at
9227        // runtime as a downstream `ContratoCaixaEmpty` /
9228        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9229        // diagnostic mismatch far from the rename's commit.
9230        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9231        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9232    }
9233
9234    #[test]
9235    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9236        // Production-through-const pin: the two per-axis labels the
9237        // per-`:contratos` entry endpoint-shape gate at
9238        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9239        // argument to [`validate_contrato_caixa`] route through the
9240        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9241        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9242        // future rebrand that reaches the const but not the gate (or
9243        // vice versa) surfaces here at build time rather than at
9244        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9245        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9246        // commit. Mirror of the peer
9247        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9248        // pin (882f498) on the sibling M3 top-level slot axis.
9249        let mut s = three_member_spec();
9250        s.contratos.push(contract_http("", "catalog", "/x"));
9251        assert_eq!(
9252            s.validate().unwrap_err(),
9253            AplicacaoError::ContratoCaixaEmpty {
9254                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9255            }
9256        );
9257        let mut s = three_member_spec();
9258        s.contratos.push(contract_http("cart", "", "/x"));
9259        assert_eq!(
9260            s.validate().unwrap_err(),
9261            AplicacaoError::ContratoCaixaEmpty {
9262                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9263            }
9264        );
9265    }
9266
9267    #[test]
9268    fn accepts_canonical_contrato_caixa_forms() {
9269        // The DNS-1123 label shapes a caixa author is realistically
9270        // going to write on a `:contratos :de` / `:para`. Pin every
9271        // leg so a future tightening that bans (e.g.) digit-start
9272        // identifiers surfaces here, mirroring
9273        // `accepts_canonical_membro_caixa_forms` on the peer name
9274        // axis.
9275        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9276            let mut s = three_member_spec();
9277            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9278            s.contratos = vec![contract_http("checkout", form, "/x")];
9279            s.entrada = None;
9280            s.validate().unwrap_or_else(|e| {
9281                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9282            });
9283
9284            let mut s = three_member_spec();
9285            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9286            s.contratos = vec![contract_http(form, "catalog", "/x")];
9287            s.entrada = None;
9288            s.validate().unwrap_or_else(|e| {
9289                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9290            });
9291        }
9292    }
9293
9294    #[test]
9295    fn rejects_empty_wit() {
9296        let mut s = three_member_spec();
9297        s.contratos.push(WitContract {
9298            de: "cart".into(),
9299            para: "catalog".into(),
9300            wit: "".into(),
9301            endpoint: None,
9302            subject: None,
9303            slot: None,
9304        });
9305        let err = s.validate().unwrap_err();
9306        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9307    }
9308
9309    #[test]
9310    fn rejects_entrada_to_unknown_member() {
9311        let mut s = three_member_spec();
9312        s.entrada.as_mut().unwrap().para = "phantom".into();
9313        assert!(matches!(
9314            s.validate().unwrap_err(),
9315            AplicacaoError::EntradaMemberMissing { .. }
9316        ));
9317    }
9318
9319    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9320
9321    #[test]
9322    fn rejects_entrada_para_empty() {
9323        // `:para ""` previously fell through to
9324        // `EntradaMemberMissing { para: "" }` because the validated
9325        // `:membros :caixa` set never contains the empty string. The
9326        // narrower `EntradaParaEmpty` diagnostic now names the
9327        // offending slot directly — same empty-first cascade
9328        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9329        // `ContratoCaixaEmpty` establish on the peer name axes.
9330        let mut s = three_member_spec();
9331        s.entrada.as_mut().unwrap().para = String::new();
9332        let err = s.validate().unwrap_err();
9333        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9334    }
9335
9336    #[test]
9337    fn rejects_entrada_para_with_uppercase() {
9338        // The canonical "I copied the Servico's TitleCase display
9339        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9340        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9341        // as "this caixa isn't in `:membros`" when the root cause is
9342        // "this `:para` value's shape can never legitimately match a
9343        // validated member (DNS-1123 labels are lowercase)". The
9344        // narrower diagnostic names the value verbatim plus the
9345        // parser-shaped reason.
9346        let mut s = three_member_spec();
9347        s.entrada.as_mut().unwrap().para = "Cart".into();
9348        let err = s.validate().unwrap_err();
9349        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9350            panic!("expected EntradaParaInvalid, got other variant");
9351        };
9352        assert_eq!(para, "Cart");
9353        assert!(
9354            reason.contains("uppercase"),
9355            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9356        );
9357    }
9358
9359    #[test]
9360    fn rejects_entrada_para_with_underscore() {
9361        // The canonical "I'm thinking of a Python module" leak —
9362        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9363        let mut s = three_member_spec();
9364        s.entrada.as_mut().unwrap().para = "my_cart".into();
9365        let err = s.validate().unwrap_err();
9366        assert!(
9367            matches!(
9368                err,
9369                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9370                    if para == "my_cart" && reason.contains('_')
9371            ),
9372            "got {err:?}"
9373        );
9374    }
9375
9376    #[test]
9377    fn rejects_entrada_para_with_dot() {
9378        // An `:entrada :para` value is a single DNS-1123 *label*, not
9379        // a subdomain — mirroring the `:membros :caixa` floor. The
9380        // strictest floor among the use sites wins.
9381        let mut s = three_member_spec();
9382        s.entrada.as_mut().unwrap().para = "team.cart".into();
9383        let err = s.validate().unwrap_err();
9384        assert!(
9385            matches!(
9386                err,
9387                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9388                    if para == "team.cart" && reason.contains('.')
9389            ),
9390            "got {err:?}"
9391        );
9392    }
9393
9394    #[test]
9395    fn rejects_entrada_para_with_unicode() {
9396        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9397        // (`xn--…`) before it reaches K8s.
9398        let mut s = three_member_spec();
9399        s.entrada.as_mut().unwrap().para = "café".into();
9400        let err = s.validate().unwrap_err();
9401        assert!(
9402            matches!(
9403                err,
9404                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9405            ),
9406            "got {err:?}"
9407        );
9408    }
9409
9410    #[test]
9411    fn rejects_entrada_para_with_leading_hyphen() {
9412        // DNS-1123 boundary rule: labels must start and end with an
9413        // alphanumeric. K8s rejects `-cart` outright.
9414        let mut s = three_member_spec();
9415        s.entrada.as_mut().unwrap().para = "-cart".into();
9416        let err = s.validate().unwrap_err();
9417        assert!(
9418            matches!(
9419                err,
9420                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9421                    if para == "-cart" && reason.contains("start and end")
9422            ),
9423            "got {err:?}"
9424        );
9425    }
9426
9427    #[test]
9428    fn rejects_entrada_para_with_trailing_hyphen() {
9429        // Symmetric boundary arm.
9430        let mut s = three_member_spec();
9431        s.entrada.as_mut().unwrap().para = "cart-".into();
9432        let err = s.validate().unwrap_err();
9433        assert!(
9434            matches!(
9435                err,
9436                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9437                    if para == "cart-" && reason.contains("start and end")
9438            ),
9439            "got {err:?}"
9440        );
9441    }
9442
9443    #[test]
9444    fn rejects_entrada_para_too_long() {
9445        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9446        // bytes per label. K8s rejects longer names at admission on
9447        // every `metadata.name` axis.
9448        let mut s = three_member_spec();
9449        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9450        let err = s.validate().unwrap_err();
9451        assert!(
9452            matches!(
9453                err,
9454                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9455                    if para.len() == 64 && reason.contains("max length")
9456            ),
9457            "got {err:?}"
9458        );
9459    }
9460
9461    #[test]
9462    fn entrada_para_empty_takes_precedence_over_invalid() {
9463        // Order pin: the `EntradaParaEmpty` arm fires before the
9464        // `EntradaParaInvalid` parse-side arm — same empty-first
9465        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9466        // / `validate_contrato_caixa` already establish.
9467        let mut s = three_member_spec();
9468        s.entrada.as_mut().unwrap().para = String::new();
9469        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9470    }
9471
9472    #[test]
9473    fn entrada_para_shape_fires_before_membership_lookup() {
9474        // The load-bearing pin: an invalid-shape `:para` surfaces its
9475        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9476        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9477        // an invalid-shape `:para` could never legitimately match any
9478        // member — the prior `EntradaMemberMissing` diagnostic framed
9479        // a structural impossibility as a graph-membership failure.
9480        let mut s = three_member_spec();
9481        s.entrada.as_mut().unwrap().para = "Cart".into();
9482        let err = s.validate().unwrap_err();
9483        assert!(
9484            matches!(
9485                err,
9486                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9487            ),
9488            "got {err:?}"
9489        );
9490    }
9491
9492    #[test]
9493    fn entrada_para_shape_fires_before_host_gate() {
9494        // Per-`:entrada` order pin: the `:para` shape gate fires
9495        // before the `:host` gate, mirroring the existing
9496        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9497        // ordering where the member-lookup arm preceded the host gate.
9498        // The shape gate slots ahead of that, so a malformed `:para`
9499        // surfaces its own diagnostic even when `:host` is also wrong.
9500        let mut s = three_member_spec();
9501        let e = s.entrada.as_mut().unwrap();
9502        e.para = "Cart".into();
9503        e.host = "BAD HOST".into();
9504        let err = s.validate().unwrap_err();
9505        assert!(
9506            matches!(
9507                err,
9508                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9509            ),
9510            "got {err:?}"
9511        );
9512    }
9513
9514    #[test]
9515    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9516        // Strict-improvement pin: a well-shaped `:para` that simply
9517        // isn't in `:membros` (a phantom reference — author meant to
9518        // add the member but didn't, or renamed and missed an
9519        // update) still surfaces `EntradaMemberMissing`, unchanged.
9520        // The shape gate only intercepts inputs that could never
9521        // legitimately match a validated member.
9522        let mut s = three_member_spec();
9523        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9524        let err = s.validate().unwrap_err();
9525        assert!(
9526            matches!(
9527                err,
9528                AplicacaoError::EntradaMemberMissing { ref para }
9529                    if para == "phantom-shim"
9530            ),
9531            "got {err:?}"
9532        );
9533    }
9534
9535    #[test]
9536    fn entrada_para_invalid_diagnostic_carries_offending_para() {
9537        // The diagnostic-shape pin: the error names the offending
9538        // `:para` value verbatim plus a non-empty parser-shaped
9539        // reason, so the author can grep their caixa.lisp for
9540        // `:para "<name>"` and fix it in one edit. Same diagnostic
9541        // shape as `MembroCaixaInvalid` (3f9d7a0),
9542        // `PlacementClusterInvalid` (6c8c00b), and
9543        // `ContratoCaixaInvalid` (8d5af6b).
9544        let mut s = three_member_spec();
9545        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9546        let err = s.validate().unwrap_err();
9547        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9548            panic!("expected EntradaParaInvalid, got {err:?}");
9549        };
9550        assert_eq!(para, "BAD_NAME");
9551        assert!(
9552            !reason.is_empty(),
9553            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9554        );
9555    }
9556
9557    #[test]
9558    fn accepts_canonical_entrada_para_forms() {
9559        // Positive-control sweep covering the DNS-1123 label shapes a
9560        // caixa author is realistically going to write on `:entrada
9561        // :para`. Pin every leg so a future tightening that bans
9562        // (e.g.) digit-start identifiers surfaces here, mirroring
9563        // `accepts_canonical_membro_caixa_forms` and
9564        // `accepts_canonical_contrato_caixa_forms` on the peer name
9565        // axes.
9566        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9567            let mut s = three_member_spec();
9568            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9569            s.contratos = vec![contract_http(form, "catalog", "/x")];
9570            s.entrada = Some(Entrada {
9571                host: "checkout.quero.cloud".into(),
9572                para: form.into(),
9573                paths: vec!["/api".into()],
9574                port: 8080,
9575            });
9576            s.validate().unwrap_or_else(|e| {
9577                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9578            });
9579        }
9580    }
9581
9582    #[test]
9583    fn rejects_replicated_without_clusters() {
9584        let mut s = three_member_spec();
9585        s.placement.clusters = vec![];
9586        assert!(matches!(
9587            s.validate().unwrap_err(),
9588            AplicacaoError::PlacementWithoutClusters { .. }
9589        ));
9590    }
9591
9592    #[test]
9593    fn rejects_sharded_without_key() {
9594        let mut s = three_member_spec();
9595        s.placement.estrategia = PlacementStrategy::Sharded;
9596        s.placement.shard_key = None;
9597        s.placement.clusters = vec!["rio".into()];
9598        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9599    }
9600
9601    #[test]
9602    fn sharded_with_key_validates() {
9603        let mut s = three_member_spec();
9604        s.placement.estrategia = PlacementStrategy::Sharded;
9605        s.placement.shard_key = Some("$tenantId".into());
9606        s.validate().unwrap();
9607    }
9608
9609    #[test]
9610    fn round_trip_via_json_preserves_shape() {
9611        let s = three_member_spec();
9612        let json = serde_json::to_string(&s.membros).unwrap();
9613        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9614        assert_eq!(back, s.membros);
9615
9616        let json = serde_json::to_string(&s.contratos).unwrap();
9617        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9618        assert_eq!(back, s.contratos);
9619
9620        let json = serde_json::to_string(&s.placement).unwrap();
9621        let back: Placement = serde_json::from_str(&json).unwrap();
9622        assert_eq!(back, s.placement);
9623
9624        let json = serde_json::to_string(&s.entrada).unwrap();
9625        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9626        assert_eq!(back, s.entrada);
9627    }
9628
9629    #[test]
9630    fn rate_limit_round_trip_seconds() {
9631        let policy = MeshPolicy {
9632            rate_limit: Some(RateLimit {
9633                rate: 100,
9634                window: Duration::from_secs(1),
9635            }),
9636            ..Default::default()
9637        };
9638        let json = serde_json::to_string(&policy).unwrap();
9639        assert!(json.contains("\"100/s\""));
9640        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9641        assert_eq!(back.rate_limit.unwrap().rate, 100);
9642        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9643    }
9644
9645    #[test]
9646    fn rate_limit_round_trip_minutes() {
9647        let policy = MeshPolicy {
9648            rate_limit: Some(RateLimit {
9649                rate: 5000,
9650                window: Duration::from_secs(60),
9651            }),
9652            ..Default::default()
9653        };
9654        let json = serde_json::to_string(&policy).unwrap();
9655        assert!(json.contains("\"5000/m\""));
9656    }
9657
9658    #[test]
9659    fn circuit_breaker_round_trip() {
9660        let policy = MeshPolicy {
9661            circuit_breaker: Some(CircuitBreaker {
9662                max_failures: 5,
9663                window: Duration::from_secs(60),
9664            }),
9665            ..Default::default()
9666        };
9667        let json = serde_json::to_string(&policy).unwrap();
9668        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9669        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9670        assert_eq!(
9671            back.circuit_breaker.unwrap().window,
9672            Duration::from_secs(60)
9673        );
9674    }
9675
9676    #[test]
9677    fn rejects_http_contrato_without_endpoint() {
9678        let mut s = three_member_spec();
9679        s.contratos.push(WitContract {
9680            de: "cart".into(),
9681            para: "catalog".into(),
9682            wit: "wasi:http/proxy".into(),
9683            endpoint: None,
9684            subject: None,
9685            slot: None,
9686        });
9687        let err = s.validate().unwrap_err();
9688        assert!(matches!(
9689            err,
9690            AplicacaoError::ContratoMissingTarget {
9691                expected: WitTarget::HTTP_FIELD_NAME,
9692                ..
9693            }
9694        ));
9695    }
9696
9697    #[test]
9698    fn rejects_http_contrato_with_subject() {
9699        let mut s = three_member_spec();
9700        s.contratos.push(WitContract {
9701            de: "cart".into(),
9702            para: "catalog".into(),
9703            wit: "wasi:http/proxy".into(),
9704            endpoint: Some("/x".into()),
9705            subject: Some("not.allowed.here".into()),
9706            slot: None,
9707        });
9708        let err = s.validate().unwrap_err();
9709        assert!(matches!(
9710            err,
9711            AplicacaoError::ContratoWrongTarget {
9712                expected: WitTarget::HTTP_FIELD_NAME,
9713                ..
9714            }
9715        ));
9716    }
9717
9718    #[test]
9719    fn rejects_pubsub_contrato_without_subject() {
9720        let mut s = three_member_spec();
9721        s.contratos.push(WitContract {
9722            de: "cart".into(),
9723            para: "catalog".into(),
9724            wit: "nats:pub-sub".into(),
9725            endpoint: None,
9726            subject: None,
9727            slot: None,
9728        });
9729        let err = s.validate().unwrap_err();
9730        assert!(matches!(
9731            err,
9732            AplicacaoError::ContratoMissingTarget {
9733                expected: WitTarget::PUBSUB_FIELD_NAME,
9734                ..
9735            }
9736        ));
9737    }
9738
9739    #[test]
9740    fn rejects_pubsub_contrato_with_endpoint() {
9741        let mut s = three_member_spec();
9742        s.contratos.push(WitContract {
9743            de: "cart".into(),
9744            para: "catalog".into(),
9745            wit: "kafka:topic".into(),
9746            endpoint: Some("/wrong".into()),
9747            subject: Some("topic.x".into()),
9748            slot: None,
9749        });
9750        let err = s.validate().unwrap_err();
9751        assert!(matches!(
9752            err,
9753            AplicacaoError::ContratoWrongTarget {
9754                expected: WitTarget::PUBSUB_FIELD_NAME,
9755                ..
9756            }
9757        ));
9758    }
9759
9760    #[test]
9761    fn rejects_store_contrato_without_slot() {
9762        let mut s = three_member_spec();
9763        s.contratos.push(WitContract {
9764            de: "cart".into(),
9765            para: "catalog".into(),
9766            wit: "wasi:keyvalue/store".into(),
9767            endpoint: None,
9768            subject: None,
9769            slot: None,
9770        });
9771        let err = s.validate().unwrap_err();
9772        assert!(matches!(
9773            err,
9774            AplicacaoError::ContratoMissingTarget {
9775                expected: WitTarget::STORE_FIELD_NAME,
9776                ..
9777            }
9778        ));
9779    }
9780
9781    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9782
9783    #[test]
9784    fn rejects_http_contrato_with_empty_endpoint() {
9785        // `Some("")` for an HTTP endpoint passes the presence check
9786        // (target() previously returned WitTarget::Http { endpoint: "" })
9787        // but renders as a `path: ""` Cilium L7 rule that matches no
9788        // traffic. Same value-shape footgun closed for :entrada :paths
9789        // entries (eb3456d).
9790        let mut s = three_member_spec();
9791        s.contratos.push(WitContract {
9792            de: "cart".into(),
9793            para: "catalog".into(),
9794            wit: "wasi:http/proxy".into(),
9795            endpoint: Some(String::new()),
9796            subject: None,
9797            slot: None,
9798        });
9799        let err = s.validate().unwrap_err();
9800        assert!(
9801            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9802                if de == "cart" && para == "catalog"),
9803            "got {err:?}"
9804        );
9805    }
9806
9807    #[test]
9808    fn rejects_http_contrato_with_relative_endpoint() {
9809        // Cilium L7 :path + Gateway API PathPrefix both require a
9810        // leading `/`. Same shape required of :entrada :paths
9811        // (eb3456d). Lifted into target() so every consumer of the
9812        // typed WitTarget view inherits the guarantee.
9813        let mut s = three_member_spec();
9814        s.contratos.push(WitContract {
9815            de: "cart".into(),
9816            para: "catalog".into(),
9817            wit: "wasi:http/proxy".into(),
9818            endpoint: Some("products/:id".into()),
9819            subject: None,
9820            slot: None,
9821        });
9822        let err = s.validate().unwrap_err();
9823        assert!(
9824            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9825                if endpoint == "products/:id"),
9826            "got {err:?}"
9827        );
9828    }
9829
9830    #[test]
9831    fn rejects_pubsub_contrato_with_empty_subject() {
9832        // NATS / Kafka publish without a subject is a no-op subscribe;
9833        // never the author's intent. Same empty-string rejection as
9834        // :membros :caixa, :placement :clusters entries, :entrada
9835        // :paths entries — every value carried by every typed slot is
9836        // value-shape-checked at validate().
9837        let mut s = three_member_spec();
9838        s.contratos.push(WitContract {
9839            de: "cart".into(),
9840            para: "catalog".into(),
9841            wit: "nats:pub-sub".into(),
9842            endpoint: None,
9843            subject: Some(String::new()),
9844            slot: None,
9845        });
9846        let err = s.validate().unwrap_err();
9847        assert!(
9848            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9849                if de == "cart" && para == "catalog"),
9850            "got {err:?}"
9851        );
9852    }
9853
9854    #[test]
9855    fn rejects_store_contrato_with_empty_slot() {
9856        // An empty slot template addresses the bucket root, defeating
9857        // the per-key isolation the slot exists for — a footgun on
9858        // `wasi:keyvalue/store` whose closest analog is the empty
9859        // shard-key rejected on :placement Sharded (c7c7799).
9860        let mut s = three_member_spec();
9861        s.contratos.push(WitContract {
9862            de: "cart".into(),
9863            para: "catalog".into(),
9864            wit: "wasi:keyvalue/store".into(),
9865            endpoint: None,
9866            subject: None,
9867            slot: Some(String::new()),
9868        });
9869        let err = s.validate().unwrap_err();
9870        assert!(
9871            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9872                if de == "cart" && para == "catalog"),
9873            "got {err:?}"
9874        );
9875    }
9876
9877    #[test]
9878    fn http_contrato_root_endpoint_validates() {
9879        // Pin the boundary case: a single-`/` endpoint is the catch-all
9880        // form the Gateway HTTPRoute renderer falls back to when
9881        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9882        // must remain a valid contrato endpoint too.
9883        let mut s = three_member_spec();
9884        s.contratos.push(contract_http("cart", "catalog", "/"));
9885        s.validate().unwrap();
9886    }
9887
9888    // ── :contratos :endpoint value-shape gate ────────────────────────────
9889    //
9890    // Mirrors the `:entrada :paths` value-shape suite on the peer
9891    // HTTP-path axis. Until this gate landed `WitContract::target()`
9892    // only refused the empty string + the missing-leading-`/` form
9893    // (c4213a4); a structurally invalid endpoint passed validate and
9894    // landed verbatim as a Cilium L7 `path:` rule
9895    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9896    // traffic or was rejected at apply time by Cilium policy admission.
9897    // Every authoring footgun the K8s Gateway API webhook / Cilium
9898    // policy validator would catch on admission now becomes a caixa-
9899    // build-time `ContratoEndpointInvalid` with the offending
9900    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9901    // shape as `EntradaPathInvalid` on the sibling axis; same shared
9902    // predicate (`crate::render::is_gateway_api_http_path`) ensures
9903    // drift between the two axes' rule enforcement is a build error
9904    // at the predicate.
9905
9906    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9907        // Fresh spec per call so the would-be-duplicate edge
9908        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9909        // `three_member_spec`'s pre-existing
9910        // `(cart, catalog, …, /products/:id)` entry — only the
9911        // endpoint payload differs.
9912        let mut s = three_member_spec();
9913        s.contratos.push(contract_http("cart", "catalog", ep));
9914        s.validate().unwrap_err()
9915    }
9916
9917    #[test]
9918    fn rejects_http_contrato_endpoint_with_query() {
9919        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9920        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9921        // rule the L7 matcher would never satisfy.
9922        let err = contrato_endpoint_err("/charge?token=X");
9923        assert!(
9924            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9925                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9926            "got {err:?}"
9927        );
9928    }
9929
9930    #[test]
9931    fn rejects_http_contrato_endpoint_with_fragment() {
9932        let err = contrato_endpoint_err("/charge#frag");
9933        assert!(
9934            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9935                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9936            "got {err:?}"
9937        );
9938    }
9939
9940    #[test]
9941    fn rejects_http_contrato_endpoint_with_whitespace() {
9942        let err = contrato_endpoint_err("/foo bar");
9943        assert!(
9944            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9945                if endpoint == "/foo bar" && reason.contains("whitespace")),
9946            "got {err:?}"
9947        );
9948    }
9949
9950    #[test]
9951    fn rejects_http_contrato_endpoint_with_control_char() {
9952        let err = contrato_endpoint_err("/api/\x01bar");
9953        assert!(
9954            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9955                if endpoint == "/api/\x01bar" && reason.contains("control character")),
9956            "got {err:?}"
9957        );
9958    }
9959
9960    #[test]
9961    fn rejects_http_contrato_endpoint_with_non_ascii() {
9962        let err = contrato_endpoint_err("/api/café");
9963        assert!(
9964            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9965                if endpoint == "/api/café" && reason.contains("non-ASCII")),
9966            "got {err:?}"
9967        );
9968    }
9969
9970    #[test]
9971    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9972        let err = contrato_endpoint_err("/api//cart");
9973        assert!(
9974            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9975                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9976            "got {err:?}"
9977        );
9978    }
9979
9980    #[test]
9981    fn rejects_http_contrato_endpoint_with_dot_segment() {
9982        let err = contrato_endpoint_err("/api/./cart");
9983        assert!(
9984            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9985                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9986            "got {err:?}"
9987        );
9988    }
9989
9990    #[test]
9991    fn rejects_http_contrato_endpoint_with_parent_segment() {
9992        // Path-traversal in a contrato endpoint is the canonical
9993        // "L7 rule that the workload's HTTP server's path-resolution
9994        // logic interprets differently than the policy enforcer"
9995        // footgun. Rejected outright at validate time.
9996        let err = contrato_endpoint_err("/api/../etc");
9997        assert!(
9998            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9999                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10000            "got {err:?}"
10001        );
10002    }
10003
10004    #[test]
10005    fn rejects_http_contrato_endpoint_too_long() {
10006        // 1025-byte endpoint — one over the Gateway API
10007        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10008        // path matcher has no inherent length limit but the policy
10009        // CR itself rides through the K8s apiserver, which enforces
10010        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10011        // conservative floor.
10012        let big = format!("/api/{}", "a".repeat(1020));
10013        assert_eq!(big.len(), 1025);
10014        let err = contrato_endpoint_err(&big);
10015        assert!(
10016            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10017                if endpoint == &big && reason.contains("max length of 1024")),
10018            "got {err:?}"
10019        );
10020    }
10021
10022    #[test]
10023    fn http_contrato_endpoint_max_length_validates() {
10024        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10025        // in the cap surfaces here and at
10026        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10027        // mirroring `entrada_path_max_length_validates` on the peer
10028        // axis.
10029        let big = format!("/api/{}", "a".repeat(1019));
10030        assert_eq!(big.len(), 1024);
10031        let mut s = three_member_spec();
10032        s.contratos.push(contract_http("cart", "catalog", &big));
10033        s.validate().unwrap();
10034    }
10035
10036    #[test]
10037    fn http_contrato_endpoint_accepts_canonical_forms() {
10038        // Positive-set sweep: every canonical HTTP-path shape the
10039        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10040        // plain paths, hidden-file-style `.config` segments distinct
10041        // from the `.` segment, digit-bearing segments, the canonical
10042        // route-template `:param` form, trailing-slash form,
10043        // percent-encoded segments, the `/foo..bar` interior-`..`-
10044        // substring forms that are NOT `..` segments) must remain a
10045        // valid contrato endpoint too. Drift between this list and
10046        // the entrada path positive sweep surfaces at the shared
10047        // `is_gateway_api_http_path` substrate-side suite — one
10048        // source of truth. Uses a fresh `(payment, catalog)` edge so
10049        // none of the swept endpoints collide with the pre-existing
10050        // `(cart, catalog, /products/:id)` / `(cart, payment,
10051        // /charge)` entries in `three_member_spec`.
10052        for ep in [
10053            "/",
10054            "/charge",
10055            "/v1/charge",
10056            "/api/.config",
10057            "/products/:id",
10058            "/api/cart/",
10059            "/api/caf%C3%A9",
10060            "/foo..bar",
10061            "/...",
10062        ] {
10063            let mut s = three_member_spec();
10064            s.contratos.push(contract_http("payment", "catalog", ep));
10065            s.validate()
10066                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10067        }
10068    }
10069
10070    #[test]
10071    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10072        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10073        // locating diagnostic on `""` and must lead — the value-
10074        // shape gate is only reached after the empty-check fires.
10075        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10076        // on the peer axis.
10077        let mut s = three_member_spec();
10078        s.contratos.push(WitContract {
10079            de: "cart".into(),
10080            para: "catalog".into(),
10081            wit: "wasi:http/proxy".into(),
10082            endpoint: Some(String::new()),
10083            subject: None,
10084            slot: None,
10085        });
10086        let err = s.validate().unwrap_err();
10087        assert!(
10088            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10089            "got {err:?}"
10090        );
10091    }
10092
10093    #[test]
10094    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10095        // Ordering pin: an endpoint without a leading `/` surfaces the
10096        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10097        // value-shape gate is only consulted on endpoints that already
10098        // satisfy the absolute-prefix invariant. Mirrors
10099        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10100        let err = contrato_endpoint_err("bad path");
10101        assert!(
10102            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10103                if endpoint == "bad path"),
10104            "got {err:?}"
10105        );
10106    }
10107
10108    #[test]
10109    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10110        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10111        // `:para` + a non-empty reason flow through verbatim so the
10112        // author can grep their caixa.lisp for the offending contrato
10113        // block and fix it in one edit. Same shape as
10114        // `entrada_path_diagnostic_carries_offending_path`.
10115        let err = contrato_endpoint_err("/api?q=1");
10116        match err {
10117            AplicacaoError::ContratoEndpointInvalid {
10118                de,
10119                para,
10120                endpoint,
10121                reason,
10122            } => {
10123                assert_eq!(de, "cart");
10124                assert_eq!(para, "catalog");
10125                assert_eq!(endpoint, "/api?q=1");
10126                assert!(!reason.is_empty(), "reason field must be non-empty");
10127            }
10128            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10129        }
10130    }
10131
10132    #[test]
10133    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10134        // The compounding theorem: every &str inside a WitTarget
10135        // returned by target() is non-empty (and absolute, for Http).
10136        // Renderers downstream of typed_view() can rely on this
10137        // without re-checking — the type system carries the proof.
10138        let http = contract_http("cart", "catalog", "/x");
10139        match http.target().unwrap() {
10140            WitTarget::Http { endpoint } => {
10141                assert!(!endpoint.is_empty());
10142                assert!(endpoint.starts_with('/'));
10143            }
10144            other => panic!("expected Http, got {other:?}"),
10145        }
10146        let nats = WitContract {
10147            de: "a".into(),
10148            para: "b".into(),
10149            wit: "nats:pub-sub".into(),
10150            endpoint: None,
10151            subject: Some("topic.x".into()),
10152            slot: None,
10153        };
10154        match nats.target().unwrap() {
10155            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10156            other => panic!("expected PubSub, got {other:?}"),
10157        }
10158        let kv = WitContract {
10159            de: "a".into(),
10160            para: "b".into(),
10161            wit: "wasi:keyvalue/store".into(),
10162            endpoint: None,
10163            subject: None,
10164            slot: Some("checkout/$orderId".into()),
10165        };
10166        match kv.target().unwrap() {
10167            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10168            other => panic!("expected Store, got {other:?}"),
10169        }
10170    }
10171
10172    #[test]
10173    fn target_diagnostic_names_offending_endpoint_value() {
10174        // When the malformed endpoint string is non-trivial, the
10175        // diagnostic carries the actual value back to the author —
10176        // not a generic "endpoint malformed" error.
10177        let bad = WitContract {
10178            de: "src".into(),
10179            para: "dst".into(),
10180            wit: "wasi:http/proxy".into(),
10181            endpoint: Some("api/v1/charge".into()),
10182            subject: None,
10183            slot: None,
10184        };
10185        match bad.target().unwrap_err() {
10186            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10187                assert_eq!(de, "src");
10188                assert_eq!(para, "dst");
10189                assert_eq!(endpoint, "api/v1/charge");
10190            }
10191            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10192        }
10193    }
10194
10195    #[test]
10196    fn rejects_unknown_wit_with_target_set() {
10197        let mut s = three_member_spec();
10198        s.contratos.push(WitContract {
10199            de: "cart".into(),
10200            para: "catalog".into(),
10201            wit: "custom:exchange".into(),
10202            endpoint: Some("/leaked".into()),
10203            subject: None,
10204            slot: None,
10205        });
10206        let err = s.validate().unwrap_err();
10207        assert!(matches!(
10208            err,
10209            AplicacaoError::ContratoWrongTarget {
10210                expected: WitTarget::CAPABILITY_EXPECTED,
10211                ..
10212            }
10213        ));
10214    }
10215
10216    #[test]
10217    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10218        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10219        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10220        // fourth arm of the same "which payload field name goes in the
10221        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10222        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10223        // consts cover on the peer HTTP / PubSub / Store arms
10224        // (`wit_target_field_name_pins_per_variant`). Until this lift
10225        // landed the byte-string sat twice — once inline in the
10226        // [`WitContract::target`] Capability-arm rejection at the
10227        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10228        // pinning against the same literal — with no compile-time link
10229        // between them. Same "one canonical declaration, next to the
10230        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10231        // lift established for the payload-less arm's human-readable
10232        // label axis; this test is the shape peer of
10233        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10234        // pair (routes-through-const + scalar-value pin) on the
10235        // wrong-target diagnostic-scalar axis.
10236        //
10237        // Fail-before-pass-after was verified locally by mutating the
10238        // const declaration to `"capability"` — the scalar-value pin
10239        // below fires (`"capability" != "none"`) and the routes-through
10240        // assertion below still holds (production and const walk in
10241        // lockstep), which is the correct behavior: a rename on the
10242        // const drifts here first, not at a downstream consumer.
10243        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10244
10245        let mut s = three_member_spec();
10246        s.contratos.push(WitContract {
10247            de: "cart".into(),
10248            para: "catalog".into(),
10249            wit: "custom:exchange".into(),
10250            endpoint: Some("/leaked".into()),
10251            subject: None,
10252            slot: None,
10253        });
10254        match s.validate().unwrap_err() {
10255            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10256                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10257            }
10258            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10259        }
10260    }
10261
10262    #[test]
10263    fn unknown_wit_capability_only_validates() {
10264        let mut s = three_member_spec();
10265        s.contratos.push(WitContract {
10266            de: "cart".into(),
10267            para: "catalog".into(),
10268            // A WIT world we haven't yet shaped — accept it as a typed
10269            // capability edge so authors aren't blocked while the WIT
10270            // registry catches up. No payload field may be carried.
10271            wit: "custom:exchange".into(),
10272            endpoint: None,
10273            subject: None,
10274            slot: None,
10275        });
10276        s.validate().unwrap();
10277        let added = s.contratos.last().unwrap();
10278        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10279    }
10280
10281    #[test]
10282    fn target_typed_view_round_trips_each_shape() {
10283        let http = contract_http("cart", "catalog", "/products/:id");
10284        assert_eq!(
10285            http.target().unwrap(),
10286            WitTarget::Http {
10287                endpoint: "/products/:id"
10288            }
10289        );
10290        let nats = WitContract {
10291            de: "a".into(),
10292            para: "b".into(),
10293            wit: "nats:pub-sub".into(),
10294            endpoint: None,
10295            subject: Some("topic.x".into()),
10296            slot: None,
10297        };
10298        assert_eq!(
10299            nats.target().unwrap(),
10300            WitTarget::PubSub { subject: "topic.x" }
10301        );
10302        let kv = WitContract {
10303            de: "a".into(),
10304            para: "b".into(),
10305            wit: "wasi:keyvalue/store".into(),
10306            endpoint: None,
10307            subject: None,
10308            slot: Some("checkout/$orderId".into()),
10309        };
10310        assert_eq!(
10311            kv.target().unwrap(),
10312            WitTarget::Store {
10313                slot: "checkout/$orderId"
10314            }
10315        );
10316    }
10317
10318    #[test]
10319    fn wit_contract_kind_predicates() {
10320        let http = contract_http("a", "b", "/x");
10321        assert!(http.is_http());
10322        assert!(!http.is_pubsub());
10323        assert!(!http.is_store());
10324        assert!(!http.is_capability());
10325
10326        let nats = WitContract {
10327            de: "a".into(),
10328            para: "b".into(),
10329            wit: "nats:pub-sub".into(),
10330            endpoint: None,
10331            subject: Some("topic.x".into()),
10332            slot: None,
10333        };
10334        assert!(nats.is_pubsub());
10335        assert!(!nats.is_http());
10336        assert!(!nats.is_capability());
10337
10338        let kv = WitContract {
10339            de: "a".into(),
10340            para: "b".into(),
10341            wit: "wasi:keyvalue/store".into(),
10342            endpoint: None,
10343            subject: None,
10344            slot: Some("checkout/$orderId".into()),
10345        };
10346        assert!(kv.is_store());
10347        assert!(!kv.is_http());
10348        assert!(!kv.is_capability());
10349
10350        // Fourth arm on the paired closed-set predicate family: the
10351        // payload-less capability edge that projects to the payload-
10352        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10353        // Extends the 3-arm predicate sweep this test opened to cover
10354        // the closed 4-way partition [`WitContract::is_capability`]
10355        // closes on the pre-projection WIT-shape axis, matched with the
10356        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10357        // 4-arm predicate set.
10358        let cap = WitContract {
10359            de: "a".into(),
10360            para: "b".into(),
10361            wit: "custom:capability-only".into(),
10362            endpoint: None,
10363            subject: None,
10364            slot: None,
10365        };
10366        assert!(cap.is_capability());
10367        assert!(!cap.is_http());
10368        assert!(!cap.is_pubsub());
10369        assert!(!cap.is_store());
10370    }
10371
10372    // ── :contratos :wit value-shape gate ─────────────────────────────────
10373    //
10374    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10375    // dispatch-discriminator axis. Until this gate landed
10376    // `WitContract::target()` accepted any non-empty string and
10377    // silently demoted unrecognized shapes to a capability-only L4
10378    // edge — the canonical "I thought I had L7 HTTP routing, got
10379    // L4-only" footgun. Every authoring footgun the WIT registry's
10380    // own grammar rejects (uppercase, hyphen-for-colon typo,
10381    // whitespace, empty package, doubled `@`, …) now becomes a
10382    // caixa-build-time `ContratoWitInvalid` with the offending
10383    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10384    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10385    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10386    // between any two axes' rule enforcement is a build error at the
10387    // predicate, not piecemeal across renderers.
10388
10389    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10390        // Fresh spec per call so the new contract doesn't collide on
10391        // identity with `three_member_spec`'s pre-existing entries.
10392        // The new edge uses `(payment, catalog)` — a pair the fixture
10393        // doesn't already declare — with no payload field set, so the
10394        // wit-shape gate fires before any payload-shape arm.
10395        let mut s = three_member_spec();
10396        s.contratos.push(WitContract {
10397            de: "payment".into(),
10398            para: "catalog".into(),
10399            wit: wit.into(),
10400            endpoint: None,
10401            subject: None,
10402            slot: None,
10403        });
10404        s.validate().unwrap_err()
10405    }
10406
10407    #[test]
10408    fn rejects_wit_with_uppercase_namespace() {
10409        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10410        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10411        // off, so the dispatch fell through to the capability arm and
10412        // the contract silently rendered as an L4-only Cilium edge.
10413        // The new gate surfaces the uppercase typo at validate time
10414        // with the offending `:wit` named.
10415        let err = contrato_wit_err("WASI:http/proxy");
10416        assert!(
10417            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10418                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10419            "got {err:?}"
10420        );
10421    }
10422
10423    #[test]
10424    fn rejects_wit_with_hyphen_for_colon_typo() {
10425        // The canonical "I forgot the `:` separator" typo — pre-gate
10426        // this passed as Capability silently, so the renderer emitted
10427        // an L4-only policy where the author expected L7 HTTP rules.
10428        let err = contrato_wit_err("wasi-http/proxy");
10429        assert!(
10430            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10431                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10432            "got {err:?}"
10433        );
10434    }
10435
10436    #[test]
10437    fn rejects_wit_with_multiple_colons() {
10438        // Doubled `:` — the namespace/package split has nowhere to
10439        // anchor, so the dispatch silently demotes to Capability.
10440        let err = contrato_wit_err("wasi:http:proxy");
10441        assert!(
10442            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10443                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10444            "got {err:?}"
10445        );
10446    }
10447
10448    #[test]
10449    fn rejects_wit_with_empty_package() {
10450        // `wasi:` — namespace alone with no package. Pre-gate this
10451        // failed neither the is_http nor is_pubsub nor is_store
10452        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10453        // a bare `wasi:`), so it silently demoted to Capability.
10454        let err = contrato_wit_err("wasi:");
10455        assert!(
10456            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10457                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10458            "got {err:?}"
10459        );
10460    }
10461
10462    #[test]
10463    fn rejects_wit_with_underscore() {
10464        // Underscore — WIT identifiers are kebab-case, same rule
10465        // DNS-1123 enforces on its peer axes. The diagnostic carries
10466        // the explicit "use `-` instead" remediation.
10467        let err = contrato_wit_err("wasi:http_proxy");
10468        assert!(
10469            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10470                if wit == "wasi:http_proxy" && reason.contains('_')),
10471            "got {err:?}"
10472        );
10473    }
10474
10475    #[test]
10476    fn rejects_wit_with_whitespace() {
10477        // Whitespace mid-token — the prefix check matches but the
10478        // package-and-onward parse silently demoted to Capability.
10479        let err = contrato_wit_err("wasi:http proxy");
10480        assert!(
10481            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10482                if wit == "wasi:http proxy" && reason.contains("whitespace")),
10483            "got {err:?}"
10484        );
10485    }
10486
10487    #[test]
10488    fn rejects_wit_with_non_ascii() {
10489        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10490        // the package name from a doc with smart quotes / accented
10491        // characters" footgun.
10492        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10493        assert!(
10494            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10495                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10496            "got {err:?}"
10497        );
10498    }
10499
10500    #[test]
10501    fn rejects_wit_with_consecutive_hyphens() {
10502        // `pub--sub` — WIT identifiers join words with single hyphens.
10503        let err = contrato_wit_err("nats:pub--sub");
10504        assert!(
10505            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10506                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10507            "got {err:?}"
10508        );
10509    }
10510
10511    #[test]
10512    fn rejects_wit_with_trailing_at_no_version() {
10513        // `wasi:http/proxy@` — the version-suffix author started to
10514        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10515        // parser would reject this; surface it at validate time.
10516        let err = contrato_wit_err("wasi:http/proxy@");
10517        assert!(
10518            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10519                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10520            "got {err:?}"
10521        );
10522    }
10523
10524    #[test]
10525    fn rejects_wit_too_long() {
10526        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10527        // The legitimate-shape arms all pass (lowercase, single `:`,
10528        // kebab-case identifiers); only the cap arm fires. Surfaces
10529        // the paste-from-binary / accidental-multi-line-blob landing
10530        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10531        // on the peer axis.
10532        let big = format!("wasi:{}", "a".repeat(124));
10533        assert_eq!(big.len(), 129);
10534        let err = contrato_wit_err(&big);
10535        assert!(
10536            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10537                if wit == &big && reason.contains("max length of 128")),
10538            "got {err:?}"
10539        );
10540    }
10541
10542    #[test]
10543    fn wit_max_length_validates() {
10544        // 128-byte WIT reference — exactly the cap. Boundary pin:
10545        // drift in the cap surfaces here and at `rejects_wit_too_long`
10546        // simultaneously, mirroring
10547        // `http_contrato_endpoint_max_length_validates` on the peer
10548        // axis.
10549        let big = format!("wasi:{}", "a".repeat(123));
10550        assert_eq!(big.len(), 128);
10551        let mut s = three_member_spec();
10552        s.contratos.push(WitContract {
10553            de: "payment".into(),
10554            para: "catalog".into(),
10555            wit: big,
10556            endpoint: None,
10557            subject: None,
10558            slot: None,
10559        });
10560        s.validate().unwrap();
10561    }
10562
10563    #[test]
10564    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10565        // Positive-set sweep through the AplicacaoSpec::validate
10566        // surface (rather than the substrate-side predicate directly)
10567        // — pins every shape the existing test fixtures + the
10568        // checkout-aplicacao example carry, so the gate's accept-set
10569        // matches the substrate's emit-set. Drift between this list
10570        // and `render::tests::wit_world_ref_accepts_canonical_forms`
10571        // surfaces at the substrate layer's positive sweep — one
10572        // source of truth for the rule.
10573        for wit in [
10574            "wasi:http/proxy",
10575            "wasi:keyvalue/store",
10576            "nats:pub-sub",
10577            "kafka:topic",
10578            "custom:exchange",
10579            "pleme:cap/audit",
10580            "wasi:http/proxy@0.2.0",
10581        ] {
10582            // Payload field paired to the dispatched WIT shape so the
10583            // shape-↔-target arm doesn't fire instead of the wit-shape
10584            // arm we're exercising. Routes off the same
10585            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10586            // `wit_shape_is_store` free functions the production
10587            // `WitContract::is_http` / `is_pubsub` / `is_store`
10588            // methods delegate to (both consult the lifted
10589            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10590            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10591            // future prefix addition to the routing accept-set
10592            // reaches this test's payload-dispatch arm by
10593            // construction — no per-test-site drift can hide a
10594            // shape-→-target-slot mismatch that would silently
10595            // demote a canonical `:wit` value to the
10596            // `(None, None, None)` capability-only arm and let the
10597            // `AplicacaoSpec::validate` positive sweep pass on a
10598            // shape it should exercise as HTTP / pub-sub / store.
10599            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10600                (Some("/x".into()), None, None)
10601            } else if wit_shape_is_pubsub(wit) {
10602                (None, Some("topic.x".into()), None)
10603            } else if wit_shape_is_store(wit) {
10604                (None, None, Some("bucket/$key".into()))
10605            } else {
10606                (None, None, None)
10607            };
10608            let mut s = three_member_spec();
10609            s.contratos.push(WitContract {
10610                de: "payment".into(),
10611                para: "catalog".into(),
10612                wit: wit.into(),
10613                endpoint,
10614                subject,
10615                slot,
10616            });
10617            s.validate()
10618                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10619        }
10620    }
10621
10622    #[test]
10623    fn wit_shape_predicates_accept_canonical_prefix_set() {
10624        // Positive-set sweep pinning every prefix in
10625        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10626        // WIT_STORE_SHAPE_PREFIXES against the three free-function
10627        // dispatch predicates. The six prefixes are the load-bearing
10628        // routing keys the substrate's WIT-shape dispatch consults
10629        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10630        // key/value-store-slot admission); any drift between the
10631        // free-function accept-set and this list surfaces here
10632        // rather than at apply time as a silent
10633        // shape-→-capability-only demotion.
10634        assert!(wit_shape_is_http("wasi:http/proxy"));
10635        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10636        assert!(wit_shape_is_http("http:incoming"));
10637
10638        assert!(wit_shape_is_pubsub("nats:pub-sub"));
10639        assert!(wit_shape_is_pubsub("kafka:topic"));
10640
10641        assert!(wit_shape_is_store("wasi:keyvalue/store"));
10642        assert!(wit_shape_is_store("kv:cache/session"));
10643    }
10644
10645    #[test]
10646    fn wit_shape_predicates_reject_uncanonical_forms() {
10647        // Negative-set pin: the six canonical prefixes are
10648        // lowercase-only (mirrors the `is_wit_world_ref` substrate
10649        // predicate's lowercase invariant — see its docstring on the
10650        // "I thought I had L7 HTTP routing, got L4-only" footgun).
10651        // The empty string, an uppercase-prefixed form, a hyphen-
10652        // instead-of-colon typo, and a bare kebab identifier all miss
10653        // every shape arm — reachable-by-construction only via the
10654        // `is_wit_world_ref` gate that admission-checks the `:wit`
10655        // value first, but pinned here so any future
10656        // free-function change (e.g. a case-insensitive
10657        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10658        // this unit level.
10659        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10660            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10661            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10662            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10663        }
10664    }
10665
10666    #[test]
10667    fn wit_shape_predicates_partition_canonical_set() {
10668        // Every canonical prefix routes to exactly one shape arm —
10669        // the three prefix sets are pairwise disjoint. Pins the
10670        // routing property [`WitContract::target`] relies on: an
10671        // `is_http()` return of `true` guarantees `is_pubsub()` and
10672        // `is_store()` return `false`, so the shape-→-target-slot
10673        // dispatch (endpoint vs subject vs slot) is unambiguous.
10674        // Drift (e.g. a future `"kv:"` moved into the HTTP set
10675        // without removal from the store set) would silently route
10676        // one prefix to two arms and the first-matching-arm order
10677        // becomes load-bearing — this pin surfaces it as a build
10678        // error instead.
10679        for prefix in WIT_HTTP_SHAPE_PREFIXES {
10680            let sample = format!("{prefix}x");
10681            assert!(wit_shape_is_http(&sample));
10682            assert!(!wit_shape_is_pubsub(&sample));
10683            assert!(!wit_shape_is_store(&sample));
10684        }
10685        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10686            let sample = format!("{prefix}x");
10687            assert!(!wit_shape_is_http(&sample));
10688            assert!(wit_shape_is_pubsub(&sample));
10689            assert!(!wit_shape_is_store(&sample));
10690        }
10691        for prefix in WIT_STORE_SHAPE_PREFIXES {
10692            let sample = format!("{prefix}x");
10693            assert!(!wit_shape_is_http(&sample));
10694            assert!(!wit_shape_is_pubsub(&sample));
10695            assert!(wit_shape_is_store(&sample));
10696        }
10697    }
10698
10699    #[test]
10700    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10701        // Positive pin: [`wit_shape_matches`] is exactly the
10702        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10703        // parameterized on the accept-set. Two-prefix accept-set,
10704        // one-prefix accept-set, and empty accept-set (which must
10705        // reject everything, including the empty string — an empty
10706        // `any()` fold returns `false`) all pinned so a future
10707        // reimplementation that swaps `starts_with` for `contains`,
10708        // `==`, or a case-folded comparator surfaces at unit-test
10709        // time.
10710        let two = &["wasi:http/", "http:"];
10711        assert!(wit_shape_matches("wasi:http/proxy", two));
10712        assert!(wit_shape_matches("http:incoming", two));
10713        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10714
10715        let one = &["nats:"];
10716        assert!(wit_shape_matches("nats:pub-sub", one));
10717        assert!(!wit_shape_matches("kafka:topic", one));
10718
10719        // Empty accept-set matches nothing — the identity element
10720        // for the disjunctive `any()` fold across the prefix set.
10721        // Reachable via a future `wit_shape_is_<name>` const paired
10722        // to a still-empty prefix table on a nascent shape-arm draft.
10723        let empty: &[&str] = &[];
10724        assert!(!wit_shape_matches("wasi:http/proxy", empty));
10725        assert!(!wit_shape_matches("", empty));
10726
10727        // starts_with, not contains: a prefix embedded mid-string
10728        // never matches. Pins the routing invariant [`WitContract::target`]
10729        // relies on (an authored `:wit "custom:wasi:http/"` string
10730        // does not silently route through the HTTP arm just because
10731        // it happens to contain the canonical HTTP prefix).
10732        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10733    }
10734
10735    #[test]
10736    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10737        // Equivalence pin: each per-shape predicate is exactly
10738        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10739        // every canonical prefix + the empty string + one negative
10740        // sample against every peer so a future predicate that grew
10741        // its own inline `iter().any(starts_with)` (rather than
10742        // delegating through the lifted combinator) drifts loudly here
10743        // — the peer-const table's contents must agree with the
10744        // predicate's accept-set by construction.
10745        let samples = [
10746            String::new(),
10747            "wasi:http/proxy".to_string(),
10748            "http:incoming".to_string(),
10749            "nats:pub-sub".to_string(),
10750            "kafka:topic".to_string(),
10751            "wasi:keyvalue/store".to_string(),
10752            "kv:cache/session".to_string(),
10753            "custom-shape".to_string(),
10754            "WASI:HTTP/proxy".to_string(),
10755        ];
10756        for wit in &samples {
10757            assert_eq!(
10758                wit_shape_is_http(wit),
10759                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10760                "wit_shape_is_http drifted from combinator on {wit:?}",
10761            );
10762            assert_eq!(
10763                wit_shape_is_pubsub(wit),
10764                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10765                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10766            );
10767            assert_eq!(
10768                wit_shape_is_store(wit),
10769                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10770                "wit_shape_is_store drifted from combinator on {wit:?}",
10771            );
10772        }
10773    }
10774
10775    #[test]
10776    fn wit_contract_shape_methods_delegate_to_free_functions() {
10777        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10778        // `is_store` are `&self` conveniences on top of the free
10779        // functions — for every canonical prefix the method's return
10780        // matches its free-function peer. Sweeps the union of the
10781        // three prefix sets so a future method that grew its own
10782        // inline prefix logic (rather than delegating) drifts loudly
10783        // here on the first prefix the free function accepts and the
10784        // method doesn't.
10785        for shape_set in [
10786            WIT_HTTP_SHAPE_PREFIXES,
10787            WIT_PUBSUB_SHAPE_PREFIXES,
10788            WIT_STORE_SHAPE_PREFIXES,
10789        ] {
10790            for prefix in shape_set {
10791                let c = WitContract {
10792                    de: "cart".into(),
10793                    para: "catalog".into(),
10794                    wit: format!("{prefix}x"),
10795                    endpoint: None,
10796                    subject: None,
10797                    slot: None,
10798                };
10799                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10800                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10801                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10802            }
10803        }
10804    }
10805
10806    #[test]
10807    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
10808        // 4-way partition-witness pin: for every canonical prefix in
10809        // the payload-arm accept-sets, exactly one of the four
10810        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
10811        // [`WitContract::is_store`] / [`WitContract::is_capability`]
10812        // predicates returns `true` and the other three return `false`
10813        // — the four-arm partition witness that locks the substrate's
10814        // WIT-shape-space closure on the pre-projection axis load-
10815        // bearing. A future arm addition (a hypothetical fourth
10816        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
10817        // shape) that landed on one of the payload-arm predicates
10818        // without shrinking [`WitContract::is_capability`]'s accept-set
10819        // would surface here as two arms returning `true` simultaneously
10820        // — a partition-witness break the pin catches at caixa-core
10821        // build time rather than a silent per-consumer misclassification
10822        // at renderer emit time. Peer of the sibling `WitTarget`-side
10823        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
10824        // partition-witness pin on the post-projection payload-scalar
10825        // arm-set — extends the discipline onto the pre-projection
10826        // 4-arm shape-space.
10827        for shape_set in [
10828            WIT_HTTP_SHAPE_PREFIXES,
10829            WIT_PUBSUB_SHAPE_PREFIXES,
10830            WIT_STORE_SHAPE_PREFIXES,
10831        ] {
10832            for prefix in shape_set {
10833                let c = WitContract {
10834                    de: "cart".into(),
10835                    para: "catalog".into(),
10836                    wit: format!("{prefix}x"),
10837                    endpoint: None,
10838                    subject: None,
10839                    slot: None,
10840                };
10841                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
10842                    .iter()
10843                    .filter(|&&b| b)
10844                    .count();
10845                assert_eq!(
10846                    hits,
10847                    1,
10848                    "WitContract WIT-shape 4-way predicate partition must \
10849                     admit exactly one arm per canonical prefix; got {hits} \
10850                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
10851                     is_capability={})",
10852                    c.wit,
10853                    c.is_http(),
10854                    c.is_pubsub(),
10855                    c.is_store(),
10856                    c.is_capability(),
10857                );
10858            }
10859        }
10860        // Capability-arm sweep: two representative capability shapes
10861        // (a bare WIT world outside the three payload-arm prefix sets,
10862        // and the deliberately-shaped empty string that
10863        // [`crate::render::is_wit_world_ref`] rejects at
10864        // [`WitContract::target`] time but which the pure classifier
10865        // still admits — see the method docstring's "purely syntactic
10866        // classification" note). Both must land on the fourth arm
10867        // exclusively, so the partition witness holds across the full
10868        // 4-arm closure.
10869        for wit in ["custom:capability-only", ""] {
10870            let c = WitContract {
10871                de: "cart".into(),
10872                para: "catalog".into(),
10873                wit: wit.into(),
10874                endpoint: None,
10875                subject: None,
10876                slot: None,
10877            };
10878            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
10879                .iter()
10880                .filter(|&&b| b)
10881                .count();
10882            assert_eq!(
10883                hits, 1,
10884                "WitContract WIT-shape 4-way predicate partition must \
10885                 admit exactly one arm on Capability-shaped wit={wit:?}"
10886            );
10887            assert!(
10888                c.is_capability(),
10889                "wit={wit:?} must project onto the Capability arm"
10890            );
10891        }
10892    }
10893
10894    #[test]
10895    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
10896        // Composition-witness pin: [`WitContract::is_capability`] is the
10897        // exact-inverse disjunction of the sibling payload-arm predicate
10898        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
10899        // [`WitContract::is_store`]. A future reimplementation that
10900        // grew its own prefix-set scan (e.g. inlining a fourth
10901        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
10902        // own today) rather than delegating to the sibling trio would
10903        // drift loudly here — the composition contract binds the
10904        // fourth-arm predicate to the exact-inverse of the three
10905        // payload-arm predicates, so any rebrand of any prefix-set const
10906        // flows through this method by construction without a
10907        // coordinated per-consumer rewrite. Sweeps the union of the
10908        // three payload-arm prefix sets plus two Capability-shaped
10909        // shapes (a bare non-prefix-matching WIT world, the deliberately-
10910        // empty string the pure classifier still admits per the method
10911        // docstring's "purely syntactic classification" note).
10912        let mut cases: Vec<String> = Vec::new();
10913        for shape_set in [
10914            WIT_HTTP_SHAPE_PREFIXES,
10915            WIT_PUBSUB_SHAPE_PREFIXES,
10916            WIT_STORE_SHAPE_PREFIXES,
10917        ] {
10918            for prefix in shape_set {
10919                cases.push(format!("{prefix}x"));
10920            }
10921        }
10922        cases.push("custom:capability-only".to_string());
10923        cases.push(String::new());
10924        for wit in cases {
10925            let c = WitContract {
10926                de: "cart".into(),
10927                para: "catalog".into(),
10928                wit: wit.clone(),
10929                endpoint: None,
10930                subject: None,
10931                slot: None,
10932            };
10933            assert_eq!(
10934                c.is_capability(),
10935                !c.is_http() && !c.is_pubsub() && !c.is_store(),
10936                "WitContract::is_capability must equal \
10937                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
10938            );
10939        }
10940    }
10941
10942    #[test]
10943    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
10944        // Cross-projection-witness pin: whenever [`WitContract::target`]
10945        // succeeds, the pre-projection [`WitContract::is_capability`]
10946        // classification agrees with the post-projection
10947        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
10948        // predicate — the 4-arm typed partition on the substrate's
10949        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
10950        // partition on the pre-projection axis line up by construction.
10951        // A future divergence between the two axes (a peer
10952        // [`WitTarget`] variant addition that landed on the typed-view
10953        // surface without a peer prefix-set + [`WitContract`] predicate
10954        // extension, or vice versa) would surface here at caixa-core
10955        // build time rather than a silent per-consumer split at renderer
10956        // emit time. Peer of the sibling pre-/post-projection
10957        // agreement pins the payload-carrier trio
10958        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
10959        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
10960        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
10961        // post-projection — b11bb49 trio lift) already carry across the
10962        // three payload arms — this pin closes the pair on the fourth
10963        // payload-less arm.
10964        let http = WitContract {
10965            de: "cart".into(),
10966            para: "catalog".into(),
10967            wit: "wasi:http/proxy".into(),
10968            endpoint: Some("/x".into()),
10969            subject: None,
10970            slot: None,
10971        };
10972        assert!(!http.is_capability());
10973        assert!(!http.target().unwrap().is_capability());
10974
10975        let nats = WitContract {
10976            de: "cart".into(),
10977            para: "catalog".into(),
10978            wit: "nats:pub-sub".into(),
10979            endpoint: None,
10980            subject: Some("events.x".into()),
10981            slot: None,
10982        };
10983        assert!(!nats.is_capability());
10984        assert!(!nats.target().unwrap().is_capability());
10985
10986        let kv = WitContract {
10987            de: "cart".into(),
10988            para: "catalog".into(),
10989            wit: "wasi:keyvalue/store".into(),
10990            endpoint: None,
10991            subject: None,
10992            slot: Some("checkout/$orderId".into()),
10993        };
10994        assert!(!kv.is_capability());
10995        assert!(!kv.target().unwrap().is_capability());
10996
10997        let cap = WitContract {
10998            de: "cart".into(),
10999            para: "catalog".into(),
11000            wit: "custom:capability-only".into(),
11001            endpoint: None,
11002            subject: None,
11003            slot: None,
11004        };
11005        assert!(cap.is_capability());
11006        assert!(cap.target().unwrap().is_capability());
11007    }
11008
11009    #[test]
11010    fn empty_wit_takes_precedence_over_invalid() {
11011        // Ordering pin: `EmptyWit` is the more self-locating
11012        // diagnostic on `""` and must lead — the value-shape gate is
11013        // only reached after the empty-check fires. Mirrors
11014        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11015        // the peer payload axis.
11016        let mut s = three_member_spec();
11017        s.contratos.push(WitContract {
11018            de: "payment".into(),
11019            para: "catalog".into(),
11020            wit: String::new(),
11021            endpoint: None,
11022            subject: None,
11023            slot: None,
11024        });
11025        let err = s.validate().unwrap_err();
11026        assert!(
11027            matches!(err, AplicacaoError::EmptyWit { .. }),
11028            "got {err:?}"
11029        );
11030    }
11031
11032    #[test]
11033    fn wit_invalid_fires_before_payload_shape_arm() {
11034        // Ordering pin: a malformed `:wit` surfaces *its own*
11035        // diagnostic (which names the offending wit verbatim) before
11036        // any payload-field check — a contrato whose wit is
11037        // structurally invalid AND carries a wrong target field
11038        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
11039        // because the dispatch on the wit is what decides which
11040        // payload field is "right" in the first place. Without this
11041        // ordering, the author would see "wrong target field" for a
11042        // wit that hasn't even been parsed, which doesn't name the
11043        // root cause.
11044        let mut s = three_member_spec();
11045        s.contratos.push(WitContract {
11046            de: "payment".into(),
11047            para: "catalog".into(),
11048            // Hyphen-for-colon typo + endpoint set: pre-gate this
11049            // raised `ContratoWrongTarget { expected: "none" }` (the
11050            // Capability arm rejecting the endpoint), masking the
11051            // real authoring mistake (the wit isn't `wasi:http/proxy`).
11052            wit: "wasi-http/proxy".into(),
11053            endpoint: Some("/x".into()),
11054            subject: None,
11055            slot: None,
11056        });
11057        let err = s.validate().unwrap_err();
11058        assert!(
11059            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
11060                if wit == "wasi-http/proxy"),
11061            "got {err:?}"
11062        );
11063    }
11064
11065    #[test]
11066    fn wit_invalid_diagnostic_carries_offending_wit() {
11067        // Diagnostic-shape pin — the offending `:wit` + `:de` +
11068        // `:para` + a non-empty reason flow through verbatim so the
11069        // author can grep their caixa.lisp for the offending contrato
11070        // block and fix it in one edit. Same shape as
11071        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
11072        let err = contrato_wit_err("WASI:HTTP/proxy");
11073        match err {
11074            AplicacaoError::ContratoWitInvalid {
11075                de,
11076                para,
11077                wit,
11078                reason,
11079            } => {
11080                assert_eq!(de, "payment");
11081                assert_eq!(para, "catalog");
11082                assert_eq!(wit, "WASI:HTTP/proxy");
11083                assert!(!reason.is_empty(), "reason field must be non-empty");
11084            }
11085            other => panic!("expected ContratoWitInvalid, got {other:?}"),
11086        }
11087    }
11088
11089    // ── :contratos :subject value-shape gate ─────────────────────────────
11090    //
11091    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
11092    // suites on the peer payload axes. Until this gate landed
11093    // `WitContract::target()` only refused the empty string; a
11094    // structurally invalid subject silently passed validate and the
11095    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
11096    // Subject'` on publish / subscribe, or as a silent message drop,
11097    // far from the source caixa.lisp. Every authoring footgun the
11098    // NATS server's subject parser would catch on admission now
11099    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
11100    // offending `:subject` + `:de` + `:para` named verbatim. Same
11101    // diagnostic shape as `ContratoEndpointInvalid` /
11102    // `ContratoWitInvalid` on the peer payload axes; same shared
11103    // predicate (`crate::render::is_nats_subject`) ensures drift
11104    // between any two axes' rule enforcement is a build error at the
11105    // predicate, not piecemeal across renderers.
11106
11107    fn contrato_subject_err(subject: &str) -> AplicacaoError {
11108        // Fresh spec per call so the new contract doesn't collide on
11109        // identity with `three_member_spec`'s pre-existing entries.
11110        // The new edge uses `(payment, catalog)` — a pair the fixture
11111        // doesn't already declare — with `:wit "nats:pub-sub"` and the
11112        // varying `:subject`, so the subject-shape gate fires cleanly
11113        // after the wit-shape gate (which `"nats:pub-sub"` passes).
11114        let mut s = three_member_spec();
11115        s.contratos.push(WitContract {
11116            de: "payment".into(),
11117            para: "catalog".into(),
11118            wit: "nats:pub-sub".into(),
11119            endpoint: None,
11120            subject: Some(subject.into()),
11121            slot: None,
11122        });
11123        s.validate().unwrap_err()
11124    }
11125
11126    #[test]
11127    fn rejects_pubsub_contrato_subject_with_whitespace() {
11128        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
11129        // landed at the NATS server as a malformed subject the parser
11130        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
11131        // source caixa.lisp.
11132        let err = contrato_subject_err("foo bar");
11133        assert!(
11134            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11135                if subject == "foo bar" && reason.contains("whitespace")),
11136            "got {err:?}"
11137        );
11138    }
11139
11140    #[test]
11141    fn rejects_pubsub_contrato_subject_with_control_char() {
11142        let err = contrato_subject_err("foo\x01bar");
11143        assert!(
11144            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11145                if subject == "foo\x01bar" && reason.contains("control character")),
11146            "got {err:?}"
11147        );
11148    }
11149
11150    #[test]
11151    fn rejects_pubsub_contrato_subject_with_non_ascii() {
11152        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11153        // the subject from a doc with smart quotes / accented
11154        // characters" footgun.
11155        let err = contrato_subject_err("foo.caf\u{e9}");
11156        assert!(
11157            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11158                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
11159            "got {err:?}"
11160        );
11161    }
11162
11163    #[test]
11164    fn rejects_pubsub_contrato_subject_with_leading_dot() {
11165        // Empty leading token — NATS rejects.
11166        let err = contrato_subject_err(".foo");
11167        assert!(
11168            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11169                if subject == ".foo" && reason.contains("must not start with `.`")),
11170            "got {err:?}"
11171        );
11172    }
11173
11174    #[test]
11175    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
11176        // Empty trailing token — NATS rejects. The remediation
11177        // (use `>` instead) is in the reason string.
11178        let err = contrato_subject_err("foo.");
11179        assert!(
11180            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11181                if subject == "foo." && reason.contains("must not end with `.`")),
11182            "got {err:?}"
11183        );
11184    }
11185
11186    #[test]
11187    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
11188        // The canonical "I forgot to fill in the middle segment"
11189        // typo — `"foo..bar"`. NATS rejects empty tokens.
11190        let err = contrato_subject_err("foo..bar");
11191        assert!(
11192            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11193                if subject == "foo..bar" && reason.contains("consecutive `.`")),
11194            "got {err:?}"
11195        );
11196    }
11197
11198    #[test]
11199    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
11200        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
11201        // as the final segment. Pre-gate this passed as a typed edge
11202        // and surfaced at runtime as a NATS subscribe rejection.
11203        let err = contrato_subject_err("foo.>.bar");
11204        assert!(
11205            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11206                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
11207            "got {err:?}"
11208        );
11209    }
11210
11211    #[test]
11212    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
11213        // `foo*.bar` — NATS wildcards are standalone tokens. The
11214        // remediation is in the reason string.
11215        let err = contrato_subject_err("foo*.bar");
11216        assert!(
11217            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11218                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
11219            "got {err:?}"
11220        );
11221    }
11222
11223    #[test]
11224    fn rejects_pubsub_contrato_subject_with_invalid_char() {
11225        // `foo,bar` — comma is not a valid NATS subject character.
11226        // Pinned separately from the wildcard arms so the invalid-
11227        // character diagnostic is in force.
11228        let err = contrato_subject_err("foo,bar");
11229        assert!(
11230            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11231                if subject == "foo,bar" && reason.contains("invalid character")),
11232            "got {err:?}"
11233        );
11234    }
11235
11236    #[test]
11237    fn rejects_pubsub_contrato_subject_too_long() {
11238        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
11239        // The legitimate-shape arms all pass (one all-`a` token, no
11240        // `.`, no wildcards); only the cap arm fires. Surfaces the
11241        // paste-from-binary / accidental-multi-line-blob landing
11242        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11243        // on the peer axis.
11244        let big = "a".repeat(257);
11245        assert_eq!(big.len(), 257);
11246        let err = contrato_subject_err(&big);
11247        assert!(
11248            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11249                if subject == &big && reason.contains("max length of 256")),
11250            "got {err:?}"
11251        );
11252    }
11253
11254    #[test]
11255    fn pubsub_contrato_subject_max_length_validates() {
11256        // 256-byte subject — exactly the cap. Boundary pin: drift in
11257        // the cap surfaces here and at
11258        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
11259        // mirroring `http_contrato_endpoint_max_length_validates` and
11260        // `wit_max_length_validates` on the peer axes.
11261        let big = "a".repeat(256);
11262        assert_eq!(big.len(), 256);
11263        let mut s = three_member_spec();
11264        s.contratos.push(WitContract {
11265            de: "payment".into(),
11266            para: "catalog".into(),
11267            wit: "nats:pub-sub".into(),
11268            endpoint: None,
11269            subject: Some(big),
11270            slot: None,
11271        });
11272        s.validate().unwrap();
11273    }
11274
11275    #[test]
11276    fn pubsub_contrato_subject_accepts_canonical_forms() {
11277        // Positive-set sweep: every canonical NATS subject shape the
11278        // substrate-side `is_nats_subject` predicate accepts (the
11279        // multi-dot `events.order.charged`, the snake_case / kebab-
11280        // case / mixed-case tokens, the digit-bearing tokens, the
11281        // single-token wildcard `*` at every segment position, and
11282        // the trailing `>` multi-token wildcard) must remain a valid
11283        // contrato subject too. Drift between this list and the
11284        // substrate-side `nats_subject_accepts_canonical_forms` sweep
11285        // surfaces at the shared predicate — one source of truth.
11286        // Uses a fresh `(payment, catalog)` edge so none of the swept
11287        // subjects collide with the pre-existing entries in
11288        // `three_member_spec`.
11289        for subject in [
11290            "checkout.events.charge.failed",
11291            "rio.events.order.charged",
11292            "orders",
11293            "orders.123",
11294            "snake_case.token",
11295            "kebab-case.token",
11296            "MixedCase.Token",
11297            "orders.*.charged",
11298            "*.events.*",
11299            "orders.>",
11300        ] {
11301            let mut s = three_member_spec();
11302            s.contratos.push(WitContract {
11303                de: "payment".into(),
11304                para: "catalog".into(),
11305                wit: "nats:pub-sub".into(),
11306                endpoint: None,
11307                subject: Some(subject.into()),
11308                slot: None,
11309            });
11310            s.validate()
11311                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
11312        }
11313    }
11314
11315    #[test]
11316    fn contrato_subject_empty_takes_precedence_over_invalid() {
11317        // Ordering pin: `ContratoSubjectEmpty` is the more self-
11318        // locating diagnostic on `""` and must lead — the value-shape
11319        // gate is only reached after the empty-check fires. Mirrors
11320        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11321        // the peer payload axis.
11322        let mut s = three_member_spec();
11323        s.contratos.push(WitContract {
11324            de: "payment".into(),
11325            para: "catalog".into(),
11326            wit: "nats:pub-sub".into(),
11327            endpoint: None,
11328            subject: Some(String::new()),
11329            slot: None,
11330        });
11331        let err = s.validate().unwrap_err();
11332        assert!(
11333            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
11334            "got {err:?}"
11335        );
11336    }
11337
11338    #[test]
11339    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
11340        // Diagnostic-shape pin — the offending `:subject` + `:de` +
11341        // `:para` + a non-empty reason flow through verbatim so the
11342        // author can grep their caixa.lisp for the offending contrato
11343        // block and fix it in one edit. Same shape as
11344        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11345        // and `wit_invalid_diagnostic_carries_offending_wit`.
11346        let err = contrato_subject_err("foo..bar");
11347        match err {
11348            AplicacaoError::ContratoSubjectInvalid {
11349                de,
11350                para,
11351                subject,
11352                reason,
11353            } => {
11354                assert_eq!(de, "payment");
11355                assert_eq!(para, "catalog");
11356                assert_eq!(subject, "foo..bar");
11357                assert!(!reason.is_empty(), "reason field must be non-empty");
11358            }
11359            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
11360        }
11361    }
11362
11363    #[test]
11364    fn target_view_pubsub_subject_passes_through_to_typed_view() {
11365        // The compounding theorem on the pub-sub axis: every
11366        // `WitTarget::PubSub { subject }` returned by `target()` carries
11367        // a NATS-server-accepted subject. Renderers downstream of
11368        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
11369        // NATS Stream/Consumer CR emitter, the future `feira app graph`
11370        // view's subject labeller) can rely on this without re-checking
11371        // — the type system carries the proof. Mirrors
11372        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
11373        // on the peer axes.
11374        let nats = WitContract {
11375            de: "a".into(),
11376            para: "b".into(),
11377            wit: "nats:pub-sub".into(),
11378            endpoint: None,
11379            subject: Some("orders.events.*.charged".into()),
11380            slot: None,
11381        };
11382        match nats.target().unwrap() {
11383            WitTarget::PubSub { subject } => {
11384                assert_eq!(subject, "orders.events.*.charged");
11385            }
11386            other => panic!("expected PubSub, got {other:?}"),
11387        }
11388    }
11389
11390    // ── :contratos :slot value-shape gate ────────────────────────────────
11391    //
11392    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
11393    // (63e18a0) value-shape suites on the peer payload axes. Until this
11394    // gate landed `WitContract::target()` only refused the empty string
11395    // for the Store arm; a structurally invalid slot (raw whitespace,
11396    // control character, non-ASCII byte, paste-from-binary multi-line
11397    // blob) silently passed validate and surfaced at runtime as a
11398    // per-backend kv write rejection or a silent next-read corruption,
11399    // far from the source caixa.lisp with no field naming which
11400    // `:contratos` edge carried the typo. Every authoring footgun the
11401    // kv backend intersection-floor would catch on write now becomes a
11402    // caixa-build-time `ContratoSlotInvalid` with the offending
11403    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
11404    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
11405    // peer payload axes; same shared predicate
11406    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
11407    // any two axes' rule enforcement is a build error at the
11408    // predicate, not piecemeal across renderers. Closes the typed
11409    // payload-axis value-shape trajectory across all three legs of the
11410    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
11411
11412    fn contrato_slot_err(slot: &str) -> AplicacaoError {
11413        // Fresh spec per call so the new contract doesn't collide on
11414        // identity with `three_member_spec`'s pre-existing entries
11415        // and doesn't close a synchronous cycle the cycle detector
11416        // would reject before the slot-shape gate fires. The new edge
11417        // uses `(payment, catalog)` — a pair the fixture doesn't
11418        // already declare in either direction (the fixture carries
11419        // `cart -> catalog` and `cart -> payment`, so `payment ->
11420        // catalog` doesn't form a cycle on the sync subgraph) — with
11421        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
11422        // slot-shape gate fires cleanly after the wit-shape gate
11423        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
11424        // peer `contrato_subject_err` helper uses (63e18a0).
11425        let mut s = three_member_spec();
11426        s.contratos.push(WitContract {
11427            de: "payment".into(),
11428            para: "catalog".into(),
11429            wit: "wasi:keyvalue/store".into(),
11430            endpoint: None,
11431            subject: None,
11432            slot: Some(slot.into()),
11433        });
11434        s.validate().unwrap_err()
11435    }
11436
11437    #[test]
11438    fn rejects_store_contrato_slot_with_whitespace() {
11439        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
11440        // silently landed at the kv backend with whitespace whose
11441        // runtime behavior varies unpredictably across backends (etcd
11442        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
11443        // rejects on write). Now caught at the source caixa.lisp.
11444        let err = contrato_slot_err("check out/$order");
11445        assert!(
11446            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11447                if slot == "check out/$order" && reason.contains("whitespace")),
11448            "got {err:?}"
11449        );
11450    }
11451
11452    #[test]
11453    fn rejects_store_contrato_slot_with_tab() {
11454        // Tab byte arm-pinned separately from the space arm so a
11455        // future relaxation that admits one but not the other surfaces
11456        // here.
11457        let err = contrato_slot_err("check\tout");
11458        assert!(
11459            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11460                if slot == "check\tout" && reason.contains("whitespace")),
11461            "got {err:?}"
11462        );
11463    }
11464
11465    #[test]
11466    fn rejects_store_contrato_slot_with_control_char() {
11467        // SOH (0x01) — distinct from the whitespace arm. Redis admits
11468        // and corrupts on RESP protocol framing; DynamoDB rejects on
11469        // write.
11470        let err = contrato_slot_err("checkout/\x01order");
11471        assert!(
11472            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11473                if slot == "checkout/\x01order" && reason.contains("control character")),
11474            "got {err:?}"
11475        );
11476    }
11477
11478    #[test]
11479    fn rejects_store_contrato_slot_with_newline() {
11480        // Embedded newline — the canonical "the paste-from-binary slug
11481        // spans multiple lines" footgun. Distinct from the whitespace
11482        // arm because `\n` is a control character (0x0A).
11483        let err = contrato_slot_err("checkout\norder");
11484        assert!(
11485            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11486                if slot == "checkout\norder" && reason.contains("control character")),
11487            "got {err:?}"
11488        );
11489    }
11490
11491    #[test]
11492    fn rejects_store_contrato_slot_with_non_ascii() {
11493        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11494        // the slot from a doc with accented characters" footgun. Each
11495        // kv backend re-encodes non-ASCII differently (etcd preserves
11496        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
11497        // rejects), so the typed slot's value set is the intersection-
11498        // floor every backend admits identically (printable ASCII).
11499        let err = contrato_slot_err("ch\u{e9}ckout/$order");
11500        assert!(
11501            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11502                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
11503            "got {err:?}"
11504        );
11505    }
11506
11507    #[test]
11508    fn rejects_store_contrato_slot_too_long() {
11509        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
11510        // legitimate-shape arms all pass (a single all-`a` token, no
11511        // separators); only the cap arm fires. Surfaces the paste-
11512        // from-binary / accidental-multi-line-blob landing footgun.
11513        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
11514        // `rejects_http_contrato_endpoint_too_long` on the peer
11515        // payload axes.
11516        let big = "a".repeat(513);
11517        assert_eq!(big.len(), 513);
11518        let err = contrato_slot_err(&big);
11519        assert!(
11520            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11521                if slot == &big && reason.contains("max length of 512")),
11522            "got {err:?}"
11523        );
11524    }
11525
11526    #[test]
11527    fn store_contrato_slot_max_length_validates() {
11528        // 512-byte slot — exactly the cap. Boundary pin: drift in the
11529        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
11530        // simultaneously, mirroring
11531        // `pubsub_contrato_subject_max_length_validates` and
11532        // `http_contrato_endpoint_max_length_validates` on the peer
11533        // payload axes.
11534        let big = "a".repeat(512);
11535        assert_eq!(big.len(), 512);
11536        let mut s = three_member_spec();
11537        s.contratos.push(WitContract {
11538            de: "payment".into(),
11539            para: "catalog".into(),
11540            wit: "wasi:keyvalue/store".into(),
11541            endpoint: None,
11542            subject: None,
11543            slot: Some(big),
11544        });
11545        s.validate().unwrap();
11546    }
11547
11548    #[test]
11549    fn store_contrato_slot_accepts_canonical_forms() {
11550        // Positive-set sweep: every canonical kv slot template the
11551        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
11552        // (single-token identifiers, path-namespaced `$`-templates,
11553        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
11554        // snake_case / kebab-case / MixedCase tokens, digit-bearing
11555        // tokens, percent-encoded fragments) must remain valid
11556        // contrato slots too. Drift between this list and the
11557        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
11558        // surfaces at the shared predicate — one source of truth.
11559        // Uses a fresh `(payment, catalog)` edge so none of the swept
11560        // slots collide with the pre-existing entries in
11561        // `three_member_spec`.
11562        for slot in [
11563            "checkout",
11564            "checkout/$orderId",
11565            "users:{tenant}/{id}",
11566            "session.<sid>",
11567            "session.tokens.<sid>",
11568            "snake_case_key",
11569            "kebab-case-key",
11570            "MixedCase",
11571            "shard0",
11572            "v2/key",
11573            "users/caf%C3%A9",
11574        ] {
11575            let mut s = three_member_spec();
11576            s.contratos.push(WitContract {
11577                de: "payment".into(),
11578                para: "catalog".into(),
11579                wit: "wasi:keyvalue/store".into(),
11580                endpoint: None,
11581                subject: None,
11582                slot: Some(slot.into()),
11583            });
11584            s.validate()
11585                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
11586        }
11587    }
11588
11589    #[test]
11590    fn contrato_slot_empty_takes_precedence_over_invalid() {
11591        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
11592        // diagnostic on `""` and must lead — the value-shape gate is
11593        // only reached after the empty-check fires. Mirrors
11594        // `contrato_subject_empty_takes_precedence_over_invalid` and
11595        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11596        // the peer payload axes.
11597        let mut s = three_member_spec();
11598        s.contratos.push(WitContract {
11599            de: "payment".into(),
11600            para: "catalog".into(),
11601            wit: "wasi:keyvalue/store".into(),
11602            endpoint: None,
11603            subject: None,
11604            slot: Some(String::new()),
11605        });
11606        let err = s.validate().unwrap_err();
11607        assert!(
11608            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
11609            "got {err:?}"
11610        );
11611    }
11612
11613    #[test]
11614    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
11615        // Diagnostic-shape pin — the offending `:slot` + `:de` +
11616        // `:para` + a non-empty reason flow through verbatim so the
11617        // author can grep their caixa.lisp for the offending contrato
11618        // block and fix it in one edit. Same shape as
11619        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
11620        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11621        // on the peer payload axes.
11622        let err = contrato_slot_err("check out/$order");
11623        match err {
11624            AplicacaoError::ContratoSlotInvalid {
11625                de,
11626                para,
11627                slot,
11628                reason,
11629            } => {
11630                assert_eq!(de, "payment");
11631                assert_eq!(para, "catalog");
11632                assert_eq!(slot, "check out/$order");
11633                assert!(!reason.is_empty(), "reason field must be non-empty");
11634            }
11635            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
11636        }
11637    }
11638
11639    #[test]
11640    fn target_view_store_slot_passes_through_to_typed_view() {
11641        // The compounding theorem on the store axis: every
11642        // `WitTarget::Store { slot }` returned by `target()` carries a
11643        // kv-backend-accepted slot template. Renderers downstream of
11644        // `typed_view()` (the future per-Servico `:capabilities
11645        // wasi:keyvalue/store` axis emitter, the future `feira app
11646        // graph` view's slot labeller, the future kv-provider CR
11647        // materializer) can rely on this without re-checking — the
11648        // type system carries the proof. Mirrors
11649        // `target_view_pubsub_subject_passes_through_to_typed_view` on
11650        // the peer payload axis.
11651        let store = WitContract {
11652            de: "a".into(),
11653            para: "b".into(),
11654            wit: "wasi:keyvalue/store".into(),
11655            endpoint: None,
11656            subject: None,
11657            slot: Some("checkout/$orderId".into()),
11658        };
11659        match store.target().unwrap() {
11660            WitTarget::Store { slot } => {
11661                assert_eq!(slot, "checkout/$orderId");
11662            }
11663            other => panic!("expected Store, got {other:?}"),
11664        }
11665    }
11666
11667    #[test]
11668    fn rejects_self_loop_in_synchronous_contratos() {
11669        // A synchronous self-edge (`cart → cart` over HTTP) is now
11670        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
11671        // "this edge is degenerate" diagnostic — rather than incidentally
11672        // by the cycle detector framing it as a `["cart", "cart"]`
11673        // multi-node deadlock.
11674        let mut s = three_member_spec();
11675        s.contratos.push(contract_http("cart", "cart", "/loop"));
11676        let err = s.validate().unwrap_err();
11677        match err {
11678            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11679                assert_eq!(caixa, "cart");
11680                assert_eq!(wit, "wasi:http/proxy");
11681            }
11682            other => panic!("expected ContratoSelfLoop, got {other:?}"),
11683        }
11684    }
11685
11686    #[test]
11687    fn rejects_self_loop_in_pubsub_contratos() {
11688        // The cycle detector excludes pub-sub edges (acyclic by
11689        // construction), so before the explicit gate a `nats:pub-sub`
11690        // self-edge silently validated and rendered a self-allow CNP.
11691        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
11692        let mut s = three_member_spec();
11693        s.contratos.push(WitContract {
11694            de: "payment".into(),
11695            para: "payment".into(),
11696            wit: "nats:pub-sub".into(),
11697            endpoint: None,
11698            subject: Some("rio.events.payment".into()),
11699            slot: None,
11700        });
11701        let err = s.validate().unwrap_err();
11702        match err {
11703            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11704                assert_eq!(caixa, "payment");
11705                assert_eq!(wit, "nats:pub-sub");
11706            }
11707            other => panic!("expected ContratoSelfLoop, got {other:?}"),
11708        }
11709    }
11710
11711    #[test]
11712    fn self_loop_fires_before_payload_shape_check() {
11713        // The structural "this edge can't exist" error precedes the
11714        // narrower payload-shape diagnostics: a self-edge carrying an
11715        // otherwise-malformed endpoint still reports ContratoSelfLoop,
11716        // not ContratoEndpointInvalid.
11717        let mut s = three_member_spec();
11718        s.contratos.push(WitContract {
11719            de: "cart".into(),
11720            para: "cart".into(),
11721            wit: "wasi:http/proxy".into(),
11722            endpoint: Some("not-absolute".into()),
11723            subject: None,
11724            slot: None,
11725        });
11726        match s.validate().unwrap_err() {
11727            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
11728            other => panic!("expected ContratoSelfLoop, got {other:?}"),
11729        }
11730    }
11731
11732    #[test]
11733    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
11734        // A self-edge naming a non-member reports the more fundamental
11735        // ContratoMemberMissing first (the member doesn't exist), so the
11736        // self-loop gate is reached only once both endpoints resolve.
11737        let mut s = three_member_spec();
11738        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
11739        match s.validate().unwrap_err() {
11740            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
11741            other => panic!("expected ContratoMemberMissing, got {other:?}"),
11742        }
11743    }
11744
11745    #[test]
11746    fn rejects_two_node_synchronous_cycle() {
11747        let mut s = three_member_spec();
11748        // existing edges: cart → catalog, cart → payment
11749        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
11750        s.contratos
11751            .push(contract_http("catalog", "cart", "/refresh"));
11752        let err = s.validate().unwrap_err();
11753        match err {
11754            AplicacaoError::ContratoCycle { cycle } => {
11755                // Cycle traversal should mention both endpoints, with
11756                // the back-edge target appearing as both first and last
11757                // element to close the loop.
11758                assert!(cycle.len() >= 3);
11759                assert_eq!(cycle.first(), cycle.last());
11760                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11761                assert!(body.contains("cart"));
11762                assert!(body.contains("catalog"));
11763            }
11764            other => panic!("expected ContratoCycle, got {other:?}"),
11765        }
11766    }
11767
11768    #[test]
11769    fn rejects_three_node_synchronous_cycle() {
11770        let mut s = three_member_spec();
11771        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
11772        s.contratos = vec![
11773            contract_http("catalog", "cart", "/x"),
11774            contract_http("cart", "payment", "/y"),
11775            contract_http("payment", "catalog", "/z"),
11776        ];
11777        let err = s.validate().unwrap_err();
11778        match err {
11779            AplicacaoError::ContratoCycle { cycle } => {
11780                assert_eq!(cycle.first(), cycle.last());
11781                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11782                assert_eq!(body.len(), 3);
11783                assert!(body.contains("cart"));
11784                assert!(body.contains("catalog"));
11785                assert!(body.contains("payment"));
11786            }
11787            other => panic!("expected ContratoCycle, got {other:?}"),
11788        }
11789    }
11790
11791    #[test]
11792    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
11793        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
11794        // "acyclic by construction" — so a cycle whose closing edge
11795        // is pub-sub should NOT raise ContratoCycle.
11796        let mut s = three_member_spec();
11797        s.contratos = vec![
11798            contract_http("catalog", "cart", "/x"),
11799            contract_http("cart", "payment", "/y"),
11800            // Closing edge is pub-sub — async; not a sync deadlock.
11801            WitContract {
11802                de: "payment".into(),
11803                para: "catalog".into(),
11804                wit: "nats:pub-sub".into(),
11805                endpoint: None,
11806                subject: Some("checkout.events.charge.completed".into()),
11807                slot: None,
11808            },
11809        ];
11810        s.validate().expect("pub-sub edge breaks the sync cycle");
11811    }
11812
11813    #[test]
11814    fn store_edge_counts_as_synchronous_for_cycle_detection() {
11815        // wasi:keyvalue/store is request/response; a cycle through one
11816        // *is* a sync deadlock, just like HTTP.
11817        let mut s = three_member_spec();
11818        s.contratos = vec![
11819            contract_http("catalog", "cart", "/x"),
11820            WitContract {
11821                de: "cart".into(),
11822                para: "catalog".into(),
11823                wit: "wasi:keyvalue/store".into(),
11824                endpoint: None,
11825                subject: None,
11826                slot: Some("session/$id".into()),
11827            },
11828        ];
11829        let err = s.validate().unwrap_err();
11830        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11831    }
11832
11833    #[test]
11834    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
11835        // Capability-only edges (unknown WIT shape, no payload) default
11836        // to synchronous — safer; authors with truly async capability
11837        // semantics can model them as pub-sub explicitly.
11838        let mut s = three_member_spec();
11839        s.contratos = vec![
11840            contract_http("catalog", "cart", "/x"),
11841            WitContract {
11842                de: "cart".into(),
11843                para: "catalog".into(),
11844                wit: "custom:exchange".into(),
11845                endpoint: None,
11846                subject: None,
11847                slot: None,
11848            },
11849        ];
11850        let err = s.validate().unwrap_err();
11851        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11852    }
11853
11854    #[test]
11855    fn long_acyclic_chain_validates() {
11856        // A long sync chain (no back-edges) must validate even when
11857        // every node is reachable from the first.
11858        let mut s = three_member_spec();
11859        s.membros = vec![
11860            membro("a", "^0.1"),
11861            membro("b", "^0.1"),
11862            membro("c", "^0.1"),
11863            membro("d", "^0.1"),
11864            membro("e", "^0.1"),
11865        ];
11866        s.contratos = vec![
11867            contract_http("a", "b", "/1"),
11868            contract_http("b", "c", "/2"),
11869            contract_http("c", "d", "/3"),
11870            contract_http("d", "e", "/4"),
11871        ];
11872        s.entrada.as_mut().unwrap().para = "a".into();
11873        s.validate().unwrap();
11874    }
11875
11876    #[test]
11877    fn diamond_acyclic_validates() {
11878        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
11879        let mut s = three_member_spec();
11880        s.membros = vec![
11881            membro("a", "^0.1"),
11882            membro("b", "^0.1"),
11883            membro("c", "^0.1"),
11884            membro("d", "^0.1"),
11885        ];
11886        s.contratos = vec![
11887            contract_http("a", "b", "/1"),
11888            contract_http("a", "c", "/2"),
11889            contract_http("b", "d", "/3"),
11890            contract_http("c", "d", "/4"),
11891        ];
11892        s.entrada.as_mut().unwrap().para = "a".into();
11893        s.validate().unwrap();
11894    }
11895
11896    // ── duplicate-`:contratos` build-error gate ──────────────────────────
11897
11898    #[test]
11899    fn rejects_duplicate_http_contrato() {
11900        // Fail-before-pass-after pin: the fixture's `cart → catalog`
11901        // HTTP edge appears once. Push an identical entry — same
11902        // (de, para, wit, endpoint) — and validate() must reject it.
11903        // Until this gate landed the typed surface accepted the
11904        // duplicate silently and caixa-mesh's `cilium_network_policies`
11905        // emitted two ``CiliumNetworkPolicy`` objects with identical
11906        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
11907        // admission rejects on `kubectl apply` far from the source.
11908        let mut s = three_member_spec();
11909        s.contratos
11910            .push(contract_http("cart", "catalog", "/products/:id"));
11911        let err = s.validate().unwrap_err();
11912        assert!(
11913            matches!(
11914                err,
11915                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11916                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
11917            ),
11918            "got {err:?}"
11919        );
11920    }
11921
11922    #[test]
11923    fn rejects_duplicate_pubsub_contrato() {
11924        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
11925        // edges with identical (de, para, subject) are degenerate;
11926        // pin that the typed surface refuses both at validate time.
11927        let mut s = three_member_spec();
11928        let pubsub = WitContract {
11929            de: "payment".into(),
11930            para: "cart".into(),
11931            wit: "nats:pub-sub".into(),
11932            endpoint: None,
11933            subject: Some("checkout.events.charge.failed".into()),
11934            slot: None,
11935        };
11936        s.contratos.push(pubsub.clone());
11937        s.contratos.push(pubsub);
11938        let err = s.validate().unwrap_err();
11939        assert!(
11940            matches!(
11941                err,
11942                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11943                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
11944            ),
11945            "got {err:?}"
11946        );
11947    }
11948
11949    #[test]
11950    fn rejects_duplicate_store_contrato() {
11951        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
11952        // edges with identical (de, para, slot) collapse to one mesh-
11953        // policy edge; pin the build error.
11954        let mut s = three_member_spec();
11955        let store = WitContract {
11956            de: "cart".into(),
11957            para: "payment".into(),
11958            wit: "wasi:keyvalue/store".into(),
11959            endpoint: None,
11960            subject: None,
11961            slot: Some("checkout/$orderId".into()),
11962        };
11963        // Drop the conflicting HTTP `cart → payment` edge from the
11964        // fixture so the duplicate-store pair is the only one
11965        // distinguishable on this pair.
11966        s.contratos
11967            .retain(|c| !(c.de == "cart" && c.para == "payment"));
11968        s.contratos.push(store.clone());
11969        s.contratos.push(store);
11970        let err = s.validate().unwrap_err();
11971        assert!(
11972            matches!(
11973                err,
11974                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11975                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
11976            ),
11977            "got {err:?}"
11978        );
11979    }
11980
11981    #[test]
11982    fn rejects_duplicate_capability_contrato() {
11983        // Same gate on the pure-capability axis (no payload selector).
11984        // Two contracts with identical (de, para, wit) and no
11985        // endpoint/subject/slot are duplicate edges; pin so a future
11986        // `target_label` change can't accidentally collapse the
11987        // capability arm into a None-shaped key that compares equal
11988        // to a populated one.
11989        let mut s = three_member_spec();
11990        let capability = WitContract {
11991            de: "cart".into(),
11992            para: "catalog".into(),
11993            wit: "pleme:cap/audit".into(),
11994            endpoint: None,
11995            subject: None,
11996            slot: None,
11997        };
11998        s.contratos.push(capability.clone());
11999        s.contratos.push(capability);
12000        let err = s.validate().unwrap_err();
12001        match err {
12002            AplicacaoError::ContratoDuplicate {
12003                de,
12004                para,
12005                wit,
12006                target,
12007            } => {
12008                assert_eq!(de, "cart");
12009                assert_eq!(para, "catalog");
12010                assert_eq!(wit, "pleme:cap/audit");
12011                assert!(
12012                    target.contains("capability"),
12013                    "capability-edge duplicate diagnostic must surface the \
12014                     no-payload shape (got target = {target:?})"
12015                );
12016            }
12017            other => panic!("expected ContratoDuplicate, got {other:?}"),
12018        }
12019    }
12020
12021    #[test]
12022    fn accepts_distinct_http_paths_between_same_pair() {
12023        // Negative pin: two HTTP contracts cart → catalog at distinct
12024        // endpoints (`/products/:id` and `/search`) are *not*
12025        // duplicates — they're distinct typed edges differing on the
12026        // payload axis. The duplicate-gate must not over-match here,
12027        // since the cart-calls-catalog-on-multiple-paths shape is the
12028        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
12029        // example: cart calls catalog at /products/:id, payment at
12030        // /charge — same shape extends to two paths on one para).
12031        let mut s = three_member_spec();
12032        s.contratos
12033            .push(contract_http("cart", "catalog", "/search"));
12034        s.validate()
12035            .expect("distinct endpoints between same (de, para) must validate");
12036    }
12037
12038    #[test]
12039    fn accepts_same_endpoint_on_different_pairs() {
12040        // Negative pin: the same `/charge` endpoint reused on two
12041        // different (de, para) pairs is two distinct edges, not a
12042        // duplicate. Pinning this shape so the gate's identity key
12043        // includes both `de` and `para` (not just `(wit, endpoint)`).
12044        let mut s = three_member_spec();
12045        s.contratos
12046            .push(contract_http("payment", "catalog", "/charge"));
12047        s.validate()
12048            .expect("same endpoint reused on distinct (de, para) must validate");
12049    }
12050
12051    #[test]
12052    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
12053        // Pin the diagnostic shape: the duplicate-edge error names
12054        // *which* target field carried the conflict, so the author
12055        // doesn't have to re-grep the source caixa.lisp to find it.
12056        // Same self-locating diagnostic discipline as
12057        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
12058        let mut s = three_member_spec();
12059        s.contratos
12060            .push(contract_http("cart", "catalog", "/products/:id"));
12061        let err = s.validate().unwrap_err();
12062        let msg = format!("{err}");
12063        assert!(
12064            msg.contains("\"/products/:id\""),
12065            "duplicate-contrato diagnostic must name the offending \
12066             :endpoint payload (got: {msg:?})"
12067        );
12068        assert!(
12069            msg.contains("cart") && msg.contains("catalog"),
12070            "diagnostic must name both endpoints of the duplicate edge \
12071             (got: {msg:?})"
12072        );
12073    }
12074
12075    #[test]
12076    fn duplicate_contrato_gate_runs_after_membership_check() {
12077        // Order pin: a duplicate contract whose `:de` is *also* not in
12078        // `:membros` surfaces the membership error first — the
12079        // missing-member diagnostic is more locating than the
12080        // duplicate-edge one (the author has to fix the membership
12081        // before the duplicate is meaningful). Same ordering
12082        // discipline as `membros_validation_runs_before_contratos_membership_check`.
12083        let mut s = three_member_spec();
12084        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12085        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12086        let err = s.validate().unwrap_err();
12087        assert!(
12088            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
12089            "membership-missing must fire before duplicate-edge (got {err:?})"
12090        );
12091    }
12092
12093    #[test]
12094    fn duplicate_contrato_gate_runs_after_target_shape_check() {
12095        // Order pin: a contract with a malformed target (e.g. an HTTP
12096        // wit world with an empty :endpoint) surfaces the target-shape
12097        // error first, not the duplicate one. Even when two such
12098        // malformed entries are identical, the per-contract `target()`
12099        // check fires inside the loop *before* the duplicate-key
12100        // insert, so the diagnostic remains the most-locating one.
12101        let mut s = three_member_spec();
12102        let malformed = WitContract {
12103            de: "cart".into(),
12104            para: "catalog".into(),
12105            wit: "wasi:http/proxy".into(),
12106            endpoint: Some(String::new()),
12107            subject: None,
12108            slot: None,
12109        };
12110        s.contratos.push(malformed.clone());
12111        s.contratos.push(malformed);
12112        let err = s.validate().unwrap_err();
12113        assert!(
12114            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12115            "endpoint-empty must fire before duplicate-edge (got {err:?})"
12116        );
12117    }
12118
12119    #[test]
12120    fn wit_target_label_pins_per_variant_format() {
12121        // Label format is the single source of truth every duplicate-
12122        // `:contratos` diagnostic + every future `feira app graph`
12123        // consumer routes through. Pin the shape per variant so a
12124        // future edit to `WitTarget::label` (e.g. a JSON emitter that
12125        // strips the leading `:`, or a rename from `endpoint` →
12126        // `path`) surfaces as a red-red test rather than as a silent
12127        // downstream diagnostic drift. Together with the exhaustive
12128        // `match` on `WitTarget` inside `label()`, adding a future
12129        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
12130        // peer, per-edge WIT registry variants) is a compile error at
12131        // the label site — not a fall-through into the `Capability`
12132        // "no payload" default the prior raw-field-probe helper
12133        // silently landed on.
12134        assert_eq!(
12135            WitTarget::Http {
12136                endpoint: "/charge",
12137            }
12138            .label(),
12139            "\
12140:endpoint \"/charge\""
12141        );
12142        assert_eq!(
12143            WitTarget::PubSub {
12144                subject: "events.checkout.paid",
12145            }
12146            .label(),
12147            "\
12148:subject \"events.checkout.paid\""
12149        );
12150        assert_eq!(
12151            WitTarget::Store {
12152                slot: "checkout/$order",
12153            }
12154            .label(),
12155            "\
12156:slot \"checkout/$order\""
12157        );
12158        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
12159        // Capability-arm label routes through the lifted
12160        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
12161        // declaration per arm, next to the variant" discipline the
12162        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
12163        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12164        // consts already carry extends to the payload-less arm; the
12165        // byte-string equality pin below plus this label-routes-
12166        // through-the-const pin make a future rebrand on either the
12167        // const declaration or the `label()` template a build error
12168        // here rather than a downstream consumer surprise.
12169        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
12170        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
12171    }
12172
12173    #[test]
12174    fn wit_target_display_routes_through_label_helper() {
12175        // Fail-before-pass-after pin on the fourth (and only remaining)
12176        // typed-shape-discriminator axis to converge onto the
12177        // three-path-convergence discipline the sibling M3
12178        // [`PlacementStrategy`] (0a2f653) and M2
12179        // [`crate::supervisor::RestartStrategy`] /
12180        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
12181        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
12182        // through [`WitTarget::label`], so every consumer reaching for
12183        // `format!("{v}")` on a typed payload target lands on the same
12184        // stable author-facing byte-string [`WitTarget::label`] returns
12185        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
12186        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
12187        // `:contratos` gate seeds via [`WitTarget::label`] at
12188        // aplicacao.rs:5491 already threads through.
12189        //
12190        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
12191        // through to the `Debug` derive's structural output
12192        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
12193        // rather than the [`WitTarget::label`] helper's stable byte-
12194        // string (`:endpoint "/charge"` — the author-facing `:contratos`
12195        // keyword form). Every future consumer that reaches for
12196        // `format!("{target}")` — the canonical shape every user-facing
12197        // pretty-print site on the sibling typed-enum axes
12198        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
12199        // [`crate::supervisor::RestartPolicy`]) already uses — would
12200        // silently land under a different byte-string than the
12201        // [`WitTarget::label`] callers that the duplicate-`:contratos`
12202        // diagnostic already threads through, with the mismatch
12203        // surfacing as a downstream diagnostic / graph / audit line
12204        // reading one spelling while the substrate's own gate emitted
12205        // another.
12206        //
12207        // Pin the routing here so a future
12208        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
12209        // that hand-rolls the per-arm formatting instead of delegating
12210        // to [`WitTarget::label`] fails at caixa-core build time.
12211        for variant in [
12212            WitTarget::Http {
12213                endpoint: "/charge",
12214            },
12215            WitTarget::PubSub {
12216                subject: "events.checkout.paid",
12217            },
12218            WitTarget::Store {
12219                slot: "checkout/$order",
12220            },
12221            WitTarget::Capability,
12222        ] {
12223            assert_eq!(
12224                variant.to_string(),
12225                variant.label(),
12226                "WitTarget::{variant:?} Display must route through \
12227                 WitTarget::label (single source of truth: the lifted \
12228                 payload_pair 4-arm dispatch the label helper already \
12229                 threads through)"
12230            );
12231        }
12232    }
12233
12234    #[test]
12235    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
12236        // Consumer-side pin on the three-path convergence:
12237        // [`std::fmt::Display`] agrees byte-for-byte with the
12238        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
12239        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
12240        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
12241        // Pre-lift the two paths were structurally independent — the
12242        // substrate-side gate reached for `target_view.label()` while a
12243        // future downstream diagnostic / graph / audit line reaching
12244        // for `format!("{target}")` would silently land on the `Debug`
12245        // derive's structural output. Pin the two paths byte-for-byte
12246        // here so any future variant addition (M4 `Rest`/`Grpc` split
12247        // of [`WitTarget::Http`], `Queue`-shaped peer of
12248        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
12249        // match error at [`WitTarget::payload_pair`] rather than a
12250        // silent per-consumer dispatch miss.
12251        for variant in [
12252            WitTarget::Http {
12253                endpoint: "/charge",
12254            },
12255            WitTarget::PubSub {
12256                subject: "events.checkout.paid",
12257            },
12258            WitTarget::Store {
12259                slot: "checkout/$order",
12260            },
12261            WitTarget::Capability,
12262        ] {
12263            assert_eq!(
12264                format!("{variant}"),
12265                variant.label(),
12266                "WitTarget::{variant:?} Display byte-string must match \
12267                 the AplicacaoError::ContratoDuplicate `target:` carrier \
12268                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
12269                 seeds via WitTarget::label — three-path convergence: \
12270                 Display + label + payload_pair all resolve to the same \
12271                 per-arm byte-string"
12272            );
12273        }
12274    }
12275
12276    #[test]
12277    fn wit_target_payload_pair_pins_per_variant() {
12278        // Pin the per-arm `(field-name, payload)` pair single-sourced
12279        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
12280        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
12281        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
12282        // and [`WitTarget::field_name`] (returns the first component)
12283        // route through. Until this lift landed [`WitTarget::label`]
12284        // dispatched on the same three arms with a per-arm
12285        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
12286        // paired [`WitTarget::HTTP_FIELD_NAME`] /
12287        // [`WitTarget::PUBSUB_FIELD_NAME`] /
12288        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
12289        // canonical "same shape, written N times" duplication
12290        // THEORY.md §I.3.5 promotes to a build-time concern. A future
12291        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
12292        // [`WitTarget::Http`], `Queue`-shaped peer of
12293        // [`WitTarget::Store`]) is one match-arm edit at
12294        // [`WitTarget::payload_pair`], visible here as a compile-time
12295        // exhaustiveness error on both this pin and the label-format
12296        // pin above.
12297        assert_eq!(
12298            WitTarget::Http {
12299                endpoint: "/charge"
12300            }
12301            .payload_pair(),
12302            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
12303        );
12304        assert_eq!(
12305            WitTarget::PubSub {
12306                subject: "events.x",
12307            }
12308            .payload_pair(),
12309            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
12310        );
12311        assert_eq!(
12312            WitTarget::Store {
12313                slot: "checkout/$order",
12314            }
12315            .payload_pair(),
12316            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
12317        );
12318        assert_eq!(WitTarget::Capability.payload_pair(), None);
12319    }
12320
12321    #[test]
12322    fn wit_target_field_name_pins_per_variant() {
12323        // Pin the per-arm author-facing `:contratos` payload field
12324        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
12325        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12326        // + returned by [`WitTarget::field_name`]. Every downstream
12327        // consumer (the [`WitContract::target`] gate's `expected:`
12328        // scalar, the [`WitTarget::label`] template's keyword prefix,
12329        // the `feira app graph` verb's `endpoint=…` prefix) routes
12330        // through the same three peer consts, so a rename on the
12331        // author-surface `(defcaixa … :contratos ((:de … :para …
12332        // :wit … :endpoint …)))` field lands in exactly one place.
12333        assert_eq!(
12334            WitTarget::Http {
12335                endpoint: "/charge"
12336            }
12337            .field_name(),
12338            Some(WitTarget::HTTP_FIELD_NAME),
12339        );
12340        assert_eq!(
12341            WitTarget::PubSub {
12342                subject: "events.x",
12343            }
12344            .field_name(),
12345            Some(WitTarget::PUBSUB_FIELD_NAME),
12346        );
12347        assert_eq!(
12348            WitTarget::Store {
12349                slot: "checkout/$order",
12350            }
12351            .field_name(),
12352            Some(WitTarget::STORE_FIELD_NAME),
12353        );
12354        // Capability arm carries no payload field — the diagnostic
12355        // never reports `expected: "capability"` because the gate's
12356        // Capability arm accepts no payload at all (it fires the
12357        // "expected: none" WrongTarget error instead), so the field-
12358        // name method returns None here rather than a placeholder.
12359        assert_eq!(WitTarget::Capability.field_name(), None);
12360
12361        // Peer const scalar values pinned so a rename on either side
12362        // (author-surface field name in the `(defcaixa …)` DSL, or
12363        // the diagnostic's `expected:` scalar) can't drift without
12364        // failing here first.
12365        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
12366        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
12367        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
12368    }
12369
12370    #[test]
12371    fn wit_target_payload_pins_per_variant() {
12372        // Pin the per-arm payload scalar single-sourced onto the
12373        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
12374        // [`WitTarget::payload`] — the peer per-half projection to
12375        // [`WitTarget::field_name`] on the paired sub-selector axis. The
12376        // three payload-carrying arms round-trip their author-declared
12377        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
12378        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
12379        // the payload-less [`WitTarget::Capability`] arm returns `None`.
12380        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
12381        // (c6ec2af) pin on the Component-0 projection axis, extended
12382        // onto the Component-1 projection axis so both per-half readers
12383        // on the paired dispatch carry their own byte-shape pin.
12384        assert_eq!(
12385            WitTarget::Http {
12386                endpoint: "/charge",
12387            }
12388            .payload(),
12389            Some("/charge"),
12390        );
12391        assert_eq!(
12392            WitTarget::PubSub {
12393                subject: "events.x",
12394            }
12395            .payload(),
12396            Some("events.x"),
12397        );
12398        assert_eq!(
12399            WitTarget::Store {
12400                slot: "checkout/$order",
12401            }
12402            .payload(),
12403            Some("checkout/$order"),
12404        );
12405        assert_eq!(WitTarget::Capability.payload(), None);
12406    }
12407
12408    #[test]
12409    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
12410        // Per-variant equivalence pin: for every arm of [`WitTarget`],
12411        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
12412        // byte-for-byte. Guards the drift surface where a future refactor
12413        // that split one accessor off the shared match onto its own
12414        // dispatch — a well-meaning "inline the pair back into per-half
12415        // fields for one crate-internal caller who only wanted one half"
12416        // or a scratch `impl` shadowing the derived projection — would
12417        // silently desynchronize [`WitTarget::payload`] from the
12418        // authoritative [`WitTarget::payload_pair`] dispatch, and every
12419        // downstream consumer that thinks "the payload half of the pair"
12420        // would drift from the diagnostic / graph consumers reading the
12421        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
12422        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
12423        // per-half projection pin (`gitrefspec_ref_pair_projects_
12424        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
12425        // FluxCD source-controller `spec.ref.<field>` axis — same "one
12426        // paired dispatch, both per-half projections agree byte-for-
12427        // byte" discipline extended onto the M3 `:contratos` payload-
12428        // arm surface.
12429        for variant in [
12430            WitTarget::Http {
12431                endpoint: "/charge",
12432            },
12433            WitTarget::PubSub {
12434                subject: "events.checkout.paid",
12435            },
12436            WitTarget::Store {
12437                slot: "checkout/$order",
12438            },
12439            WitTarget::Capability,
12440        ] {
12441            let via_projection = variant.payload();
12442            let via_pair = variant.payload_pair().map(|(_, p)| p);
12443            assert_eq!(
12444                via_projection, via_pair,
12445                "WitTarget::{variant:?} payload() must equal \
12446                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
12447                 regression that splits the two per-half projections off \
12448                 their shared match would silently desynchronize the \
12449                 payload accessor from the paired dispatch every \
12450                 diagnostic / graph consumer reads through",
12451            );
12452        }
12453    }
12454
12455    #[test]
12456    fn wit_target_http_endpoint_pins_per_variant() {
12457        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
12458        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
12459        // substrate-primitive per-arm post-projection accessor every
12460        // L7-HTTP-facing consumer routes through, sibling to the peer
12461        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
12462        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
12463        // arm round-trips its author-declared endpoint verbatim as
12464        // `Some("/charge")`; the three sibling arms
12465        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
12466        // [`WitTarget::Capability`]) each return `None` because they
12467        // carry no HTTP endpoint by definition. Same fail-before-pass-
12468        // after per-variant discipline as the sibling
12469        // `wit_target_payload_pins_per_variant` (5d6dc92) /
12470        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
12471        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
12472        // the peer pan-arm / per-half projection axes — extended onto
12473        // the per-arm HTTP-shape post-projection axis so a future
12474        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
12475        // [`WitTarget::Http`], a `Queue`-shaped peer of
12476        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
12477        // error on the sibling [`WitTarget::http_endpoint`] match arms
12478        // whose payload the L7-HTTP-shape accept-set is meant to bound.
12479        assert_eq!(
12480            WitTarget::Http {
12481                endpoint: "/charge",
12482            }
12483            .http_endpoint(),
12484            Some("/charge"),
12485        );
12486        assert_eq!(
12487            WitTarget::PubSub {
12488                subject: "events.checkout.paid",
12489            }
12490            .http_endpoint(),
12491            None,
12492        );
12493        assert_eq!(
12494            WitTarget::Store {
12495                slot: "checkout/$order",
12496            }
12497            .http_endpoint(),
12498            None,
12499        );
12500        assert_eq!(WitTarget::Capability.http_endpoint(), None);
12501    }
12502
12503    #[test]
12504    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
12505        // Per-variant coherence pin: for every arm of [`WitTarget`],
12506        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
12507        // arm (both project the same author-declared request-path
12508        // scalar), and returns `None` on every sibling arm regardless of
12509        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
12510        // Store carry their own payload the pan-arm accessor surfaces,
12511        // but that payload is not an HTTP endpoint — the per-arm
12512        // accessor must not leak it through the HTTP-shape channel).
12513        // Guards the drift surface where a future refactor that
12514        // conflated the per-arm HTTP projection with the pan-arm
12515        // [`WitTarget::payload`] projection — a well-meaning "one
12516        // accessor for the L7 branch, one for the graph" collapse that
12517        // routes both through the same 4-arm dispatch — would silently
12518        // widen the L7-HTTP-shape accept-set onto pub-sub / store
12519        // payloads at the caixa-mesh L7 emit branch, admitting a
12520        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
12521        // rule with the operator-side apply-time symptom (Cilium's
12522        // eBPF data-plane rejects every ingress edge whose L7 filter
12523        // doesn't match the wire-format HTTP request line) far from
12524        // the source refactor. Sibling to the peer
12525        // `wit_target_payload_matches_payload_pair_second_component_
12526        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
12527        // extended onto the per-arm HTTP specialization axis so both
12528        // the pan-arm and the per-arm projections carry their own
12529        // byte-shape coherence witness against the substrate's typed
12530        // arm-family accept-set.
12531        for variant in [
12532            WitTarget::Http {
12533                endpoint: "/charge",
12534            },
12535            WitTarget::PubSub {
12536                subject: "events.checkout.paid",
12537            },
12538            WitTarget::Store {
12539                slot: "checkout/$order",
12540            },
12541            WitTarget::Capability,
12542        ] {
12543            let per_arm = variant.http_endpoint();
12544            let pan_arm = variant.payload();
12545            if variant.is_http() {
12546                assert_eq!(
12547                    per_arm, pan_arm,
12548                    "WitTarget::{variant:?} http_endpoint() must equal \
12549                     payload() on the Http arm — a per-arm-vs-pan-arm \
12550                     split would silently drift the L7 emit branch's \
12551                     path-scalar source from the graph verb's payload \
12552                     scalar source",
12553                );
12554            } else {
12555                assert_eq!(
12556                    per_arm, None,
12557                    "WitTarget::{variant:?} http_endpoint() must return \
12558                     None on non-Http arms — a leak that surfaced a \
12559                     pub-sub :subject or a key/value :slot through the \
12560                     HTTP-endpoint accessor would silently widen the \
12561                     Cilium L7 HTTP `path:` rule accept-set onto \
12562                     protocol shapes Cilium's eBPF data-plane can't \
12563                     introspect",
12564                );
12565            }
12566        }
12567    }
12568
12569    #[test]
12570    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
12571        // Per-variant coherence pin: for every arm of [`WitTarget`],
12572        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
12573        // drift surface where a future extension of the
12574        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
12575        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
12576        // accessor to cover both peers) landed without a paired
12577        // extension of the [`gen_platform::IsVariant`]-derived
12578        // `is_http()` predicate's accept-set, or vice versa — a
12579        // regression that split the "which arms count as HTTP-shaped
12580        // for L7-path emission?" answer between two dispatch surfaces
12581        // the substrate ships. Sibling to the peer
12582        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
12583        // on the paired dispatch axis — extended onto the per-arm
12584        // predicate-vs-accessor coherence axis so the gen-platform
12585        // IsVariant predicate and the substrate-lifted per-arm
12586        // accessor carry one shared answer to "is this the HTTP arm?".
12587        for variant in [
12588            WitTarget::Http {
12589                endpoint: "/charge",
12590            },
12591            WitTarget::PubSub {
12592                subject: "events.checkout.paid",
12593            },
12594            WitTarget::Store {
12595                slot: "checkout/$order",
12596            },
12597            WitTarget::Capability,
12598        ] {
12599            assert_eq!(
12600                variant.http_endpoint().is_some(),
12601                variant.is_http(),
12602                "WitTarget::{variant:?} http_endpoint().is_some() must \
12603                 equal is_http() — a drift would split the L7 emit \
12604                 branch's arm-set gate from the substrate-derived \
12605                 shape-discrimination predicate on the same axis",
12606            );
12607        }
12608    }
12609
12610    #[test]
12611    fn wit_target_pubsub_subject_pins_per_variant() {
12612        // Fail-before-pass-after pin: the substrate-canonical per-arm
12613        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
12614        // is the single dispatch every future pub-sub-facing consumer
12615        // routes through, sibling to the peer [`WitContract::subject`]
12616        // (63e18a0) pre-projection scalar accessor on the raw-field
12617        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
12618        // post-projection per-arm accessor on the sibling HTTP-shape
12619        // axis. The [`WitTarget::PubSub`] arm round-trips its
12620        // author-declared subject verbatim as
12621        // `Some("events.checkout.paid")`; the three sibling arms each
12622        // return `None` because they carry no NATS-shaped subject by
12623        // definition. Same fail-before-pass-after per-variant discipline
12624        // as the sibling `wit_target_http_endpoint_pins_per_variant`
12625        // pin on the peer per-arm axis — extended onto the per-arm
12626        // pub-sub-shape post-projection axis so a future [`WitTarget`]
12627        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
12628        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
12629        // compile-time exhaustiveness error on the sibling
12630        // [`WitTarget::pubsub_subject`] match arms whose payload the
12631        // pub-sub-shape accept-set is meant to bound.
12632        assert_eq!(
12633            WitTarget::PubSub {
12634                subject: "events.checkout.paid",
12635            }
12636            .pubsub_subject(),
12637            Some("events.checkout.paid"),
12638        );
12639        assert_eq!(
12640            WitTarget::Http {
12641                endpoint: "/charge",
12642            }
12643            .pubsub_subject(),
12644            None,
12645        );
12646        assert_eq!(
12647            WitTarget::Store {
12648                slot: "checkout/$order",
12649            }
12650            .pubsub_subject(),
12651            None,
12652        );
12653        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
12654    }
12655
12656    #[test]
12657    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
12658        // Per-variant coherence pin: for every arm of [`WitTarget`],
12659        // `.pubsub_subject()` equals `.payload()` on the
12660        // [`WitTarget::PubSub`] arm (both project the same
12661        // author-declared subject scalar), and returns `None` on every
12662        // sibling arm regardless of whether [`WitTarget::payload`]
12663        // itself returns `Some` (Http / Store carry their own payload
12664        // the pan-arm accessor surfaces, but that payload is not a
12665        // pub-sub subject — the per-arm accessor must not leak it
12666        // through the pub-sub-shape channel). Sibling to the peer
12667        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12668        // coherence pin on the per-arm HTTP-shape axis — extended onto
12669        // the per-arm pub-sub specialization axis so both per-arm
12670        // projections carry their own byte-shape coherence witness
12671        // against the substrate's typed arm-family accept-set.
12672        for variant in [
12673            WitTarget::Http {
12674                endpoint: "/charge",
12675            },
12676            WitTarget::PubSub {
12677                subject: "events.checkout.paid",
12678            },
12679            WitTarget::Store {
12680                slot: "checkout/$order",
12681            },
12682            WitTarget::Capability,
12683        ] {
12684            let per_arm = variant.pubsub_subject();
12685            let pan_arm = variant.payload();
12686            if variant.is_pubsub() {
12687                assert_eq!(
12688                    per_arm, pan_arm,
12689                    "WitTarget::{variant:?} pubsub_subject() must equal \
12690                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
12691                     split would silently drift the pub-sub-shape emit \
12692                     branch's subject-scalar source from the graph verb's \
12693                     payload scalar source",
12694                );
12695            } else {
12696                assert_eq!(
12697                    per_arm, None,
12698                    "WitTarget::{variant:?} pubsub_subject() must return \
12699                     None on non-PubSub arms — a leak that surfaced an \
12700                     HTTP :endpoint or a key/value :slot through the \
12701                     pub-sub-subject accessor would silently widen the \
12702                     downstream NATS-shape accept-set onto protocol \
12703                     shapes NATS servers can't route",
12704                );
12705            }
12706        }
12707    }
12708
12709    #[test]
12710    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
12711        // Per-variant coherence pin: for every arm of [`WitTarget`],
12712        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
12713        // drift surface where a future extension of the
12714        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
12715        // without a paired extension of the [`gen_platform::IsVariant`]-
12716        // derived `is_pubsub()` predicate's accept-set, or vice versa
12717        // — a regression that split the "which arms count as pub-sub-
12718        // shaped for subject emission?" answer between two dispatch
12719        // surfaces the substrate ships. Sibling to the peer
12720        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
12721        // pin on the per-arm HTTP-shape axis — extended onto the
12722        // per-arm pub-sub predicate-vs-accessor coherence axis so the
12723        // gen-platform IsVariant predicate and the substrate-lifted
12724        // per-arm accessor carry one shared answer to "is this the
12725        // PubSub arm?".
12726        for variant in [
12727            WitTarget::Http {
12728                endpoint: "/charge",
12729            },
12730            WitTarget::PubSub {
12731                subject: "events.checkout.paid",
12732            },
12733            WitTarget::Store {
12734                slot: "checkout/$order",
12735            },
12736            WitTarget::Capability,
12737        ] {
12738            assert_eq!(
12739                variant.pubsub_subject().is_some(),
12740                variant.is_pubsub(),
12741                "WitTarget::{variant:?} pubsub_subject().is_some() must \
12742                 equal is_pubsub() — a drift would split the pub-sub \
12743                 emit branch's arm-set gate from the substrate-derived \
12744                 shape-discrimination predicate on the same axis",
12745            );
12746        }
12747    }
12748
12749    #[test]
12750    fn wit_target_store_slot_pins_per_variant() {
12751        // Fail-before-pass-after pin: the substrate-canonical per-arm
12752        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
12753        // is the single dispatch every future store-facing consumer
12754        // routes through, sibling to the peer [`WitContract::slot`]
12755        // pre-projection scalar accessor on the raw-field axis and to
12756        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
12757        // [`WitTarget::pubsub_subject`] post-projection per-arm
12758        // accessors on the sibling per-payload-arm axes. The
12759        // [`WitTarget::Store`] arm round-trips its author-declared
12760        // slot verbatim as `Some("checkout/$order")`; the three
12761        // sibling arms each return `None` because they carry no
12762        // WASI-key/value slot by definition. Same fail-before-pass-
12763        // after per-variant discipline as the sibling
12764        // `wit_target_http_endpoint_pins_per_variant` +
12765        // `wit_target_pubsub_subject_pins_per_variant` pins on the
12766        // peer per-arm axes — extended onto the per-arm store-shape
12767        // post-projection axis so a future [`WitTarget`] variant
12768        // addition trips a compile-time exhaustiveness error on the
12769        // sibling [`WitTarget::store_slot`] match arms whose payload
12770        // the store-shape accept-set is meant to bound.
12771        assert_eq!(
12772            WitTarget::Store {
12773                slot: "checkout/$order",
12774            }
12775            .store_slot(),
12776            Some("checkout/$order"),
12777        );
12778        assert_eq!(
12779            WitTarget::Http {
12780                endpoint: "/charge",
12781            }
12782            .store_slot(),
12783            None,
12784        );
12785        assert_eq!(
12786            WitTarget::PubSub {
12787                subject: "events.checkout.paid",
12788            }
12789            .store_slot(),
12790            None,
12791        );
12792        assert_eq!(WitTarget::Capability.store_slot(), None);
12793    }
12794
12795    #[test]
12796    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
12797        // Per-variant coherence pin: for every arm of [`WitTarget`],
12798        // `.store_slot()` equals `.payload()` on the
12799        // [`WitTarget::Store`] arm (both project the same
12800        // author-declared slot scalar), and returns `None` on every
12801        // sibling arm regardless of whether [`WitTarget::payload`]
12802        // itself returns `Some`. Sibling to the peer
12803        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12804        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
12805        // pins on the per-arm HTTP and PubSub axes — closes the
12806        // per-arm-vs-pan-arm byte-shape coherence trio across all
12807        // three payload arms.
12808        for variant in [
12809            WitTarget::Http {
12810                endpoint: "/charge",
12811            },
12812            WitTarget::PubSub {
12813                subject: "events.checkout.paid",
12814            },
12815            WitTarget::Store {
12816                slot: "checkout/$order",
12817            },
12818            WitTarget::Capability,
12819        ] {
12820            let per_arm = variant.store_slot();
12821            let pan_arm = variant.payload();
12822            if variant.is_store() {
12823                assert_eq!(
12824                    per_arm, pan_arm,
12825                    "WitTarget::{variant:?} store_slot() must equal \
12826                     payload() on the Store arm — a per-arm-vs-pan-arm \
12827                     split would silently drift the store-shape emit \
12828                     branch's slot-scalar source from the graph verb's \
12829                     payload scalar source",
12830                );
12831            } else {
12832                assert_eq!(
12833                    per_arm, None,
12834                    "WitTarget::{variant:?} store_slot() must return \
12835                     None on non-Store arms — a leak that surfaced an \
12836                     HTTP :endpoint or a NATS :subject through the \
12837                     key/value-slot accessor would silently widen the \
12838                     downstream WASI-key/value slot accept-set onto \
12839                     protocol shapes the kv backends can't route",
12840                );
12841            }
12842        }
12843    }
12844
12845    #[test]
12846    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
12847        // Per-variant coherence pin: for every arm of [`WitTarget`],
12848        // `.store_slot().is_some()` iff `.is_store()`. Guards the
12849        // drift surface where a future extension of the
12850        // [`WitTarget::store_slot`] accessor's accept-set landed
12851        // without a paired extension of the [`gen_platform::IsVariant`]-
12852        // derived `is_store()` predicate's accept-set. Sibling to the
12853        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
12854        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
12855        // pins — closes the per-arm predicate-vs-accessor coherence
12856        // trio across all three payload arms so the gen-platform
12857        // IsVariant predicate and the substrate-lifted per-arm
12858        // accessor carry one shared answer to "is this the Store arm?".
12859        for variant in [
12860            WitTarget::Http {
12861                endpoint: "/charge",
12862            },
12863            WitTarget::PubSub {
12864                subject: "events.checkout.paid",
12865            },
12866            WitTarget::Store {
12867                slot: "checkout/$order",
12868            },
12869            WitTarget::Capability,
12870        ] {
12871            assert_eq!(
12872                variant.store_slot().is_some(),
12873                variant.is_store(),
12874                "WitTarget::{variant:?} store_slot().is_some() must \
12875                 equal is_store() — a drift would split the store-shape \
12876                 emit branch's arm-set gate from the substrate-derived \
12877                 shape-discrimination predicate on the same axis",
12878            );
12879        }
12880    }
12881
12882    #[test]
12883    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
12884        // Fail-before-pass-after cross-axis pin on the trio
12885        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
12886        // payload-carrying arm of [`WitTarget`], exactly one per-arm
12887        // accessor returns `Some(payload)` and the two peers return
12888        // `None`; and on the payload-less [`WitTarget::Capability`]
12889        // arm, all three return `None`. Guards the drift surface where
12890        // a future extension of one per-arm accessor's accept-set (e.g.
12891        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
12892        // that widened `http_endpoint` to cover both peers without
12893        // narrowing the peer `pubsub_subject` / `store_slot` accept-
12894        // sets to keep the partition mutually exclusive) landed without
12895        // threading through the peer per-arm accessors — the resulting
12896        // silent overlap would land the same edge's payload on two
12897        // downstream per-shape emit branches at once, or leak a
12898        // pub-sub subject through the store-slot channel, at renderer
12899        // emit time far from the substrate primitive's arm-widening
12900        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
12901        // 3-way pin on the payload-field-name axis — extended onto the
12902        // per-arm-accessor payload-projection axis so the substrate-
12903        // owned partition invariant is load-bearing at every per-arm
12904        // consumer's read site.
12905        let payload_variants = [
12906            (
12907                WitTarget::Http {
12908                    endpoint: "/charge",
12909                },
12910                "http",
12911            ),
12912            (
12913                WitTarget::PubSub {
12914                    subject: "events.checkout.paid",
12915                },
12916                "pubsub",
12917            ),
12918            (
12919                WitTarget::Store {
12920                    slot: "checkout/$order",
12921                },
12922                "store",
12923            ),
12924        ];
12925        for (variant, own_arm_label) in payload_variants {
12926            let own_arm_hit = match own_arm_label {
12927                "http" => variant.is_http(),
12928                "pubsub" => variant.is_pubsub(),
12929                "store" => variant.is_store(),
12930                other => panic!("unknown own-arm label {other:?}"),
12931            };
12932            let per_arm_results = [
12933                ("http_endpoint", variant.http_endpoint()),
12934                ("pubsub_subject", variant.pubsub_subject()),
12935                ("store_slot", variant.store_slot()),
12936            ];
12937            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
12938            assert_eq!(
12939                some_count, 1,
12940                "WitTarget::{variant:?} must land exactly one per-arm \
12941                 post-projection accessor's Some result — the trio \
12942                 (http_endpoint, pubsub_subject, store_slot) must \
12943                 partition the payload arm-set; got {per_arm_results:?}",
12944            );
12945            assert!(
12946                own_arm_hit,
12947                "WitTarget::{variant:?} own-arm gen-platform predicate \
12948                 must return true on its own arm — a partition failure \
12949                 upstream of this pin",
12950            );
12951            assert!(
12952                variant.payload().is_some(),
12953                "WitTarget::{variant:?} pan-arm payload() must return \
12954                 Some on every payload-carrying arm the trio partitions",
12955            );
12956        }
12957        // The payload-less Capability arm must return None on every
12958        // per-arm accessor — the partition's terminal-fallback shape.
12959        let cap = WitTarget::Capability;
12960        assert_eq!(cap.http_endpoint(), None);
12961        assert_eq!(cap.pubsub_subject(), None);
12962        assert_eq!(cap.store_slot(), None);
12963        assert_eq!(
12964            cap.payload(),
12965            None,
12966            "WitTarget::Capability pan-arm payload() must return None — \
12967             the trio's payload-less-arm coherence witness",
12968        );
12969    }
12970
12971    #[test]
12972    fn wit_target_field_names_are_pairwise_distinct() {
12973        // Distinctness pin: if any two of the three payload-field-name
12974        // scalars ever collapse (e.g. an accidental `endpoint` copy-
12975        // paste over the `subject` const), the [`WitContract::target`]
12976        // gate's diagnostic would point authors at the wrong field —
12977        // an "expected `:endpoint`" error on a pub-sub edge would
12978        // silently misroute the fix. Same cross-axis-distinctness
12979        // discipline as the peer M3 `:placement :estrategia` variant-
12980        // discriminator scalar-value pins (cc8f749) applied to the
12981        // payload-field-name axis.
12982        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
12983        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
12984        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
12985    }
12986
12987    #[test]
12988    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
12989        // Fail-before-pass-after pin: the graph-verb payload column's
12990        // per-arm `{field}={payload}` byte-string is derived through the
12991        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
12992        // payload-carrying arms, not through a hand-rolled per-arm match
12993        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
12994        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12995        // inline. A future variant addition — the M4-and-later per-edge
12996        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
12997        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
12998        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
12999        // and both [`WitTarget::label`] (duplicate-`:contratos`
13000        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13001        // payload column) pick up the new arm from the same dispatch.
13002        // Prior to this lift the graph verb open-coded the 4-arm match
13003        // in caixa-feira, so a variant addition would have to be threaded
13004        // through both projections in lockstep or the graph verb would
13005        // silently drop the new arm to `(capability-only)`.
13006        for variant in [
13007            WitTarget::Http {
13008                endpoint: "/charge",
13009            },
13010            WitTarget::PubSub {
13011                subject: "events.checkout.paid",
13012            },
13013            WitTarget::Store {
13014                slot: "checkout/$order",
13015            },
13016        ] {
13017            let (field, payload) = variant
13018                .payload_pair()
13019                .expect("payload arm must expose (field, payload)");
13020            assert_eq!(
13021                variant.graph_label(),
13022                format!("{field}={payload}"),
13023                "WitTarget::{variant:?} graph_label must route the \
13024                 `{{field}}={{payload}}` template through payload_pair — \
13025                 a regression to a hand-rolled per-arm match at the graph \
13026                 verb would silently disagree with a future variant \
13027                 addition landed only at payload_pair"
13028            );
13029        }
13030    }
13031
13032    #[test]
13033    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
13034        // Fail-before-pass-after pin on the payload-less arm: the graph
13035        // verb's `(capability-only)` byte-string routes through the
13036        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
13037        // [`WitTarget::Capability`] arm, not through an inline
13038        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
13039        // per-`:contratos` payload column. Peer of the sibling
13040        // [`wit_target_label_pins_per_variant_format`] Capability-arm
13041        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
13042        // extended here onto the third payload-less-arm consumer axis
13043        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
13044        // axis and the wrong-target diagnostic axis).
13045        assert_eq!(
13046            WitTarget::Capability.graph_label(),
13047            WitTarget::CAPABILITY_GRAPH_LABEL,
13048        );
13049        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
13050    }
13051
13052    #[test]
13053    fn wit_target_capability_graph_label_distinct_from_capability_label() {
13054        // Cross-consumer-axis distinctness pin: the graph-verb
13055        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
13056        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
13057        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
13058        // payload)`) surface the payload-less arm on two distinct
13059        // consumer axes; a collapse (an accidental rebrand that lands
13060        // one spelling on both consts, a copy-paste that unifies them
13061        // "for consistency") would silently merge the two byte-strings
13062        // and lose the vocabulary distinction the graph verb's
13063        // compact-column form and the diagnostic's descriptive-clause
13064        // form each carry on purpose. Peer of the sibling 4-way
13065        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
13066        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
13067        // extended here onto the cross-consumer-axis distinctness of the
13068        // two payload-less-arm consts.
13069        assert_ne!(
13070            WitTarget::CAPABILITY_GRAPH_LABEL,
13071            WitTarget::CAPABILITY_LABEL,
13072            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
13073             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
13074             diagnostic) must remain distinct — a collapse would silently \
13075             merge two consumer axes onto one spelling"
13076        );
13077    }
13078
13079    #[test]
13080    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
13081        // 4-way distinctness pin extending the sibling
13082        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
13083        // (which covers only the HTTP / PubSub / Store payload arms)
13084        // onto the fourth scalar the shared
13085        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
13086        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
13087        // (`"none"`), the payload-less Capability-arm rejection scalar.
13088        //
13089        // All four [`WitTarget::HTTP_FIELD_NAME`] /
13090        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13091        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
13092        // dispatch surface [`WitContract::target`] writes onto the
13093        // `ContratoWrongTarget::expected` field — the same `&'static
13094        // str` axis authors read as "this WIT world's shape admits
13095        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
13096        // downstream consumers rely on: an `expected: "endpoint"`
13097        // diagnostic on a Capability-shaped edge tells the author to
13098        // add a `:endpoint "…"` slot to a WIT world that admits none,
13099        // silently misrouting the fix. Until this pin landed the three
13100        // payload-arm consts were distinctness-guarded by the sibling
13101        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
13102        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
13103        // author-facing vocabulary shift from `"none"` to `"endpoint"`
13104        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
13105        // into per-shape peers) would have silently landed one
13106        // Capability-arm rejection on a payload-arm's `expected:` byte-
13107        // string and desynchronized the diagnostic from the author's
13108        // typed shape.
13109        //
13110        // Same 4-way pairwise-distinctness pin discipline as the peer
13111        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
13112        // (cc8f749) applies on the sibling M3 closed-set typed-enum
13113        // scalar-value dispatch axis; extends the pin trajectory the
13114        // sibling `wit_target_field_names_are_pairwise_distinct`
13115        // 3-way pin opened to cover the last unguarded corner on the
13116        // `ContratoWrongTarget::expected` scalar-value axis.
13117        //
13118        // Fail-before-pass-after locally verified by mutating
13119        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
13120        // — this pin fires as expected; restoring passes.
13121        let all = [
13122            WitTarget::HTTP_FIELD_NAME,
13123            WitTarget::PUBSUB_FIELD_NAME,
13124            WitTarget::STORE_FIELD_NAME,
13125            WitTarget::CAPABILITY_EXPECTED,
13126        ];
13127        for (i, a) in all.iter().enumerate() {
13128            for (j, b) in all.iter().enumerate() {
13129                if i != j {
13130                    assert_ne!(
13131                        a, b,
13132                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
13133                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
13134                         pairwise distinct — got duplicate {a:?} at indices \
13135                         {i} and {j}; all four scalars thread through the \
13136                         shared `AplicacaoError::ContratoWrongTarget::expected` \
13137                         &'static str axis, so a collapse silently misdirects \
13138                         the diagnostic on which typed shape the WIT world admits",
13139                    );
13140                }
13141            }
13142        }
13143    }
13144
13145    #[test]
13146    fn wit_target_is_variant_predicates_partition_the_arm_set() {
13147        // Fail-before-pass-after pin on the
13148        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
13149        // each of the four variants exactly one of the generated
13150        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
13151        // predicates returns `true` and the other three return
13152        // `false`. Prior to this derive the only production
13153        // arm-discriminator on [`WitTarget`] — the sync-cycle
13154        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
13155        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
13156        // the variant that expressed no compile-time link back to
13157        // the closed-set typed dispatch a future fifth
13158        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
13159        // split of [`WitTarget::PubSub`] into shape-specific peers,
13160        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
13161        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
13162        // to thread through in lockstep or the DFS exclusion would
13163        // silently disagree with the peer diagnostic templates on
13164        // which arms carry sync-versus-async semantics. Peer of the
13165        // sibling [`crate::CaixaKind`] (f5bba80),
13166        // [`PlacementStrategy`] (766ec63),
13167        // [`crate::supervisor::RestartStrategy`],
13168        // [`crate::supervisor::RestartPolicy`], and
13169        // [`crate::upgrade::UpgradeInstruction`] (915a934)
13170        // `IsVariant` derives on the sibling closed-set typed-enum
13171        // discriminator axes — extends the same one-typed-dispatch-
13172        // per-variant discipline onto the last unlifted closed-set
13173        // typed-enum discriminator on the caixa surface (the M3
13174        // mesh-slot per-`:contratos` target-arm axis), closing the
13175        // arm-discriminator convergence trajectory across every
13176        // closed-set typed enum in caixa-core.
13177        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
13178            (
13179                WitTarget::Http { endpoint: "/x" },
13180                [true, false, false, false],
13181            ),
13182            (
13183                WitTarget::PubSub {
13184                    subject: "events.x",
13185                },
13186                [false, true, false, false],
13187            ),
13188            (
13189                WitTarget::Store { slot: "kv/x" },
13190                [false, false, true, false],
13191            ),
13192            (WitTarget::Capability, [false, false, false, true]),
13193        ];
13194        for (variant, expected) in rows {
13195            let observed = [
13196                variant.is_http(),
13197                variant.is_pubsub(),
13198                variant.is_store(),
13199                variant.is_capability(),
13200            ];
13201            assert_eq!(
13202                observed, expected,
13203                "WitTarget::{variant:?} is_* predicates must partition \
13204                 the arm set (http, pubsub, store, capability); got {observed:?}"
13205            );
13206        }
13207    }
13208
13209    #[test]
13210    fn wit_target_is_variant_predicates_are_const_fn() {
13211        // The [`gen_platform::IsVariant`] derive emits `const fn`
13212        // predicates on the peer [`crate::CaixaKind`] +
13213        // [`crate::upgrade::UpgradeInstruction`] +
13214        // [`crate::supervisor::RestartStrategy`] +
13215        // [`crate::supervisor::RestartPolicy`] +
13216        // [`PlacementStrategy`] closed-set typed enums — pin the
13217        // same posture on [`WitTarget`] so a future accidental
13218        // downgrade to non-`const` (an added runtime helper reachable
13219        // only from a non-`const` context, a manual hand-rolled
13220        // `impl` that shadows the derive-generated method) trips at
13221        // caixa-core build time rather than surfacing as a downstream
13222        // `const`-context regression far from the derive declaration.
13223        //
13224        // Unlike the peer unit-variant enums (`CaixaKind` /
13225        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
13226        // whose `const` constructors need no arguments, the three
13227        // payload-carrying [`WitTarget`] arms are const-constructed
13228        // through `&'static str` payloads — the same `'static`
13229        // lifetime the closed-set typed enum's four-arm partition
13230        // pin above already threads through.
13231        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
13232        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
13233        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
13234        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
13235        const IS_HTTP: bool = HTTP.is_http();
13236        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
13237        const IS_STORE: bool = STORE.is_store();
13238        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
13239        assert!(IS_HTTP);
13240        assert!(IS_PUBSUB);
13241        assert!(IS_STORE);
13242        assert!(IS_CAPABILITY);
13243    }
13244
13245    #[test]
13246    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
13247        // Consumer-side pin on the sole production converge site:
13248        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
13249        // edges from the synchronous-subgraph DFS via the lifted
13250        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
13251        // predicate (rebound from the prior raw
13252        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
13253        // variant). Byte-equivalent today (`is_pubsub` is the
13254        // derive-generated `matches!(self, Self::PubSub { .. })` by
13255        // construction, the `#[is_variant(name = "pubsub")]` override
13256        // aliasing the auto-derived `is_pub_sub` back to the sibling
13257        // [`WitContract::is_pubsub`] name); pin the behavior so a
13258        // future accidental drift (a rebind onto a peer arm
13259        // predicate, a manual hand-rolled `impl` that shadows the
13260        // derive-generated method with different semantics, a peer
13261        // arm rename that shifts which variant carries sync-versus-
13262        // async semantics) trips at caixa-core test time rather than
13263        // at some downstream operator's runtime dispatch far from the
13264        // rebind commit.
13265        //
13266        // The fixture constructs a two-Servico Aplicacao with one
13267        // pub-sub edge that would close a sync-cycle if the DFS did
13268        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
13269        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
13270        // edge, which is not a cycle. A regression in the converge
13271        // (a rebind that reads the pub-sub arm as sync) would report
13272        // `AplicacaoError::ContratoCycle`.
13273        let s = AplicacaoSpec {
13274            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
13275            contratos: vec![
13276                // Pub-sub edge: DFS must skip via is_pubsub().
13277                WitContract {
13278                    de: "a".into(),
13279                    para: "b".into(),
13280                    wit: "nats:pub-sub".into(),
13281                    endpoint: None,
13282                    subject: Some("events.x".into()),
13283                    slot: None,
13284                },
13285                // HTTP edge: DFS must include.
13286                WitContract {
13287                    de: "b".into(),
13288                    para: "a".into(),
13289                    wit: "wasi:http/proxy".into(),
13290                    endpoint: Some("/x".into()),
13291                    subject: None,
13292                    slot: None,
13293                },
13294            ],
13295            politicas: MeshPolicy::default(),
13296            placement: Placement {
13297                estrategia: PlacementStrategy::Replicated,
13298                clusters: vec!["rio".into()],
13299                affinity: None,
13300                shard_key: None,
13301            },
13302            entrada: None,
13303        };
13304        s.validate()
13305            .expect("pub-sub edge must be excluded from sync-cycle DFS");
13306    }
13307
13308    #[test]
13309    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
13310        // Consumer-side pin: the same three peer consts thread through
13311        // both the [`WitTarget::label`] template (leading-`:` keyword
13312        // prefix in the duplicate-`:contratos` diagnostic) and the
13313        // [`WitContract::target`] gate's [`AplicacaoError::
13314        // ContratoMissingTarget`] `expected:` scalar (the field the
13315        // author needs to add). Pin both routes at once so a future
13316        // refactor can't accidentally split them onto separate string
13317        // literals — the "one place, everywhere reaches for it"
13318        // invariant the peer const set carries.
13319        let http_label = WitTarget::Http { endpoint: "/x" }.label();
13320        assert!(
13321            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
13322            "label must lead with :{} keyword (got {http_label:?})",
13323            WitTarget::HTTP_FIELD_NAME,
13324        );
13325
13326        let mut s = three_member_spec();
13327        s.contratos.push(WitContract {
13328            de: "cart".into(),
13329            para: "catalog".into(),
13330            wit: "kafka:topic".into(),
13331            endpoint: None,
13332            subject: None,
13333            slot: None,
13334        });
13335        match s.validate().unwrap_err() {
13336            AplicacaoError::ContratoMissingTarget { expected, .. } => {
13337                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
13338            }
13339            other => panic!("expected ContratoMissingTarget, got {other:?}"),
13340        }
13341    }
13342
13343    #[test]
13344    fn duplicate_pubsub_diagnostic_names_offending_subject() {
13345        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
13346        // on the pub-sub target axis: the duplicate-edge diagnostic
13347        // must name the `:subject` payload verbatim (not just the
13348        // `(de, para, wit)` triple). Prior to lifting the label onto
13349        // [`WitTarget::label`] the diagnostic derived the label from
13350        // raw [`WitContract`] `Option<String>` probes — a future
13351        // `WitTarget` variant addition (M4 per-edge WIT registry)
13352        // would silently fall through to the `Capability` "no
13353        // payload" default without a compiler warning. Pinning the
13354        // pub-sub arm's format closes the second of three
13355        // payload-carrying `WitTarget` arms this diagnostic threads
13356        // through.
13357        let mut s = three_member_spec();
13358        let pubsub = WitContract {
13359            de: "payment".into(),
13360            para: "cart".into(),
13361            wit: "nats:pub-sub".into(),
13362            endpoint: None,
13363            subject: Some("events.checkout.paid".into()),
13364            slot: None,
13365        };
13366        s.contratos.push(pubsub.clone());
13367        s.contratos.push(pubsub);
13368        let err = s.validate().unwrap_err();
13369        let msg = format!("{err}");
13370        assert!(
13371            msg.contains(":subject \"events.checkout.paid\""),
13372            "duplicate-pubsub diagnostic must name the offending \
13373             :subject payload (got: {msg:?})"
13374        );
13375    }
13376
13377    #[test]
13378    fn duplicate_store_diagnostic_names_offending_slot() {
13379        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
13380        // key-value target axis: the diagnostic must name the `:slot`
13381        // payload verbatim. Third of three payload-carrying
13382        // `WitTarget` arms this diagnostic threads through, closing
13383        // the per-arm label pin trilogy (`Http` — 6841,
13384        // `PubSub` + `Store` — this test + peer above).
13385        let mut s = three_member_spec();
13386        let store = WitContract {
13387            de: "cart".into(),
13388            para: "payment".into(),
13389            wit: "wasi:keyvalue/store".into(),
13390            endpoint: None,
13391            subject: None,
13392            slot: Some("checkout/$orderId".into()),
13393        };
13394        s.contratos
13395            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13396        s.contratos.push(store.clone());
13397        s.contratos.push(store);
13398        let err = s.validate().unwrap_err();
13399        let msg = format!("{err}");
13400        assert!(
13401            msg.contains(":slot \"checkout/$orderId\""),
13402            "duplicate-store diagnostic must name the offending :slot \
13403             payload (got: {msg:?})"
13404        );
13405    }
13406
13407    #[test]
13408    fn rejects_entrada_path_without_leading_slash() {
13409        let mut s = three_member_spec();
13410        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
13411        let err = s.validate().unwrap_err();
13412        assert!(
13413            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
13414            "got {err:?}"
13415        );
13416    }
13417
13418    #[test]
13419    fn rejects_empty_entrada_path() {
13420        let mut s = three_member_spec();
13421        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
13422        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13423    }
13424
13425    #[test]
13426    fn rejects_duplicate_entrada_paths() {
13427        let mut s = three_member_spec();
13428        s.entrada.as_mut().unwrap().paths = vec![
13429            "/api/cart".into(),
13430            "/api/products".into(),
13431            "/api/cart".into(),
13432        ];
13433        let err = s.validate().unwrap_err();
13434        assert!(
13435            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
13436            "got {err:?}"
13437        );
13438    }
13439
13440    #[test]
13441    fn rejects_zero_entrada_port() {
13442        let mut s = three_member_spec();
13443        s.entrada.as_mut().unwrap().port = 0;
13444        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
13445    }
13446
13447    // ── :entrada :paths value-shape gate ─────────────────────────────
13448    //
13449    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
13450    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
13451    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
13452    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
13453    // time now becomes a caixa-build-time `EntradaPathInvalid` with
13454    // the offending `:paths` entry named verbatim.
13455
13456    #[test]
13457    fn rejects_entrada_path_with_query() {
13458        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
13459        // silently passed validate and the Gateway API webhook
13460        // rejected it at apply time with no source citation.
13461        let mut s = three_member_spec();
13462        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
13463        let err = s.validate().unwrap_err();
13464        assert!(
13465            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13466                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
13467            "got {err:?}"
13468        );
13469    }
13470
13471    #[test]
13472    fn rejects_entrada_path_with_fragment() {
13473        let mut s = three_member_spec();
13474        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
13475        let err = s.validate().unwrap_err();
13476        assert!(
13477            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13478                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
13479            "got {err:?}"
13480        );
13481    }
13482
13483    #[test]
13484    fn rejects_entrada_path_with_space() {
13485        let mut s = three_member_spec();
13486        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
13487        let err = s.validate().unwrap_err();
13488        assert!(
13489            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13490                if path == "/api/my cart" && reason.contains("whitespace")),
13491            "got {err:?}"
13492        );
13493    }
13494
13495    #[test]
13496    fn rejects_entrada_path_with_tab() {
13497        let mut s = three_member_spec();
13498        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
13499        let err = s.validate().unwrap_err();
13500        assert!(
13501            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13502                if path == "/api/\tcart" && reason.contains("whitespace")),
13503            "got {err:?}"
13504        );
13505    }
13506
13507    #[test]
13508    fn rejects_entrada_path_with_control_char() {
13509        // 0x01 (SOH) — a non-whitespace control char surfaces the
13510        // distinct "control character" reason arm, separate from
13511        // the whitespace arm. Pinned so a future refactor that
13512        // collapses the two arms can't accidentally drop the more
13513        // self-locating diagnostic.
13514        let mut s = three_member_spec();
13515        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
13516        let err = s.validate().unwrap_err();
13517        assert!(
13518            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13519                if path == "/api/\x01cart" && reason.contains("control character")),
13520            "got {err:?}"
13521        );
13522    }
13523
13524    #[test]
13525    fn rejects_entrada_path_with_non_ascii() {
13526        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
13527        // unreserved-set rule rejects. The Gateway API webhook
13528        // rejects literal non-ASCII bytes; percent-encoding is the
13529        // only way to author non-ASCII in a path.
13530        let mut s = three_member_spec();
13531        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
13532        let err = s.validate().unwrap_err();
13533        assert!(
13534            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13535                if path == "/api/café" && reason.contains("non-ASCII")),
13536            "got {err:?}"
13537        );
13538    }
13539
13540    #[test]
13541    fn rejects_entrada_path_with_consecutive_slashes() {
13542        let mut s = three_member_spec();
13543        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
13544        let err = s.validate().unwrap_err();
13545        assert!(
13546            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13547                if path == "/api//cart" && reason.contains("consecutive `/`")),
13548            "got {err:?}"
13549        );
13550    }
13551
13552    #[test]
13553    fn rejects_entrada_path_with_dot_segment() {
13554        let mut s = three_member_spec();
13555        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
13556        let err = s.validate().unwrap_err();
13557        assert!(
13558            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13559                if path == "/api/./cart" && reason.contains("`.` segment")),
13560            "got {err:?}"
13561        );
13562    }
13563
13564    #[test]
13565    fn rejects_entrada_path_with_trailing_dot_segment() {
13566        // The bare `/.` and the trailing `/foo/.` are both rejected
13567        // by the Gateway API webhook; pinned separately so a future
13568        // narrowing that catches only the inner form surfaces here.
13569        let mut s = three_member_spec();
13570        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
13571        let err = s.validate().unwrap_err();
13572        assert!(
13573            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13574                if path == "/api/." && reason.contains("`.` segment")),
13575            "got {err:?}"
13576        );
13577    }
13578
13579    #[test]
13580    fn rejects_entrada_path_with_parent_segment() {
13581        let mut s = three_member_spec();
13582        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
13583        let err = s.validate().unwrap_err();
13584        assert!(
13585            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13586                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
13587            "got {err:?}"
13588        );
13589    }
13590
13591    #[test]
13592    fn rejects_entrada_path_with_trailing_parent_segment() {
13593        // Trailing `/..` — symmetric arm of the parent-segment rule,
13594        // pinned separately so a future relaxation that only checks
13595        // the inner form (`/../`) surfaces here.
13596        let mut s = three_member_spec();
13597        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
13598        let err = s.validate().unwrap_err();
13599        assert!(
13600            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13601                if path == "/api/.." && reason.contains("`..` parent-segment")),
13602            "got {err:?}"
13603        );
13604    }
13605
13606    #[test]
13607    fn rejects_entrada_path_too_long() {
13608        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
13609        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
13610        // ASCII-alphanumeric body so only the length rule fires.
13611        let mut s = three_member_spec();
13612        let big = format!("/api/{}", "a".repeat(1020));
13613        assert_eq!(big.len(), 1025);
13614        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
13615        let err = s.validate().unwrap_err();
13616        assert!(
13617            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13618                if path == &big && reason.contains("max length of 1024")),
13619            "got {err:?}"
13620        );
13621    }
13622
13623    #[test]
13624    fn entrada_path_max_length_validates() {
13625        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
13626        // maxLength cap. Boundary pin: drift in the cap surfaces here
13627        // and at `rejects_entrada_path_too_long` simultaneously.
13628        let mut s = three_member_spec();
13629        let big = format!("/api/{}", "a".repeat(1019));
13630        assert_eq!(big.len(), 1024);
13631        s.entrada.as_mut().unwrap().paths = vec![big];
13632        s.validate().unwrap();
13633    }
13634
13635    #[test]
13636    fn entrada_accepts_canonical_paths() {
13637        // Positive-control sweep — every form the Gateway API
13638        // apiserver accepts must round-trip through validate. Covers
13639        // the root catch-all, plain paths, dot-prefixed segments
13640        // (hidden-file-style, distinct from `.` and `..` segments
13641        // which are rejected), digit-bearing segments, the canonical
13642        // route-template `:param` form (`:` is RFC 3986 reserved-set
13643        // valid in paths), trailing-slash form, percent-encoded
13644        // segments, and an interior `..` *substring* (`/foo..bar` is
13645        // not the `..` segment and is allowed).
13646        for path in [
13647            "/",
13648            "/api/cart",
13649            "/healthz",
13650            "/api/.config",
13651            "/v1/products",
13652            "/products/:id",
13653            "/api/cart/",
13654            "/api/caf%C3%A9",
13655            "/foo..bar",
13656            "/...",
13657        ] {
13658            let mut s = three_member_spec();
13659            s.entrada.as_mut().unwrap().paths = vec![path.into()];
13660            s.validate()
13661                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
13662        }
13663    }
13664
13665    #[test]
13666    fn entrada_path_empty_takes_precedence_over_invalid() {
13667        // Ordering pin: `EntradaPathEmpty` is the more self-locating
13668        // diagnostic on `""` and must lead — `validate_entrada_path`
13669        // is only reached after the empty-check fires at the call
13670        // site. (The predicate itself defends against direct
13671        // invocation by returning the same error on `""`.)
13672        let mut s = three_member_spec();
13673        s.entrada.as_mut().unwrap().paths = vec!["".into()];
13674        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13675    }
13676
13677    #[test]
13678    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
13679        // Ordering pin: a path without a leading `/` surfaces the
13680        // narrower `EntradaPathNotAbsolute` diagnostic first; the
13681        // value-shape gate is only consulted on paths that already
13682        // satisfy the absolute-prefix invariant.
13683        let mut s = three_member_spec();
13684        // `bad path` would fire the whitespace rule under the
13685        // value-shape gate, but missing-leading-`/` is the more
13686        // self-locating diagnostic.
13687        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
13688        let err = s.validate().unwrap_err();
13689        assert!(
13690            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
13691            "got {err:?}"
13692        );
13693    }
13694
13695    #[test]
13696    fn entrada_path_invalid_fires_before_duplicate_check() {
13697        // Ordering pin: a malformed path on the *first* entry of a
13698        // would-be duplicate pair fires the value-shape gate before
13699        // the duplicate gate, mirroring the
13700        // `placement_cluster_invalid_fires_before_duplicate_check`
13701        // (6cbb900) pattern on the peer axis.
13702        let mut s = three_member_spec();
13703        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
13704        let err = s.validate().unwrap_err();
13705        assert!(
13706            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
13707            "got {err:?}"
13708        );
13709    }
13710
13711    #[test]
13712    fn entrada_path_diagnostic_carries_offending_path() {
13713        // Diagnostic-shape pin — the offending path + a non-empty
13714        // reason flow through verbatim so the author can grep their
13715        // caixa.lisp for `:paths` and fix it in one edit. Same shape
13716        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
13717        let mut s = three_member_spec();
13718        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
13719        let err = s.validate().unwrap_err();
13720        match err {
13721            AplicacaoError::EntradaPathInvalid { path, reason } => {
13722                assert_eq!(path, "/api?q=1");
13723                assert!(!reason.is_empty(), "reason field must be non-empty");
13724            }
13725            other => panic!("expected EntradaPathInvalid, got {other:?}"),
13726        }
13727    }
13728
13729    #[test]
13730    fn rejects_entrada_path_with_curly_brace_template_form() {
13731        // Per-axis pin on the shared `is_gateway_api_http_path`
13732        // reserved-byte arm: the canonical "I wrote an OpenAPI
13733        // path-template `{id}` instead of the Gateway API `:id` form"
13734        // footgun the K8s apiserver would otherwise catch at admission
13735        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
13736        // landing site, far from the caixa.lisp. Surfaces as
13737        // `EntradaPathInvalid` carrying the offending path verbatim
13738        // plus the canonical `%7B`/`%7D` percent-encoding remediation
13739        // — the substrate-side `gateway_api_http_path_rejects_every_
13740        // reserved_printable_ascii_byte` predicate-level sweep pins the
13741        // full eleven-byte set; this per-axis pin confirms the
13742        // diagnostic flows through to the `EntradaPathInvalid` variant.
13743        let mut s = three_member_spec();
13744        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
13745        let err = s.validate().unwrap_err();
13746        assert!(
13747            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13748                if path == "/api/cart/{id}"
13749                    && reason.contains("reserved character")
13750                    && reason.contains("'{'")
13751                    && reason.contains("%7B")),
13752            "got {err:?}"
13753        );
13754    }
13755
13756    #[test]
13757    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
13758        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
13759        // template_form` on the sibling `:contratos :endpoint` axis.
13760        // Same shared `is_gateway_api_http_path` reserved-byte arm
13761        // fires through `ContratoEndpointInvalid`, with the offending
13762        // endpoint + `:de` + `:para` + reason flowing through verbatim.
13763        // Pins that the lifted predicate's tightening lands on both
13764        // caller axes simultaneously — one source of truth for the
13765        // Gateway API HTTPPathMatch.value accepted set.
13766        let err = contrato_endpoint_err("/api/cart/{id}");
13767        assert!(
13768            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13769                if endpoint == "/api/cart/{id}"
13770                    && reason.contains("reserved character")
13771                    && reason.contains("'{'")
13772                    && reason.contains("%7B")),
13773            "got {err:?}"
13774        );
13775    }
13776
13777    // ── :entrada :host value-shape gate ──────────────────────────────
13778    //
13779    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
13780    // the sibling `:host` axis. Every authoring footgun the K8s
13781    // Gateway API v1 apiserver would catch at admission time becomes
13782    // a caixa-build-time `EntradaHostInvalid` with the offending
13783    // `:host` named verbatim. Same diagnostic shape as
13784    // `MembroVersaoInvalid` (9888b13).
13785
13786    #[test]
13787    fn rejects_entrada_host_with_scheme() {
13788        // Fail-before-pass-after pin — pre-gate codebases silently
13789        // accepted `https://…` and the apiserver rejected it at apply
13790        // time with no source citation.
13791        let mut s = three_member_spec();
13792        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
13793        let err = s.validate().unwrap_err();
13794        assert!(
13795            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13796                if host == "https://checkout.quero.cloud"),
13797            "got {err:?}"
13798        );
13799    }
13800
13801    #[test]
13802    fn rejects_entrada_host_with_port() {
13803        // The `:8080` port suffix is the canonical "I forgot the port
13804        // belongs in `:entrada :port`" footgun. The top-level `:` arm
13805        // (introduced after the per-label loop-only impl silently
13806        // surfaced a deep "label \"cloud:8080\" contains invalid
13807        // character ':'" leak) names the canonical fix verbatim — the
13808        // `:entrada :port` slot.
13809        let mut s = three_member_spec();
13810        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
13811        let err = s.validate().unwrap_err();
13812        assert!(
13813            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13814                if host == "checkout.quero.cloud:8080"
13815                && reason.contains(":entrada :port")),
13816            "got {err:?}"
13817        );
13818    }
13819
13820    #[test]
13821    fn rejects_entrada_host_with_trailing_colon() {
13822        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
13823        // edit) — the per-label loop would land it as a deep
13824        // "label \"com:\" must start and end with an alphanumeric"
13825        // / "contains invalid character ':'" leak. The top-level
13826        // `:` arm pre-empts with the canonical `:port` slot
13827        // diagnostic.
13828        let mut s = three_member_spec();
13829        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
13830        let err = s.validate().unwrap_err();
13831        assert!(
13832            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13833                if host == "checkout.quero.cloud:"
13834                && reason.contains(":entrada :port")),
13835            "got {err:?}"
13836        );
13837    }
13838
13839    #[test]
13840    fn rejects_entrada_host_unbracketed_ipv6_literal() {
13841        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
13842        // literals across the board (peer with `rejects_entrada_host_
13843        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
13844        // Before this top-level `:` arm landed the per-label loop
13845        // surfaced a single-label byte-class diagnostic that named the
13846        // `:` byte but not the IP-literal prohibition. The top-level
13847        // `:` arm names both the `:port` slot and the IP-literal
13848        // prohibition verbatim, so an author whose `:host "2001:..."`
13849        // value lands here gets a self-locating fix either way.
13850        let mut s = three_member_spec();
13851        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
13852        let err = s.validate().unwrap_err();
13853        assert!(
13854            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13855                if host == "2001:db8::1"
13856                && reason.contains("IPv6")),
13857            "got {err:?}"
13858        );
13859    }
13860
13861    #[test]
13862    fn rejects_entrada_host_wildcard_with_port() {
13863        // Wildcard host with port suffix — the `*.` strip and the
13864        // per-label loop on `["foo", "quero", "cloud:8080"]` would
13865        // surface the deep byte-class leak. The top-level `:` arm sits
13866        // upstream of the `*.` strip, so it names the canonical `:port`
13867        // fix verbatim regardless of whether the host is wildcard-led.
13868        let mut s = three_member_spec();
13869        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
13870        let err = s.validate().unwrap_err();
13871        assert!(
13872            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13873                if host == "*.quero.cloud:8080"
13874                && reason.contains(":entrada :port")),
13875            "got {err:?}"
13876        );
13877    }
13878
13879    #[test]
13880    fn rejects_entrada_host_with_path() {
13881        let mut s = three_member_spec();
13882        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
13883        let err = s.validate().unwrap_err();
13884        assert!(
13885            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13886                if host == "checkout.quero.cloud/api"),
13887            "got {err:?}"
13888        );
13889    }
13890
13891    #[test]
13892    fn rejects_entrada_host_with_uppercase() {
13893        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
13894        // rejected, not silently lower-cased.
13895        let mut s = three_member_spec();
13896        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
13897        let err = s.validate().unwrap_err();
13898        assert!(
13899            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13900                if reason.contains("uppercase")),
13901            "got {err:?}"
13902        );
13903    }
13904
13905    #[test]
13906    fn rejects_entrada_host_with_underscore() {
13907        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
13908        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
13909        let mut s = three_member_spec();
13910        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
13911        let err = s.validate().unwrap_err();
13912        assert!(
13913            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13914                if reason.contains('_')),
13915            "got {err:?}"
13916        );
13917    }
13918
13919    #[test]
13920    fn rejects_entrada_host_ipv4_literal() {
13921        // Gateway API v1 explicitly forbids IP literals as Hostnames.
13922        let mut s = three_member_spec();
13923        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
13924        let err = s.validate().unwrap_err();
13925        assert!(
13926            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13927                if reason.contains("IPv4")),
13928            "got {err:?}"
13929        );
13930    }
13931
13932    #[test]
13933    fn rejects_entrada_host_with_trailing_dot() {
13934        // The Gateway API regex anchors at end-of-string with no
13935        // trailing `.` allowance — the FQDN root-dot form is rejected.
13936        let mut s = three_member_spec();
13937        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
13938        let err = s.validate().unwrap_err();
13939        assert!(
13940            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13941                if host == "checkout.quero.cloud."),
13942            "got {err:?}"
13943        );
13944    }
13945
13946    #[test]
13947    fn rejects_entrada_host_with_leading_dot() {
13948        let mut s = three_member_spec();
13949        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
13950        let err = s.validate().unwrap_err();
13951        assert!(
13952            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13953                if reason.contains("empty label")),
13954            "got {err:?}"
13955        );
13956    }
13957
13958    #[test]
13959    fn rejects_entrada_host_with_consecutive_dots() {
13960        let mut s = three_member_spec();
13961        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
13962        let err = s.validate().unwrap_err();
13963        assert!(
13964            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13965                if reason.contains("empty label")),
13966            "got {err:?}"
13967        );
13968    }
13969
13970    #[test]
13971    fn rejects_entrada_host_with_leading_hyphen_label() {
13972        let mut s = three_member_spec();
13973        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
13974        let err = s.validate().unwrap_err();
13975        assert!(
13976            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13977                if reason.contains("alphanumeric")),
13978            "got {err:?}"
13979        );
13980    }
13981
13982    #[test]
13983    fn rejects_entrada_host_with_trailing_hyphen_label() {
13984        let mut s = three_member_spec();
13985        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
13986        let err = s.validate().unwrap_err();
13987        assert!(
13988            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13989                if reason.contains("alphanumeric")),
13990            "got {err:?}"
13991        );
13992    }
13993
13994    #[test]
13995    fn rejects_entrada_host_with_inner_wildcard() {
13996        // Gateway API allows `*` only as the first label (`*.foo`);
13997        // any inner or trailing `*` is rejected.
13998        let mut s = three_member_spec();
13999        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14000        let err = s.validate().unwrap_err();
14001        assert!(
14002            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14003                if reason.contains("wildcard")),
14004            "got {err:?}"
14005        );
14006    }
14007
14008    #[test]
14009    fn rejects_entrada_host_bare_wildcard() {
14010        // `*.` with no domain is meaningless; Gateway API rejects it.
14011        let mut s = three_member_spec();
14012        s.entrada.as_mut().unwrap().host = "*.".into();
14013        let err = s.validate().unwrap_err();
14014        assert!(
14015            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14016                if reason.contains("wildcard")),
14017            "got {err:?}"
14018        );
14019    }
14020
14021    #[test]
14022    fn rejects_entrada_host_with_whitespace() {
14023        let mut s = three_member_spec();
14024        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14025        let err = s.validate().unwrap_err();
14026        assert!(
14027            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14028                if reason.contains("whitespace")),
14029            "got {err:?}"
14030        );
14031    }
14032
14033    #[test]
14034    fn rejects_entrada_host_space_names_offending_byte() {
14035        // Embedded space in the `:entrada :host` axis surfaces the
14036        // byte-naming diagnostic through the lifted
14037        // `find_ascii_whitespace_byte` predicate. Peer with the
14038        // sibling `parse_rejects_leading_whitespace` pins on
14039        // `supervisor::duration_codec` (a7ae622) — same "the
14040        // diagnostic carries the offending byte's `0x{b:02x}` shape"
14041        // discipline extended from the shared duration codec to the
14042        // Gateway API v1 Hostname axis.
14043        let mut s = three_member_spec();
14044        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14045        let err = s.validate().unwrap_err();
14046        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14047            panic!("expected EntradaHostInvalid, got {err:?}");
14048        };
14049        assert!(
14050            reason.contains("ASCII whitespace byte"),
14051            "expected byte-naming diagnostic, got {reason:?}"
14052        );
14053        assert!(
14054            reason.contains("0x20"),
14055            "expected offending space byte 0x20, got {reason:?}"
14056        );
14057    }
14058
14059    #[test]
14060    fn rejects_entrada_host_tab_names_offending_byte() {
14061        // Embedded tab byte in the `:entrada :host` axis — the
14062        // canonical paste-from-YAML-block-scalar / paste-from-
14063        // indented-doc footgun. Pins that the lifted predicate covers
14064        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
14065        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
14066        // not just the leading-space case the pre-lift `.bytes().any`
14067        // arm's opaque "must not contain whitespace" reason already
14068        // covered. Peer with `parse_rejects_tab_byte` on
14069        // `supervisor::duration_codec` (a7ae622).
14070        let mut s = three_member_spec();
14071        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
14072        let err = s.validate().unwrap_err();
14073        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14074            panic!("expected EntradaHostInvalid, got {err:?}");
14075        };
14076        assert!(
14077            reason.contains("ASCII whitespace byte"),
14078            "expected byte-naming diagnostic, got {reason:?}"
14079        );
14080        assert!(
14081            reason.contains("0x09"),
14082            "expected offending tab byte 0x09, got {reason:?}"
14083        );
14084    }
14085
14086    #[test]
14087    fn rejects_entrada_host_lf_names_offending_byte() {
14088        // Embedded LF byte in the `:entrada :host` axis — the
14089        // canonical paste-from-shell-heredoc / paste-from-multiline-
14090        // doc footgun the caixa-mesh YAML emitter would silently
14091        // reinterpret at the Gateway API v1 HTTPRoute admission
14092        // layer (an embedded LF byte in a YAML plain scalar either
14093        // truncates the value at the emitter or crashes the parser
14094        // on the k8s-apiserver side). Pins the third representative
14095        // of the full ASCII-whitespace set through the shared
14096        // predicate.
14097        let mut s = three_member_spec();
14098        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
14099        let err = s.validate().unwrap_err();
14100        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14101            panic!("expected EntradaHostInvalid, got {err:?}");
14102        };
14103        assert!(
14104            reason.contains("ASCII whitespace byte"),
14105            "expected byte-naming diagnostic, got {reason:?}"
14106        );
14107        assert!(
14108            reason.contains("0x0a"),
14109            "expected offending LF byte 0x0a, got {reason:?}"
14110        );
14111    }
14112
14113    #[test]
14114    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
14115        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
14116        // axis — the canonical paste-from-typography /
14117        // paste-from-word-processor footgun. Before the non-ASCII
14118        // Unicode `White_Space` scan lifted through the shared
14119        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
14120        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
14121        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
14122        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
14123        // with the far-from-source `label "…" must start and end
14124        // with an alphanumeric` diagnostic — burying the
14125        // paste-from-typography origin under a label-shape leak.
14126        // Peer with the sibling non-ASCII-whitespace pins at
14127        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
14128        // — 1b75b38), `limits::parse_duration`,
14129        // `limits::parse_millicores`, and the shared duration codec
14130        // — same "the diagnostic carries the offending Unicode
14131        // codepoint's `U+XXXX` shape" discipline extended from every
14132        // typed-magnitude codec to the Gateway API v1 Hostname axis.
14133        let mut s = three_member_spec();
14134        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
14135        let err = s.validate().unwrap_err();
14136        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14137            panic!("expected EntradaHostInvalid, got {err:?}");
14138        };
14139        assert!(
14140            reason.contains("non-ASCII Unicode whitespace character"),
14141            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14142        );
14143        assert!(
14144            reason.contains("U+00A0"),
14145            "expected offending NBSP codepoint U+00A0, got {reason:?}"
14146        );
14147    }
14148
14149    #[test]
14150    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
14151        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
14152        // `:entrada :host` axis — the canonical paste-from-web-doc /
14153        // paste-from-published-HTML footgun. `char::is_whitespace`
14154        // returns true for `U+2028` per the Unicode `White_Space`
14155        // property, so `str::trim` at any downstream site would
14156        // silently strip it — same drift class as NBSP but on a
14157        // different codepoint region. Pins the second representative
14158        // (non-Latin-1 `char::is_whitespace` member) through the
14159        // shared predicate. Peer with
14160        // `parse_byte_size_rejects_internal_line_separator` on
14161        // `limits::parse_byte_size` (1b75b38).
14162        let mut s = three_member_spec();
14163        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
14164        let err = s.validate().unwrap_err();
14165        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14166            panic!("expected EntradaHostInvalid, got {err:?}");
14167        };
14168        assert!(
14169            reason.contains("non-ASCII Unicode whitespace character"),
14170            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14171        );
14172        assert!(
14173            reason.contains("U+2028"),
14174            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
14175        );
14176    }
14177
14178    #[test]
14179    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
14180        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
14181        // labels in the `:entrada :host` axis — the canonical
14182        // paste-from-CJK-typography footgun (CJK IMEs default to
14183        // full-width whitespace when the space bar is pressed in
14184        // Japanese / Chinese input modes). Pins the third
14185        // representative of the non-ASCII Unicode `White_Space` set
14186        // through the shared predicate: the CJK block, distinct from
14187        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
14188        // SEPARATOR `U+2028` — covering the same axis breadth the
14189        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
14190        // (1b75b38) pins on `limits::parse_byte_size`.
14191        let mut s = three_member_spec();
14192        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
14193        let err = s.validate().unwrap_err();
14194        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14195            panic!("expected EntradaHostInvalid, got {err:?}");
14196        };
14197        assert!(
14198            reason.contains("non-ASCII Unicode whitespace character"),
14199            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14200        );
14201        assert!(
14202            reason.contains("U+3000"),
14203            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
14204        );
14205    }
14206
14207    #[test]
14208    fn rejects_entrada_host_too_long() {
14209        // Total length cap = 253; build a 254-byte host out of two
14210        // 63-byte labels + one 62-byte label + dots.
14211        let mut s = three_member_spec();
14212        let big = format!(
14213            "{}.{}.{}.{}",
14214            "a".repeat(63),
14215            "b".repeat(63),
14216            "c".repeat(63),
14217            "d".repeat(254 - 63 * 3 - 3)
14218        );
14219        assert_eq!(big.len(), 254);
14220        s.entrada.as_mut().unwrap().host = big;
14221        let err = s.validate().unwrap_err();
14222        assert!(
14223            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14224                if reason.contains("max length of 253")),
14225            "got {err:?}"
14226        );
14227    }
14228
14229    #[test]
14230    fn rejects_entrada_host_label_too_long() {
14231        let mut s = three_member_spec();
14232        // 64-byte label — one over the per-label cap.
14233        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
14234        let err = s.validate().unwrap_err();
14235        assert!(
14236            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14237                if reason.contains("label max length of 63")),
14238            "got {err:?}"
14239        );
14240    }
14241
14242    #[test]
14243    fn entrada_host_diagnostic_carries_offending_host() {
14244        // Diagnostic-shape pin — the offending host + a non-empty
14245        // reason flow through verbatim so the author can grep their
14246        // caixa.lisp for `:host "<host>"` and fix it in one edit.
14247        let mut s = three_member_spec();
14248        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14249        let err = s.validate().unwrap_err();
14250        match err {
14251            AplicacaoError::EntradaHostInvalid { host, reason } => {
14252                assert_eq!(host, "checkout.quero.cloud:8080");
14253                assert!(!reason.is_empty(), "reason field must be non-empty");
14254            }
14255            other => panic!("expected EntradaHostInvalid, got {other:?}"),
14256        }
14257    }
14258
14259    #[test]
14260    fn entrada_host_empty_takes_precedence_over_invalid() {
14261        // Ordering pin: `EmptyEntradaHost` is the more self-locating
14262        // diagnostic on `""` and must lead — `validate_entrada_host`
14263        // is only reached after the empty-check fires at the call
14264        // site. (The predicate itself defends against direct
14265        // invocation by returning the same error on `""`.)
14266        let mut s = three_member_spec();
14267        s.entrada.as_mut().unwrap().host = String::new();
14268        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
14269    }
14270
14271    #[test]
14272    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
14273        // Ordering pin: a missing :para member is the more
14274        // self-locating diagnostic and fires before the host gate.
14275        let mut s = three_member_spec();
14276        let e = s.entrada.as_mut().unwrap();
14277        e.para = "ghost".into();
14278        e.host = "BAD HOST".into();
14279        let err = s.validate().unwrap_err();
14280        assert!(
14281            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
14282            "got {err:?}"
14283        );
14284    }
14285
14286    #[test]
14287    fn entrada_host_invalid_fires_before_port_zero() {
14288        // Ordering pin: the host gate fires before the port gate so
14289        // a malformed host is named even when the port is also wrong.
14290        let mut s = three_member_spec();
14291        let e = s.entrada.as_mut().unwrap();
14292        e.host = "Checkout.quero.cloud".into();
14293        e.port = 0;
14294        let err = s.validate().unwrap_err();
14295        assert!(
14296            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14297                if host == "Checkout.quero.cloud"),
14298            "got {err:?}"
14299        );
14300    }
14301
14302    #[test]
14303    fn entrada_accepts_canonical_hosts() {
14304        // Positive-control sweep — every form the Gateway API
14305        // apiserver accepts must round-trip through validate. Covers
14306        // a plain DNS subdomain, a leading wildcard, a single-label
14307        // host (cluster-internal), a max-length-edge label, a
14308        // hyphen-bearing label, and a Punycode IDN label.
14309        for host in [
14310            "checkout.quero.cloud",
14311            "*.quero.cloud",
14312            "checkout",
14313            // 63-byte label — exactly the per-label cap.
14314            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
14315            "foo-bar.quero.cloud",
14316            // Punycode IDN — valid because the author pre-encoded.
14317            "xn--bcher-kva.example.com",
14318        ] {
14319            let mut s = three_member_spec();
14320            s.entrada.as_mut().unwrap().host = host.into();
14321            s.validate()
14322                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
14323        }
14324    }
14325
14326    #[test]
14327    fn entrada_host_max_length_validates() {
14328        // 253-byte host is the cap exactly — must validate. Build a
14329        // 253-byte host out of three 63-byte labels + one 61-byte
14330        // label + 3 dots = 252 bytes, then pad one byte to 253.
14331        let mut s = three_member_spec();
14332        let host = format!(
14333            "{}.{}.{}.{}",
14334            "a".repeat(63),
14335            "b".repeat(63),
14336            "c".repeat(63),
14337            "d".repeat(253 - 63 * 3 - 3)
14338        );
14339        assert_eq!(host.len(), 253);
14340        s.entrada.as_mut().unwrap().host = host;
14341        s.validate().unwrap();
14342    }
14343
14344    #[test]
14345    fn entrada_host_total_length_cap_threads_lifted_render_const() {
14346        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
14347        // total-length gate now reads the K8s Gateway API v1 Hostname
14348        // `maxLength: 253` cap from the lifted
14349        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
14350        // of truth — the same constant every future Gateway-API-Hostname
14351        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
14352        // materializer's per-host validator, the future per-`Certificate`
14353        // SAN emitter for cert-manager, the multi-`:entrada`
14354        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
14355        // from. Before the lift, the aplicacao-side reader consumed a
14356        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
14357        // 253-byte value as the peer render-side canonical bounds
14358        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
14359        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
14360        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
14361        // module boundary — a future 253-byte drift on either side would
14362        // silently split into two axes' worth of admission-schema mismatch
14363        // without a build-time signal. Pin the cap through a fresh 254-
14364        // byte host that hits the total-length arm, then read the reason
14365        // for the exact byte count the shared constant carries: any future
14366        // regression on the lift (a private alias reintroduced, a hard-
14367        // coded literal at the arm, a mismatch between the aplicacao-side
14368        // and render-side canonicals) surfaces as this pin's diagnostic
14369        // failing to match, not as a per-cluster admission rejection far
14370        // from the caixa.lisp source line.
14371        let mut s = three_member_spec();
14372        let over_cap = format!(
14373            "{}.{}.{}.{}",
14374            "a".repeat(63),
14375            "b".repeat(63),
14376            "c".repeat(63),
14377            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
14378        );
14379        assert_eq!(
14380            over_cap.len(),
14381            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
14382        );
14383        s.entrada.as_mut().unwrap().host = over_cap;
14384        let err = s.validate().unwrap_err();
14385        match err {
14386            AplicacaoError::EntradaHostInvalid { reason, .. } => {
14387                let needle = format!(
14388                    "max length of {} bytes",
14389                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
14390                );
14391                assert!(
14392                    reason.contains(&needle),
14393                    "diagnostic must name the lifted \
14394                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
14395                );
14396            }
14397            other => panic!("expected EntradaHostInvalid, got {other:?}"),
14398        }
14399    }
14400
14401    #[test]
14402    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
14403        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
14404        // on the per-label-cap axis. Before the lift, the aplicacao-side
14405        // per-label arm consumed a private const alias
14406        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
14407        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
14408        // split from it at the module boundary — every `.`-separated
14409        // label in a Gateway API v1 Hostname is a DNS-1123 label under
14410        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
14411        // so the private alias's 63 and the canonical const's 63 were
14412        // pinning the same underlying rule twice. Pin the cap through a
14413        // 64-byte label that hits the per-label arm, then read the reason
14414        // for the exact byte count the shared constant carries: any
14415        // future drift on either side (a private alias reintroduced, a
14416        // hard-coded literal at the arm, a mismatch between the two
14417        // 63-byte pins) surfaces at this pin's diagnostic rather than at
14418        // a per-cluster admission rejection whose "field is invalid"
14419        // opacity misframes the root cause.
14420        let mut s = three_member_spec();
14421        let over_cap_label = format!(
14422            "{}.quero.cloud",
14423            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
14424        );
14425        s.entrada.as_mut().unwrap().host = over_cap_label;
14426        let err = s.validate().unwrap_err();
14427        match err {
14428            AplicacaoError::EntradaHostInvalid { reason, .. } => {
14429                let needle = format!(
14430                    "label max length of {} bytes",
14431                    crate::render::DNS_1123_LABEL_MAX_LEN,
14432                );
14433                assert!(
14434                    reason.contains(&needle),
14435                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
14436                     cap verbatim on the per-label arm, got: {reason:?}",
14437                );
14438            }
14439            other => panic!("expected EntradaHostInvalid, got {other:?}"),
14440        }
14441    }
14442
14443    #[test]
14444    fn entrada_with_empty_paths_validates() {
14445        // Empty `:paths` is the documented "match every path" form;
14446        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
14447        let mut s = three_member_spec();
14448        s.entrada.as_mut().unwrap().paths = vec![];
14449        s.validate().unwrap();
14450    }
14451
14452    #[test]
14453    fn entrada_root_path_validates() {
14454        // The author-supplied bare-root `:entrada :paths` entry is the
14455        // same byte-shape the peer emit-side catch-all constant
14456        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
14457        // the author's `:paths` list is empty — sweeping the test-side
14458        // probe literal onto the lifted const closes the two-axis pin
14459        // (author-side admit + emit-side canonical fallback) around
14460        // one `&'static str`, so a future rebrand of the catch-all
14461        // reaches both consumers by construction. Peer to
14462        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
14463        // on the canonical-literal pin surface.
14464        let mut s = three_member_spec();
14465        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
14466        s.validate().unwrap();
14467    }
14468
14469    #[test]
14470    fn placement_strategy_variants_round_trip() {
14471        for s in [
14472            PlacementStrategy::SingleNode,
14473            PlacementStrategy::Replicated,
14474            PlacementStrategy::Sharded,
14475        ] {
14476            let p = Placement {
14477                estrategia: s,
14478                clusters: vec!["rio".into()],
14479                affinity: None,
14480                // Route the paired `:shard-key` fixture-builder through the
14481                // typed cross-slot invariant predicate
14482                // [`PlacementStrategy::requires_shard_key`] rather than the
14483                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
14484                // arm-identity predicate — the two answer the same
14485                // question under today's closed accept-set but a future
14486                // arm addition that consumed `:shard-key` under a
14487                // non-`Sharded` name would silently mis-attach the
14488                // fixture's `:shard-key` if the builder read through the
14489                // arm-identity predicate. The cross-slot-invariant
14490                // predicate migrates through one caixa-core edit on any
14491                // future arm addition; the fixture keeps producing a
14492                // `validate()`-passing round-trip by construction.
14493                shard_key: if s.requires_shard_key() {
14494                    Some("$key".into())
14495                } else {
14496                    None
14497                },
14498            };
14499            let json = serde_json::to_string(&p).unwrap();
14500            let back: Placement = serde_json::from_str(&json).unwrap();
14501            assert_eq!(back, p);
14502        }
14503    }
14504
14505    #[test]
14506    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
14507        // The fail-before-pass-after pin: pre-lift there was no
14508        // single-source binding between the [`PlacementStrategy`]
14509        // variant name the `Serialize` derive emits and the byte-
14510        // string every downstream cluster-side dispatcher (the
14511        // `lareira-fleet-programs` aggregator's per-entry strategy
14512        // branch, the future `app-operator` reconciler, the M3
14513        // Adaptive compression pass's per-strategy weighting) probes
14514        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
14515        // future `#[serde(rename_all = "kebab-case")]` attribute on
14516        // the enum — or a variant rename in the source — would
14517        // silently rebrand the emitted scalar under one spelling
14518        // while every downstream dispatcher still probed the other,
14519        // with the failure surfacing at the aggregator's dispatch
14520        // step or the operator's reconcile posture (workloads coming
14521        // up under the `default()` `Replicated` arm rather than the
14522        // typed slot's declared strategy) far from the source
14523        // rebrand commit and with no field naming the drift. Pinning
14524        // the two paths (the `Serialize` derive's serialized string
14525        // AND the [`PlacementStrategy::as_str`] helper) to the same
14526        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
14527        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14528        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
14529        // makes any future drift on either endpoint fail here at
14530        // caixa-core build time.
14531        for (variant, expected) in [
14532            (
14533                PlacementStrategy::SingleNode,
14534                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14535            ),
14536            (
14537                PlacementStrategy::Replicated,
14538                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14539            ),
14540            (
14541                PlacementStrategy::Sharded,
14542                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14543            ),
14544        ] {
14545            let json = serde_json::to_string(&variant).unwrap();
14546            assert_eq!(
14547                json,
14548                format!("\"{expected}\""),
14549                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
14550            );
14551            assert_eq!(
14552                variant.as_str(),
14553                expected,
14554                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
14555                 M3_PLACEMENT_ESTRATEGIA_* constant"
14556            );
14557        }
14558    }
14559
14560    #[test]
14561    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
14562        // Cross-arm drift-detection pin on the M3
14563        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
14564        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14565        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
14566        // scalar-value pentad: a future collapse of two canonical
14567        // variant byte-strings onto the same value (an accidental
14568        // copy-paste flip of
14569        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
14570        // read `"SingleNode"`, a per-arm rebrand that lands one const
14571        // without touching its paired peer) would silently reroute
14572        // every downstream operator's per-strategy dispatch onto the
14573        // sibling arm's reconcile branch and pass every
14574        // propagation-probe test that expected only the stale arm's
14575        // value — a `Replicated`-declared Aplicacao would come up
14576        // under the `SingleNode` primary-and-standby reconcile
14577        // posture, so every-cluster active-active workload would
14578        // silently collapse onto one-cluster-runs-at-a-time takeover
14579        // semantics against its declared strategy, with no field
14580        // naming the strategy-value drift root cause. Peer of the
14581        // sibling
14582        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
14583        // (09ffb2d) /
14584        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
14585        // (ccdf955) /
14586        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
14587        // (d739850) distinctness pins on the sibling OTP-shape /
14588        // caixa-kind closed-set typed-enum discriminator axes — the
14589        // fourth (and structurally the M3 mesh-primitive-defining)
14590        // closed-set typed-enum axis to converge on the same
14591        // "pairwise-distinct-by-construction" discipline.
14592        //
14593        // Fail-before-pass-after locally verified by mutating
14594        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
14595        // also read `"SingleNode"` — this pin fires as expected;
14596        // restoring passes.
14597        let all = [
14598            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14599            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14600            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14601        ];
14602        for (i, a) in all.iter().enumerate() {
14603            for (j, b) in all.iter().enumerate() {
14604                if i != j {
14605                    assert_ne!(
14606                        a, b,
14607                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
14608                         distinct — got duplicate {a:?} at indices {i} and {j}",
14609                    );
14610                }
14611            }
14612        }
14613    }
14614
14615    #[test]
14616    fn placement_strategy_display_routes_through_as_str_helper() {
14617        // The fail-before-pass-after pin: pre-lift the sibling
14618        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
14619        // / [`crate::supervisor::RestartPolicy`] both carried a stable
14620        // [`std::fmt::Display`] surface via their
14621        // `#[discriminant(also_display)]` gen-platform derive, but
14622        // [`PlacementStrategy`] did not — every consumer reaching for
14623        // a strategy byte-string past the wire format had to pick
14624        // between three paths ([`PlacementStrategy::as_str`], the
14625        // `Serialize` derive's serialized string, or `format!("{v:?}")`
14626        // on the `Debug` derive), any two of which a future variant
14627        // rename or `#[serde(rename_all = "kebab-case")]` attribute
14628        // would silently desynchronize. Wiring [`std::fmt::Display`]
14629        // through [`PlacementStrategy::as_str`] closes the third path:
14630        // every `format!("{v}")` call reaches the same lifted
14631        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
14632        // and the [`PlacementStrategy::as_str`] helper already route
14633        // through, so a future variant rename lands at exactly one
14634        // place. Pin the routing here so a future
14635        // `impl std::fmt::Display for PlacementStrategy` reimplementation
14636        // that hand-rolls the arms instead of delegating to
14637        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
14638        for variant in [
14639            PlacementStrategy::SingleNode,
14640            PlacementStrategy::Replicated,
14641            PlacementStrategy::Sharded,
14642        ] {
14643            assert_eq!(
14644                variant.to_string(),
14645                variant.as_str(),
14646                "PlacementStrategy::{variant:?} Display must route through \
14647                 PlacementStrategy::as_str (single source of truth: the lifted \
14648                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
14649            );
14650        }
14651    }
14652
14653    #[test]
14654    fn placement_strategy_display_matches_serialized_wire_byte_string() {
14655        // The fail-before-pass-after pin on the second half of the
14656        // three-path convergence: `Display` (user-facing text) agrees
14657        // byte-for-byte with the `Serialize` derive's wire format
14658        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
14659        // scalar) on every variant. Pre-lift the two paths were
14660        // structurally independent — a future
14661        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
14662        // would silently rebrand the emitted wire scalar
14663        // (`single-node`, `replicated`, `sharded`) while every consumer
14664        // that pretty-prints the strategy (the M3 diagnostic templates,
14665        // the future `feira app graph` per-Aplicacao strategy line,
14666        // the future M4 CR materializer's admission-webhook rejection
14667        // body) would still emit the TitleCase form the `as_str` /
14668        // `Display` route returns, with the mismatch surfacing at
14669        // consumer parse time / operator dispatch time far from the
14670        // source rebrand commit. Pin the two paths byte-for-byte here
14671        // so any future serde-attribute or variant-rename drift is a
14672        // caixa-core-build-time test failure at this call, not a
14673        // silent per-consumer dispatch miss.
14674        for variant in [
14675            PlacementStrategy::SingleNode,
14676            PlacementStrategy::Replicated,
14677            PlacementStrategy::Sharded,
14678        ] {
14679            let wire = serde_json::to_string(&variant).unwrap();
14680            // Strip the outer `"…"` the JSON string form carries — the
14681            // wire scalar the K8s / YAML apiserver consumes is the
14682            // enclosed byte-string, not the quote wrapper.
14683            let unquoted = wire
14684                .strip_prefix('"')
14685                .and_then(|s| s.strip_suffix('"'))
14686                .expect("serialized PlacementStrategy is a JSON string");
14687            assert_eq!(
14688                variant.to_string(),
14689                unquoted,
14690                "PlacementStrategy::{variant:?} Display byte-string must match the \
14691                 Serialize derive's wire byte-string (three-path convergence: \
14692                 Display + as_str + Serialize all resolve to the same \
14693                 M3_PLACEMENT_ESTRATEGIA_* const)"
14694            );
14695        }
14696    }
14697
14698    #[test]
14699    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
14700        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14701        // derive on [`PlacementStrategy`]: for each of the three variants
14702        // exactly one of the generated `is_single_node` / `is_replicated`
14703        // / `is_sharded` predicates returns `true` and the other two
14704        // return `false`. Prior to this derive the three per-arm
14705        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
14706        // (the `placement_strategy_variants_round_trip` fixture, the
14707        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
14708        // fixture, and the
14709        // `validate_placement_reads_through_lifted_estrategia_accessor`
14710        // fixture) each open-coded a per-arm PartialEq compare against
14711        // the enum variant — three sites that expressed no compile-time
14712        // link back to the closed-set typed dispatch a future fourth
14713        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
14714        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
14715        // would have to thread through in lockstep or one fixture would
14716        // silently disagree with the others on which arms consume the
14717        // `:shard-key` axis. Peer of the sibling
14718        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
14719        // / [`crate::supervisor::RestartPolicy`] /
14720        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
14721        // the sibling closed-set typed-enum discriminator axes — extends
14722        // the same one-typed-dispatch-per-variant discipline onto the
14723        // fifth (and only remaining) closed-set typed-enum discriminator
14724        // on the caixa surface, closing the axis on the M3 mesh-slot
14725        // family.
14726        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
14727            (PlacementStrategy::SingleNode, [true, false, false]),
14728            (PlacementStrategy::Replicated, [false, true, false]),
14729            (PlacementStrategy::Sharded, [false, false, true]),
14730        ];
14731        for (variant, expected) in rows {
14732            let observed = [
14733                variant.is_single_node(),
14734                variant.is_replicated(),
14735                variant.is_sharded(),
14736            ];
14737            assert_eq!(
14738                observed, expected,
14739                "PlacementStrategy::{variant:?} is_* predicates must partition \
14740                 the arm set (single_node, replicated, sharded); got {observed:?}"
14741            );
14742        }
14743    }
14744
14745    #[test]
14746    fn placement_strategy_is_variant_predicates_are_const_fn() {
14747        // The [`gen_platform::IsVariant`] derive emits `const fn`
14748        // predicates on the peer [`crate::CaixaKind`] +
14749        // [`crate::upgrade::UpgradeInstruction`] +
14750        // [`crate::supervisor::RestartStrategy`] +
14751        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
14752        // pin the same posture on [`PlacementStrategy`] so a future
14753        // accidental downgrade to non-`const` (an added runtime helper
14754        // reachable only from a non-`const` context, a manual hand-rolled
14755        // `impl` that shadows the derive-generated method) trips at
14756        // caixa-core build time rather than surfacing as a downstream
14757        // `const`-context regression far from the derive declaration.
14758        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
14759        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
14760        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
14761        assert!(IS_SINGLE_NODE);
14762        assert!(IS_REPLICATED);
14763        assert!(IS_SHARDED);
14764    }
14765
14766    #[test]
14767    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
14768        // Fail-before-pass-after pin on the substrate-lifted
14769        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
14770        // per-arm predicate: for each variant in the closed accept-set the
14771        // predicate returns `true` iff the variant consumes the paired
14772        // [`Placement::shard_key`] axis under
14773        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
14774        // partition. Today the accept-set is the singleton `{Sharded}` —
14775        // `Sharded` is the Akka-style hash-keyed distribution arm
14776        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
14777        // §II.1) and `Replicated` (active-active) refuse the axis through
14778        // [`AplicacaoError::ShardKeyOnNonSharded`].
14779        //
14780        // Pins the per-arm truth-table so a future arm addition (an
14781        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
14782        // roadmap names, a `WeightedShard` promotion the future M5
14783        // adaptive-placement engine acknowledges) that landed a variant
14784        // without extending this predicate's arm-set would surface as a
14785        // caixa-core build-time exhaustiveness error at the
14786        // `match self { … }` arm-fan below rather than a silent per-consumer
14787        // mis-classification at renderer emit time. The paired
14788        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
14789        // predicate stays a distinct question — arm-identity (which the
14790        // sibling
14791        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
14792        // pin already locks) is not cross-slot-invariant consumption; today
14793        // they trip on the same singleton but the pair migrates through
14794        // one caixa-core edit on any future arm addition.
14795        //
14796        // Peer of the sibling per-arm classifier pins
14797        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
14798        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
14799        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
14800        // derived paired predicate on the post-projection typed-view axis
14801        // — same "per-arm semantic-classification predicate paired with
14802        // the arm-identity predicate the derive already emits" discipline
14803        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
14804        // `:placement :shard-key` cross-slot-invariant axis.
14805        let rows: [(PlacementStrategy, bool); 3] = [
14806            (PlacementStrategy::SingleNode, false),
14807            (PlacementStrategy::Replicated, false),
14808            (PlacementStrategy::Sharded, true),
14809        ];
14810        for (variant, expected) in rows {
14811            assert_eq!(
14812                variant.requires_shard_key(),
14813                expected,
14814                "PlacementStrategy::{variant:?}.requires_shard_key() must \
14815                 be {expected} (the substrate-canonical cross-slot invariant \
14816                 on the :placement :shard-key axis; today `Sharded` is the \
14817                 singleton consuming arm — MESH-COMPOSITION §II.4)",
14818            );
14819        }
14820    }
14821
14822    #[test]
14823    fn placement_strategy_requires_shard_key_is_const_fn() {
14824        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
14825        // invariant per-arm predicate is declared `#[must_use] pub const
14826        // fn` — pin the `const`-eval posture here so a future accidental
14827        // downgrade to non-`const` (an added runtime helper reachable
14828        // only from a non-`const` context, a manual hand-rolled `impl`
14829        // that shadows the current three-arm `match self { … }` dispatch)
14830        // trips at caixa-core build time rather than surfacing as a
14831        // downstream `const`-context regression far from the declaration.
14832        // Same shape as the sibling
14833        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
14834        // the peer [`gen_platform::IsVariant`]-derived arm-identity
14835        // predicate axis, but here the load-bearing assertions live in
14836        // module-scope `const _: () = assert!(…)` items so a violation
14837        // fails at compile time (const-eval trip) rather than test time —
14838        // strictly stronger than the runtime `assert!(CONST)` pattern the
14839        // sibling pin uses, and side-steps the
14840        // `clippy::assertions_on_constants` lint the runtime pattern
14841        // otherwise accumulates on the module baseline.
14842        //
14843        // The test body simply witnesses that the module-scope items
14844        // compiled and the runtime dispatch agrees with the const-eval
14845        // dispatch on every arm — the runtime read gives the test a
14846        // failure surface (rather than an empty test body clippy would
14847        // flag as a no-op).
14848        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
14849        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
14850        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
14851        assert_eq!(
14852            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
14853            [
14854                PlacementStrategy::SingleNode.requires_shard_key(),
14855                PlacementStrategy::Replicated.requires_shard_key(),
14856                PlacementStrategy::Sharded.requires_shard_key(),
14857            ],
14858            "runtime and const-eval dispatch on \
14859             PlacementStrategy::requires_shard_key must agree on every arm",
14860        );
14861    }
14862
14863    #[test]
14864    fn placement_estrategia_accessor_is_const_fn() {
14865        // The [`Placement::estrategia`] per-`:placement` distribution-
14866        // strategy `Copy`-return scalar accessor is declared
14867        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
14868        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
14869        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
14870        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
14871        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
14872        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
14873        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
14874        // [`RateLimit`], every one a `pub const fn`). Pin the
14875        // `const`-eval posture here so a future accidental downgrade to
14876        // non-`const` (an added runtime helper reachable only from a
14877        // non-`const` context, a slot promotion to a non-`Copy` return
14878        // that would silently drop the `const` qualifier, a manual
14879        // hand-rolled shadow) trips at caixa-core build time rather
14880        // than surfacing as a downstream `const`-context regression far
14881        // from the declaration.
14882        //
14883        // Same shape as the sibling
14884        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
14885        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
14886        // predicate axis — the load-bearing witness lives in the
14887        // module-scope `const fn` wrapper `estrategia_via_const_fn`
14888        // below: a body that calls [`Placement::estrategia`] under a
14889        // `const fn` signature is well-formed only when the callee is
14890        // itself `const fn`, so any future accidental downgrade of
14891        // [`Placement::estrategia`] to non-`const` fails at caixa-core
14892        // build time (const-eval E0015 / E0658 depending on the arm),
14893        // strictly stronger than a runtime `assert!(CONST)` and
14894        // side-stepping the destructor-in-const restriction that
14895        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
14896        // items on `Placement`'s `Vec<String>` / `Option<String>`
14897        // carriers.
14898        //
14899        // The runtime body witnesses that the const-eval-shaped
14900        // wrapper agrees with a direct call on every closed-set arm.
14901        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
14902            p.estrategia()
14903        }
14904        for estrategia in [
14905            PlacementStrategy::SingleNode,
14906            PlacementStrategy::Replicated,
14907            PlacementStrategy::Sharded,
14908        ] {
14909            let placement = Placement {
14910                estrategia,
14911                clusters: Vec::new(),
14912                affinity: None,
14913                shard_key: None,
14914            };
14915            assert_eq!(
14916                estrategia_via_const_fn(&placement),
14917                placement.estrategia(),
14918                "const-fn-wrapped and direct dispatch on \
14919                 Placement::estrategia must agree for {estrategia:?}",
14920            );
14921        }
14922    }
14923
14924    #[test]
14925    fn entrada_port_accessor_is_const_fn() {
14926        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
14927        // scalar accessor is declared `#[must_use] pub const fn` —
14928        // matching the peer M3 mesh-slot `Copy`-return accessor family
14929        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
14930        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
14931        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
14932        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
14933        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
14934        // [`RateLimit::window`] on the sibling [`RateLimit`], the
14935        // sibling per-`:placement` [`Placement::estrategia`] pinned by
14936        // [`placement_estrategia_accessor_is_const_fn`] above — every
14937        // one a `pub const fn`). Pin the `const`-eval posture here so
14938        // a future accidental downgrade to non-`const` (an added
14939        // runtime helper reachable only from a non-`const` context, an
14940        // `Option<u16>`-shape migration once the substrate grows
14941        // per-`:membros` heterogeneous listener ports that would
14942        // silently drop the `const` qualifier, a manual hand-rolled
14943        // shadow) trips at caixa-core build time rather than surfacing
14944        // as a downstream `const`-context regression far from the
14945        // declaration.
14946        //
14947        // Same shape as the sibling
14948        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
14949        // load-bearing witness lives in the module-scope `const fn`
14950        // wrapper `port_via_const_fn`: a body that calls
14951        // [`Entrada::port`] under a `const fn` signature is well-formed
14952        // only when the callee is itself `const fn`, side-stepping the
14953        // destructor-in-const restriction that would otherwise block a
14954        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
14955        // `String` / `Vec<String>` carriers.
14956        //
14957        // The runtime body sweeps a representative port set spanning
14958        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
14959        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
14960        // ceiling — the const-fn-wrapped call must agree with a direct
14961        // call on every fixture (a violation trips the test) and every
14962        // returned scalar must byte-equal the input `port` (a violation
14963        // means the accessor stopped being a raw field-return copy).
14964        const fn port_via_const_fn(e: &Entrada) -> u16 {
14965            e.port()
14966        }
14967        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
14968            let entrada = Entrada {
14969                host: String::new(),
14970                para: String::new(),
14971                port,
14972                paths: Vec::new(),
14973            };
14974            assert_eq!(
14975                port_via_const_fn(&entrada),
14976                entrada.port(),
14977                "const-fn-wrapped and direct dispatch on Entrada::port \
14978                 must agree for port={port}",
14979            );
14980            assert_eq!(
14981                entrada.port(),
14982                port,
14983                "Entrada::port must return the storage-side u16 verbatim \
14984                 for port={port}",
14985            );
14986        }
14987    }
14988
14989    #[test]
14990    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
14991        // Load-bearing cross-slot-partition pin closing the loop between
14992        // the substrate-lifted
14993        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
14994        // the closed-set typed enum and the actual
14995        // [`AplicacaoSpec::validate_placement`] runtime behavior across
14996        // the paired `:placement :shard-key` axis: every validated
14997        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
14998        // satisfies `placement.shard_key().is_some() ==
14999        // placement.estrategia().requires_shard_key()`. The four-cell
15000        // shape witness sweeps every combination of (variant in the
15001        // closed accept-set, `:shard-key` Some/None) and pins:
15002        //
15003        //   * variant.requires_shard_key() && shard_key.is_some() →
15004        //     validate() passes; the paired shape is the sole
15005        //     `requires_shard_key` arm-family accepted shape.
15006        //   * variant.requires_shard_key() && shard_key.is_none() →
15007        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15008        //     the paired shape is the refused missing-key shape on
15009        //     Sharded-family arms.
15010        //   * !variant.requires_shard_key() && shard_key.is_some() →
15011        //     validate() fails with
15012        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
15013        //     is the refused declared-but-inert shape on non-Sharded-
15014        //     family arms.
15015        //   * !variant.requires_shard_key() && shard_key.is_none() →
15016        //     validate() passes; the paired shape is the sole
15017        //     non-`requires_shard_key` arm-family accepted shape.
15018        //
15019        // The compile-time-exhaustive `match p.estrategia()` dispatch at
15020        // [`AplicacaoSpec::validate_placement`] preserves its structural
15021        // arm-fan (a future arm addition still surfaces a build-time
15022        // exhaustiveness error there); this pin closes the semantic loop
15023        // between the arm-fan's shape-gate cascades and the substrate-
15024        // canonical predicate every downstream consumer of the paired
15025        // shape reads through. Fail-before-pass-after locally verified by
15026        // mutating the predicate's `Sharded => true` arm to `false` — the
15027        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
15028        // `validate() must pass` assertion; restoring passes. Same "close
15029        // the loop between the typed predicate and the runtime behavior"
15030        // discipline as the sibling
15031        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
15032        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
15033        // per-arm classifier axis.
15034        for variant in [
15035            PlacementStrategy::SingleNode,
15036            PlacementStrategy::Replicated,
15037            PlacementStrategy::Sharded,
15038        ] {
15039            for present in [false, true] {
15040                let mut spec = three_member_spec();
15041                spec.placement.estrategia = variant;
15042                spec.placement.shard_key = present.then(|| "tenantId".into());
15043                let expects_ok = variant.requires_shard_key() == present;
15044                let result = spec.validate();
15045                match (expects_ok, &result) {
15046                    (true, Ok(())) => {}
15047                    (false, Err(err)) => {
15048                        // Cross-check the refusal diagnostic names the
15049                        // right cell of the four-cell shape witness — the
15050                        // `requires_shard_key && !present` cell must trip
15051                        // [`AplicacaoError::ShardedWithoutKey`]; the
15052                        // `!requires_shard_key && present` cell must trip
15053                        // [`AplicacaoError::ShardKeyOnNonSharded`].
15054                        match (variant.requires_shard_key(), present, err) {
15055                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
15056                            (
15057                                false,
15058                                true,
15059                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
15060                            ) => {
15061                                assert_eq!(
15062                                    *e, variant,
15063                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
15064                                     the paired PlacementStrategy",
15065                                );
15066                            }
15067                            _ => panic!(
15068                                "unexpected refusal for estrategia={variant:?} \
15069                                 present={present}: {err:?}"
15070                            ),
15071                        }
15072                    }
15073                    (true, Err(err)) => panic!(
15074                        "validate() must pass for estrategia={variant:?} \
15075                         present={present} (requires_shard_key={} == present={present}), \
15076                         got {err:?}",
15077                        variant.requires_shard_key(),
15078                    ),
15079                    (false, Ok(())) => panic!(
15080                        "validate() must fail for estrategia={variant:?} \
15081                         present={present} (requires_shard_key={} != present={present})",
15082                        variant.requires_shard_key(),
15083                    ),
15084                }
15085            }
15086        }
15087    }
15088
15089    #[test]
15090    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
15091        // Pin the M3 diagnostic template routes through the typed
15092        // [`PlacementStrategy`] Display byte-string (rebound from the
15093        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
15094        // routes emitted identical bytes (the `Debug` derive on a
15095        // unit variant emits the variant name verbatim, exactly what
15096        // `as_str` returns), but the two paths were structurally
15097        // independent — a future `#[serde(rename_all = "…")]`
15098        // attribute or variant rename would coordinate the wire /
15099        // `Display` / `as_str` triple through the lifted const but
15100        // leave the `Debug` route on the compiler-derived variant name,
15101        // silently desynchronizing the diagnostic byte-string from the
15102        // wire byte-string. Rebinding the template onto `Display`
15103        // ties the diagnostic to the same lifted
15104        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15105        // emits — drift becomes structurally impossible. Pin the
15106        // byte-string here so a future edit that reverts the template
15107        // to `{estrategia:?}` is caught at caixa-core test time, not
15108        // at consumer dispatch time.
15109        for (variant, expected_scalar) in [
15110            (
15111                PlacementStrategy::SingleNode,
15112                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15113            ),
15114            (
15115                PlacementStrategy::Replicated,
15116                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15117            ),
15118            (
15119                PlacementStrategy::Sharded,
15120                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15121            ),
15122        ] {
15123            let err = AplicacaoError::PlacementWithoutClusters {
15124                estrategia: variant,
15125            };
15126            let msg = err.to_string();
15127            assert!(
15128                msg.starts_with(&format!(":placement {expected_scalar} requires")),
15129                "PlacementWithoutClusters diagnostic for {variant:?} must open \
15130                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15131            );
15132        }
15133    }
15134
15135    #[test]
15136    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
15137        // Peer of
15138        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
15139        // on the second M3 diagnostic that carries the typed
15140        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
15141        // diagnostics now route the strategy scalar through the same
15142        // [`std::fmt::Display`] surface, tying the diagnostic
15143        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
15144        // const set the wire format also emits. The two non-Sharded
15145        // arms are exercised here (the diagnostic exists to flag a
15146        // `:shard-key` slot the current strategy will never consume);
15147        // the peer `Sharded` arm never reaches this diagnostic (the
15148        // `Sharded` strategy consumes `:shard-key` — the
15149        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
15150        // slot instead).
15151        for (variant, expected_scalar) in [
15152            (
15153                PlacementStrategy::SingleNode,
15154                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15155            ),
15156            (
15157                PlacementStrategy::Replicated,
15158                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15159            ),
15160        ] {
15161            let err = AplicacaoError::ShardKeyOnNonSharded {
15162                estrategia: variant,
15163                shard_key: "$tenantId".into(),
15164            };
15165            let msg = err.to_string();
15166            assert!(
15167                msg.starts_with(&format!(":placement {expected_scalar} carries")),
15168                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
15169                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15170            );
15171        }
15172    }
15173
15174    #[test]
15175    fn placement_strategy_all_enumerates_every_variant_once() {
15176        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
15177        // exhaustive-iteration surface: every variant appears exactly
15178        // once, and the slice length matches the arm count of the
15179        // closed set. Every consumer that walks the accepted-strategy
15180        // set (a future `feira app placement --list` CLI-side surfacing,
15181        // a future M4 admission-webhook's rejection body naming the
15182        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
15183        // reverse-projection consumers that iterate the accept-set for
15184        // a "did you mean" hint) reads through this slice, so a future
15185        // variant addition (an `Anycast` mesh-anycast arm the
15186        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
15187        // grows the enum but forgets to grow [`Self::ALL`] silently
15188        // truncates every downstream consumer's accept-set at the same
15189        // pre-addition boundary — this pin fails at caixa-core build
15190        // time on the pairwise-distinct + arm-count invariants.
15191        //
15192        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
15193        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
15194        // pins on the peer closed-set typed-enum axes.
15195        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
15196        assert_eq!(
15197            all.len(),
15198            3,
15199            "PlacementStrategy::ALL must enumerate every variant of the \
15200             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
15201        );
15202        for (i, a) in all.iter().enumerate() {
15203            for (j, b) in all.iter().enumerate() {
15204                if i != j {
15205                    assert_ne!(
15206                        a, b,
15207                        "PlacementStrategy::ALL must carry every variant exactly \
15208                         once — got duplicate {a:?} at indices {i} and {j}"
15209                    );
15210                }
15211            }
15212        }
15213        for variant in [
15214            PlacementStrategy::SingleNode,
15215            PlacementStrategy::Replicated,
15216            PlacementStrategy::Sharded,
15217        ] {
15218            assert!(
15219                all.contains(&variant),
15220                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
15221                 addition that grows the enum but forgets to grow the ALL slice \
15222                 silently truncates every downstream consumer's accept-set at the \
15223                 pre-addition boundary"
15224            );
15225        }
15226    }
15227
15228    #[test]
15229    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
15230        // Fail-before-pass-after pin on the forward accept-set of the
15231        // [`PlacementStrategy::from_wire`] reverse projection: every
15232        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
15233        // constant the [`PlacementStrategy::as_str`] emitter walks
15234        // parses back to its paired variant. Any future arm addition
15235        // that grows the emitter's `as_str` match but forgets to grow
15236        // the parser's `from_str` match silently splits the two halves
15237        // of the round-trip — the wire byte-string one non-serde
15238        // consumer parses from the one the emitter wrote — with the
15239        // failure surfacing at parse time far from the rebrand commit.
15240        // Pinning the three-arm accept-set here catches the drift at
15241        // caixa-core build time.
15242        //
15243        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
15244        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
15245        // closed-set typed-enum `str → Self` axes.
15246        for (wire, expected) in [
15247            (
15248                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15249                PlacementStrategy::SingleNode,
15250            ),
15251            (
15252                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15253                PlacementStrategy::Replicated,
15254            ),
15255            (
15256                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15257                PlacementStrategy::Sharded,
15258            ),
15259        ] {
15260            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15261                panic!(
15262                    "PlacementStrategy::from_wire({wire:?}) must accept every \
15263                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
15264                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
15265                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
15266                )
15267            });
15268            assert_eq!(
15269                parsed, expected,
15270                "PlacementStrategy::from_wire({wire:?}) must return \
15271                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
15272            );
15273        }
15274    }
15275
15276    #[test]
15277    fn placement_strategy_from_wire_round_trips_through_as_str() {
15278        // Fail-before-pass-after pin on the closed round-trip between
15279        // the forward [`PlacementStrategy::as_str`] emitter and the
15280        // reverse [`PlacementStrategy::from_wire`] parser: for every
15281        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
15282        // output must return exactly the same variant. Any per-arm
15283        // divergence — a future arm added to `as_str` but not
15284        // `from_str`, an accidental copy-paste flip in one but not the
15285        // other — silently splits the emit and parse halves and the
15286        // failure surfaces at consumer parse time far from the drift
15287        // site. The `ALL`-iterating shape means a future variant
15288        // addition picks up the coverage by construction.
15289        //
15290        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
15291        // [`crate::CaixaKind::from_wire`] and the
15292        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
15293        // sibling round-trip pin on [`RateLimitUnit`].
15294        for &variant in PlacementStrategy::ALL {
15295            let wire = variant.as_str();
15296            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15297                panic!(
15298                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15299                     must be Some({variant:?}) — the two halves of the round-trip \
15300                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
15301                     got None on wire byte-string {wire:?}"
15302                )
15303            });
15304            assert_eq!(
15305                parsed, variant,
15306                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15307                 must round-trip to the same variant; got {parsed:?}"
15308            );
15309        }
15310    }
15311
15312    #[test]
15313    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
15314        // Fail-before-pass-after pin on the closed-set refusal
15315        // discipline of [`PlacementStrategy::from_wire`]: every
15316        // byte-string outside the three-arm accept-set returns `None`
15317        // rather than silently collapsing onto the [`Default`]
15318        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
15319        // exercised here sweeps the load-bearing drift shapes: the
15320        // empty string (a stripped serde-attribute drift), an all-
15321        // whitespace string (the canonical text-editor accidental
15322        // padding shape), the lowercased kebab-case forms a future
15323        // `#[serde(rename_all = "kebab-case")]` attribute would emit
15324        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
15325        // coincidentally match the accepted canonical scalars, so only
15326        // `"single-node"` fires as a refusal, but pinning the case-
15327        // sensitivity of the accepted arms via the peer [`SingleNode`]
15328        // assertion in the round-trip pin makes the discipline
15329        // structurally clear), the lowercased single-word forms
15330        // (`"singlenode"`), the padded canonical scalar
15331        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
15332        // (`"Sharded\n"`), and a pointer-different `&'static str` that
15333        // happens to alias a canonical byte-string by content but not
15334        // by identity (validated implicitly by the emitter's routing
15335        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
15336        // identity a paired [`crate::assert_str_reexport_identity`] pin
15337        // in caixa-core's per-const declaration surface would catch).
15338        //
15339        // Peer of the sibling
15340        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15341        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
15342        for bad in [
15343            "",
15344            " ",
15345            "\n",
15346            "\t",
15347            "single-node",
15348            "singlenode",
15349            "SingleNodes",
15350            "single_node",
15351            "single node",
15352            "SINGLENODE",
15353            "SingleNode ",
15354            " SingleNode",
15355            " Sharded ",
15356            "Sharded\n",
15357            "replicated ",
15358            "sharded",
15359            "REPLICATED",
15360            "Anycast",
15361            "Global",
15362            "?",
15363        ] {
15364            assert!(
15365                PlacementStrategy::from_wire(bad).is_none(),
15366                "PlacementStrategy::from_wire({bad:?}) must return None — the \
15367                 parser's accept-set is exactly the three PlacementStrategy::as_str \
15368                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
15369                 is outside that closed set"
15370            );
15371        }
15372    }
15373
15374    #[test]
15375    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
15376        // Fail-before-pass-after pin on the third path of the four-path
15377        // convergence: `from_str` (the reverse projection) inverts the
15378        // `Serialize` derive's wire byte-string on every variant.
15379        // Together with the pre-existing three-path convergence
15380        // (`Display` + `as_str` + `Serialize` all resolve to the same
15381        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
15382        // the peer
15383        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
15384        // this closes the round-trip: the wire byte-string the
15385        // `Serialize` derive emits parses back to the same variant
15386        // through `from_str`, so any future serde-attribute or variant-
15387        // rename drift on the emit half now surfaces as a matched drift
15388        // on the parse half at caixa-core build time — the two halves
15389        // migrate as a unit through the lifted consts on any future
15390        // rename, and the round-trip cannot silently split.
15391        //
15392        // Peer of the sibling
15393        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
15394        // wire-format pin — extends the three-path convergence
15395        // (`Display` + `as_str` + `Serialize`) onto the fourth path
15396        // (`from_str`), closing the `str ↔ Self` round-trip on the
15397        // M3 `:placement :estrategia` closed-set axis.
15398        for &variant in PlacementStrategy::ALL {
15399            let wire = serde_json::to_string(&variant).unwrap();
15400            let unquoted = wire
15401                .strip_prefix('"')
15402                .and_then(|s| s.strip_suffix('"'))
15403                .expect("serialized PlacementStrategy is a JSON string");
15404            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
15405                panic!(
15406                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
15407                     Serialize derive's wire byte-string for \
15408                     PlacementStrategy::{variant:?} — the four-path convergence \
15409                     (Display + as_str + Serialize + from_str) resolves through \
15410                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
15411                )
15412            });
15413            assert_eq!(
15414                parsed, variant,
15415                "PlacementStrategy::from_wire of the Serialize derive's wire \
15416                 byte-string for PlacementStrategy::{variant:?} must round-trip \
15417                 to the same variant; got {parsed:?}"
15418            );
15419        }
15420    }
15421
15422    #[test]
15423    fn rejects_zero_policy_timeout() {
15424        let mut s = three_member_spec();
15425        s.politicas.timeout = Some(Duration::ZERO);
15426        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15427    }
15428
15429    #[test]
15430    fn rejects_zero_policy_retries() {
15431        let mut s = three_member_spec();
15432        s.politicas.retries = Some(0);
15433        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
15434    }
15435
15436    #[test]
15437    fn rejects_policy_retries_above_cap() {
15438        // The fail-before-pass-after pin: `Some(11)` is structurally
15439        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
15440        // passed validate on every pre-gate codebase because the
15441        // typed slot's only check was the zero-floor arm. The
15442        // thundering-herd amplification vector only surfaced at the
15443        // runtime substrate (Envoy / Cilium L7 retry overlay)
15444        // far from the source caixa.lisp with no field naming the
15445        // offending policy.
15446        let mut s = three_member_spec();
15447        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
15448        assert_eq!(
15449            s.validate().unwrap_err(),
15450            AplicacaoError::PolicyRetriesExceedsCap {
15451                retries: POLICY_RETRIES_MAX + 1
15452            }
15453        );
15454    }
15455
15456    #[test]
15457    fn rejects_policy_retries_far_above_cap() {
15458        // The `u32::MAX` worst case — the four-billion-retry policy
15459        // a typo (`(:retries 4294967295)`) or struct-literal
15460        // copy-paste lands in the slot. Pin the cap arm's coverage
15461        // explicitly across the full `u32` overflow so a future
15462        // relaxation that drops the upper bound surfaces here.
15463        let mut s = three_member_spec();
15464        s.politicas.retries = Some(u32::MAX);
15465        assert_eq!(
15466            s.validate().unwrap_err(),
15467            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
15468        );
15469    }
15470
15471    #[test]
15472    fn accepts_policy_retries_at_cap() {
15473        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
15474        // must validate. The cap is inclusive on the top edge,
15475        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15476        // discipline on the sibling [`crate::LimitsSpec::memory`]
15477        // axis. Pin the boundary explicitly so a future off-by-one
15478        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
15479        // surfaces here as a test failure rather than a silent
15480        // contract narrowing.
15481        let mut s = three_member_spec();
15482        s.politicas.retries = Some(POLICY_RETRIES_MAX);
15483        s.validate()
15484            .expect("retries == POLICY_RETRIES_MAX must validate");
15485    }
15486
15487    #[test]
15488    fn accepts_policy_retries_typical_values() {
15489        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
15490        // every value in the validated set must pass. The
15491        // Envoy / Istio production-playbook recommendation band
15492        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
15493        // (`maxRetries ≤ 10`) both lie within this set.
15494        for r in 1..=POLICY_RETRIES_MAX {
15495            let mut s = three_member_spec();
15496            s.politicas.retries = Some(r);
15497            s.validate()
15498                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
15499        }
15500    }
15501
15502    #[test]
15503    fn policy_retries_zero_takes_precedence_over_cap() {
15504        // The cross-arm ordering pin: `Some(0)` is structurally
15505        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
15506        // (cap), but the zero-floor diagnostic is the more
15507        // self-locating one (it directly names the omit-axis
15508        // remediation), so the validate gate must fire on zero
15509        // first. Pin the order so a future refactor that reorders
15510        // the arms surfaces here as a test failure rather than a
15511        // silent diagnostic regression. Same shape every other
15512        // zero-then-shape ordering on this surface uses
15513        // ([`AplicacaoError::PolicyTimeoutZero`] then
15514        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
15515        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
15516        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
15517        let mut s = three_member_spec();
15518        s.politicas.retries = Some(0);
15519        assert_eq!(
15520            s.validate().unwrap_err(),
15521            AplicacaoError::PolicyRetriesZero,
15522            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
15523        );
15524    }
15525
15526    #[test]
15527    fn policy_retries_cap_diagnostic_carries_offending_value() {
15528        // The diagnostic-shape pin: the offending `u32` is carried
15529        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
15530        // variant so the surfaced error message names the value the
15531        // author wrote (`":politicas :retries (47) exceeds the
15532        // mesh-policy ceiling …"`), not just the cap. Same
15533        // self-locating diagnostic shape every other typed-cap arm
15534        // on this surface carries
15535        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15536        // offending byte count verbatim).
15537        let mut s = three_member_spec();
15538        s.politicas.retries = Some(47);
15539        let err = s.validate().unwrap_err();
15540        assert!(
15541            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
15542            "got {err:?}"
15543        );
15544        let msg = err.to_string();
15545        assert!(
15546            msg.contains("47"),
15547            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
15548        );
15549    }
15550
15551    #[test]
15552    fn policy_retries_cap_is_aws_app_mesh_aligned() {
15553        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
15554        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
15555        // schema cap — the only upstream mesh-policy schema that
15556        // documents an explicit hard cap. Pinning the literal value
15557        // here surfaces a future drift (a relaxation to 20, a
15558        // tightening to 5) as a deliberate test edit, not a silent
15559        // contract narrowing.
15560        assert_eq!(POLICY_RETRIES_MAX, 10);
15561    }
15562
15563    #[test]
15564    fn rejects_circuit_breaker_zero_max_failures() {
15565        let mut s = three_member_spec();
15566        s.politicas.circuit_breaker = Some(CircuitBreaker {
15567            max_failures: 0,
15568            window: Duration::from_secs(60),
15569        });
15570        assert_eq!(
15571            s.validate().unwrap_err(),
15572            AplicacaoError::PolicyBreakerZeroFailures
15573        );
15574    }
15575
15576    #[test]
15577    fn rejects_circuit_breaker_max_failures_above_cap() {
15578        // The fail-before-pass-after pin: `1001` is structurally one
15579        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
15580        // silently passed validate on every pre-gate codebase
15581        // because the typed slot's only check was the zero-floor
15582        // arm. The breaker-no-op vector only surfaced at the runtime
15583        // substrate (Envoy / Cilium L7 outlier-detection overlay)
15584        // far from the source caixa.lisp with no field naming the
15585        // offending policy.
15586        let mut s = three_member_spec();
15587        s.politicas.circuit_breaker = Some(CircuitBreaker {
15588            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15589            window: Duration::from_secs(60),
15590        });
15591        assert_eq!(
15592            s.validate().unwrap_err(),
15593            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15594                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15595            }
15596        );
15597    }
15598
15599    #[test]
15600    fn rejects_circuit_breaker_max_failures_far_above_cap() {
15601        // The `u32::MAX` worst case — the four-billion-failure
15602        // threshold a typo (`(:max-failures 4294967295)`) or a
15603        // struct-literal copy-paste lands in the slot. Pin the cap
15604        // arm's coverage explicitly across the full `u32` overflow
15605        // so a future relaxation that drops the upper bound surfaces
15606        // here.
15607        let mut s = three_member_spec();
15608        s.politicas.circuit_breaker = Some(CircuitBreaker {
15609            max_failures: u32::MAX,
15610            window: Duration::from_secs(60),
15611        });
15612        assert_eq!(
15613            s.validate().unwrap_err(),
15614            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15615                max_failures: u32::MAX,
15616            }
15617        );
15618    }
15619
15620    #[test]
15621    fn accepts_circuit_breaker_max_failures_at_cap() {
15622        // The boundary value — exactly
15623        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
15624        // cap is inclusive on the top edge, matching the
15625        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15626        // discipline on the sibling capped axes. Pin the boundary
15627        // explicitly so a future off-by-one tightening
15628        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
15629        // surfaces here as a test failure rather than a silent
15630        // contract narrowing.
15631        let mut s = three_member_spec();
15632        s.politicas.circuit_breaker = Some(CircuitBreaker {
15633            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
15634            window: Duration::from_secs(60),
15635        });
15636        s.validate()
15637            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
15638    }
15639
15640    #[test]
15641    fn accepts_circuit_breaker_max_failures_typical_values() {
15642        // The documented production-playbook band positive-control
15643        // sweep — every value Hystrix / Istio / Envoy / Polly /
15644        // Resilience4j recommend (5..=50) must pass, plus a sweep
15645        // through the hyperscale band (100, 500, 1000) the cap
15646        // accepts. Pin the inclusive validated set explicitly so a
15647        // future tightening of the ceiling surfaces here.
15648        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
15649            let mut s = three_member_spec();
15650            s.politicas.circuit_breaker = Some(CircuitBreaker {
15651                max_failures: n,
15652                window: Duration::from_secs(60),
15653            });
15654            s.validate()
15655                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
15656        }
15657    }
15658
15659    #[test]
15660    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
15661        // The cross-arm ordering pin: `0` is structurally outside
15662        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
15663        // (cap), but the zero-floor diagnostic is the more
15664        // self-locating one (it directly names the omit-axis
15665        // remediation), so the validate gate must fire on zero
15666        // first. Same shape every other zero-then-shape ordering on
15667        // this surface uses
15668        // ([`AplicacaoError::PolicyRetriesZero`] then
15669        // [`AplicacaoError::PolicyRetriesExceedsCap`];
15670        // [`AplicacaoError::PolicyTimeoutZero`] then
15671        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
15672        let mut s = three_member_spec();
15673        s.politicas.circuit_breaker = Some(CircuitBreaker {
15674            max_failures: 0,
15675            window: Duration::from_secs(60),
15676        });
15677        assert_eq!(
15678            s.validate().unwrap_err(),
15679            AplicacaoError::PolicyBreakerZeroFailures,
15680            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
15681        );
15682    }
15683
15684    #[test]
15685    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
15686        // The cross-arm ordering pin between the cap and the
15687        // sibling `:window` gates (zero-window, canonical-window).
15688        // A breaker carrying both an over-cap `max_failures` AND a
15689        // structurally invalid window (zero, sub-ms) must surface
15690        // the cap diagnostic first — the cap arm is wired
15691        // immediately after the zero-failure arm and strictly
15692        // before the window arms, so the offending value the
15693        // diagnostic names matches the order the author would
15694        // discover the gates by reading top-to-bottom through
15695        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
15696        // future refactor that reorders the arms surfaces here as a
15697        // test failure rather than a silent diagnostic regression.
15698        let mut s = three_member_spec();
15699        s.politicas.circuit_breaker = Some(CircuitBreaker {
15700            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15701            window: Duration::ZERO,
15702        });
15703        assert_eq!(
15704            s.validate().unwrap_err(),
15705            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15706                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15707            },
15708            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
15709        );
15710    }
15711
15712    #[test]
15713    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
15714        // The diagnostic-shape pin: the offending `u32` is carried
15715        // verbatim into the
15716        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
15717        // variant so the surfaced error message names the value the
15718        // author wrote (`":politicas :circuit-breaker :max-failures
15719        // (50000) exceeds the mesh-policy ceiling …"`), not just
15720        // the cap. Same self-locating diagnostic shape every other
15721        // typed-cap arm on this surface carries
15722        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
15723        // offending retry count verbatim,
15724        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15725        // offending byte count verbatim).
15726        let mut s = three_member_spec();
15727        s.politicas.circuit_breaker = Some(CircuitBreaker {
15728            max_failures: 50_000,
15729            window: Duration::from_secs(60),
15730        });
15731        let err = s.validate().unwrap_err();
15732        assert!(
15733            matches!(
15734                err,
15735                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15736                    max_failures: 50_000
15737                }
15738            ),
15739            "got {err:?}"
15740        );
15741        let msg = err.to_string();
15742        assert!(
15743            msg.contains("50000"),
15744            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
15745        );
15746    }
15747
15748    #[test]
15749    fn policy_breaker_max_failures_cap_pins_canonical_value() {
15750        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
15751        // value at 1000 — an order of magnitude above every
15752        // documented production-playbook recommendation band
15753        // (Hystrix `requestVolumeThreshold` default 20, Istio
15754        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
15755        // `outlier_detection.consecutive_5xx` default 5, Polly /
15756        // Resilience4j typical 5..=50) and below the
15757        // clearly-pathological "effectively no protection" floor
15758        // (10_000, 100_000, u32::MAX). Pinning the literal value
15759        // here surfaces a future drift (a relaxation to 10_000, a
15760        // tightening to 100) as a deliberate test edit, not a
15761        // silent contract narrowing.
15762        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
15763    }
15764
15765    #[test]
15766    fn rejects_circuit_breaker_zero_window() {
15767        let mut s = three_member_spec();
15768        s.politicas.circuit_breaker = Some(CircuitBreaker {
15769            max_failures: 5,
15770            window: Duration::ZERO,
15771        });
15772        assert_eq!(
15773            s.validate().unwrap_err(),
15774            AplicacaoError::PolicyBreakerZeroWindow
15775        );
15776    }
15777
15778    #[test]
15779    fn rejects_zero_rate_limit() {
15780        let mut s = three_member_spec();
15781        s.politicas.rate_limit = Some(RateLimit {
15782            rate: 0,
15783            window: Duration::from_secs(1),
15784        });
15785        assert_eq!(
15786            s.validate().unwrap_err(),
15787            AplicacaoError::PolicyRateLimitZero
15788        );
15789    }
15790
15791    #[test]
15792    fn rejects_rate_limit_zero_window() {
15793        // `RateLimit { rate: 100, window: Duration::ZERO }` is
15794        // constructible programmatically (the typed `Duration` field
15795        // imposes no nonzero invariant) but renders through
15796        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
15797        // codec's `parse` rejects as `unknown rate-limit window unit
15798        // "0s"`. Until this validate-time gate landed the typed slot
15799        // accepted the value silently and the round-trip break only
15800        // surfaced at deserialize time (potentially in a downstream
15801        // consumer that never re-validates). Pin the rejection at
15802        // `AplicacaoSpec::validate` so the typed slot's valid set
15803        // matches the codec's round-trippable set structurally.
15804        let mut s = three_member_spec();
15805        s.politicas.rate_limit = Some(RateLimit {
15806            rate: 100,
15807            window: Duration::ZERO,
15808        });
15809        assert_eq!(
15810            s.validate().unwrap_err(),
15811            AplicacaoError::PolicyRateLimitWindowNotCanonical {
15812                window: Duration::ZERO
15813            }
15814        );
15815    }
15816
15817    #[test]
15818    fn rejects_rate_limit_arbitrary_seconds_window() {
15819        // 45 seconds is a valid `Duration` but not one of the three
15820        // canonical rate-limit windows the codec round-trips
15821        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
15822        // refuses on round-trip — same round-trip-break shape the
15823        // zero-window arm above pins, with a non-zero magnitude to
15824        // guard against a future "reject only zero" half-measure.
15825        let mut s = three_member_spec();
15826        let window = Duration::from_secs(45);
15827        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
15828        assert_eq!(
15829            s.validate().unwrap_err(),
15830            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15831        );
15832    }
15833
15834    #[test]
15835    fn rejects_rate_limit_two_minute_window() {
15836        // 120 seconds = 2 minutes is a "looks-canonical" but
15837        // not-canonical window: it's a clean integer multiple of the
15838        // minute unit, but the codec only round-trips the
15839        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
15840        // A `Duration::from_secs(120)` window renders as `"100/120s"`
15841        // which the parser rejects. Pinning this case rules out a
15842        // future "accept any clean multiple of s/m/h" relaxation
15843        // that would silently break the codec contract.
15844        let mut s = three_member_spec();
15845        let window = Duration::from_secs(120);
15846        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
15847        assert_eq!(
15848            s.validate().unwrap_err(),
15849            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15850        );
15851    }
15852
15853    #[test]
15854    fn rejects_rate_limit_subsecond_window() {
15855        // A sub-second window (e.g. 500ms) is a valid `Duration` but
15856        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
15857        // Pin the rejection so a future relaxation can't silently
15858        // admit fractional-second windows that the codec can't
15859        // round-trip.
15860        let mut s = three_member_spec();
15861        let window = Duration::from_millis(500);
15862        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
15863        assert_eq!(
15864            s.validate().unwrap_err(),
15865            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15866        );
15867    }
15868
15869    #[test]
15870    fn rejects_policy_rate_limit_above_cap() {
15871        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
15872        // is structurally one past the cap and silently passed
15873        // validate on every pre-gate codebase because the typed slot's
15874        // only `rate` check was the zero-floor arm. The no-op-limiter
15875        // shape only surfaced at the runtime substrate (Envoy's
15876        // `local_rate_limit.token_bucket.max_tokens`, the future
15877        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
15878        // with no field naming the offending policy.
15879        let mut s = three_member_spec();
15880        s.politicas.rate_limit = Some(RateLimit {
15881            rate: POLICY_RATE_LIMIT_MAX + 1,
15882            window: Duration::from_secs(1),
15883        });
15884        assert_eq!(
15885            s.validate().unwrap_err(),
15886            AplicacaoError::PolicyRateLimitExceedsCap {
15887                rate: POLICY_RATE_LIMIT_MAX + 1
15888            }
15889        );
15890    }
15891
15892    #[test]
15893    fn rejects_policy_rate_limit_far_above_cap() {
15894        // The `u32::MAX` worst case — the four-billion-token rate-limit
15895        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
15896        // copy-paste lands in the slot. Pin the cap arm's coverage
15897        // explicitly across the full `u32` overflow so a future
15898        // relaxation that drops the upper bound surfaces here. Peer to
15899        // `rejects_policy_retries_far_above_cap` on the sibling
15900        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
15901        // on the sibling `:max-failures` axis.
15902        let mut s = three_member_spec();
15903        s.politicas.rate_limit = Some(RateLimit {
15904            rate: u32::MAX,
15905            window: Duration::from_secs(1),
15906        });
15907        assert_eq!(
15908            s.validate().unwrap_err(),
15909            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
15910        );
15911    }
15912
15913    #[test]
15914    fn accepts_policy_rate_limit_at_cap() {
15915        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
15916        // must validate. The cap is inclusive on the top edge, matching
15917        // every other typed upper bound in this crate
15918        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
15919        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
15920        // across all three canonical windows so a future off-by-one
15921        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
15922        // window-conditional cap surfaces here as a test failure rather
15923        // than a silent contract narrowing.
15924        for secs in [1u64, 60, 3600] {
15925            let mut s = three_member_spec();
15926            s.politicas.rate_limit = Some(RateLimit {
15927                rate: POLICY_RATE_LIMIT_MAX,
15928                window: Duration::from_secs(secs),
15929            });
15930            s.validate().unwrap_or_else(|e| {
15931                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
15932            });
15933        }
15934    }
15935
15936    #[test]
15937    fn accepts_policy_rate_limit_typical_values() {
15938        // The documented production-playbook recommendation band —
15939        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
15940        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
15941        // Enterprise ~1M per-hour. Every value in the validated set
15942        // must pass; pin the band explicitly so a future tightening
15943        // surfaces here.
15944        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
15945            for secs in [1u64, 60, 3600] {
15946                let mut s = three_member_spec();
15947                s.politicas.rate_limit = Some(RateLimit {
15948                    rate,
15949                    window: Duration::from_secs(secs),
15950                });
15951                s.validate().unwrap_or_else(|e| {
15952                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
15953                });
15954            }
15955        }
15956    }
15957
15958    #[test]
15959    fn policy_rate_limit_zero_takes_precedence_over_cap() {
15960        // The cross-arm ordering pin: `rate == 0` is structurally
15961        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
15962        // (cap), but the zero-floor diagnostic is the more
15963        // self-locating one (it directly names the omit-axis
15964        // remediation). Pin the order so a future refactor that
15965        // reorders the arms surfaces here as a test failure rather
15966        // than a silent diagnostic regression. Same shape every other
15967        // zero-then-cap ordering on this surface uses
15968        // ([`AplicacaoError::PolicyRetriesZero`] then
15969        // [`AplicacaoError::PolicyRetriesExceedsCap`];
15970        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15971        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15972        let mut s = three_member_spec();
15973        s.politicas.rate_limit = Some(RateLimit {
15974            rate: 0,
15975            window: Duration::from_secs(1),
15976        });
15977        assert_eq!(
15978            s.validate().unwrap_err(),
15979            AplicacaoError::PolicyRateLimitZero,
15980            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
15981        );
15982    }
15983
15984    #[test]
15985    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
15986        // Two-axis-bad pin: rate above cap *and* window non-canonical.
15987        // The validate gate must fire on the rate cap first — the
15988        // amplification-shape (no-op limiter) diagnostic is the more
15989        // fundamental one; the window-canonical diagnostic is the
15990        // narrower codec-round-trip shape. Pin the ordering so a future
15991        // refactor that reorders the rate-then-window check arms
15992        // surfaces here as a test failure rather than a silent
15993        // diagnostic regression.
15994        let mut s = three_member_spec();
15995        s.politicas.rate_limit = Some(RateLimit {
15996            rate: POLICY_RATE_LIMIT_MAX + 1,
15997            window: Duration::from_secs(45),
15998        });
15999        assert_eq!(
16000            s.validate().unwrap_err(),
16001            AplicacaoError::PolicyRateLimitExceedsCap {
16002                rate: POLICY_RATE_LIMIT_MAX + 1
16003            },
16004            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16005        );
16006    }
16007
16008    #[test]
16009    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
16010        // The diagnostic-shape pin: the offending `u32` is carried
16011        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
16012        // variant so the surfaced error message names the value the
16013        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
16014        // the mesh-policy ceiling …"`), not just the cap. Same
16015        // self-locating diagnostic shape every other typed-cap arm on
16016        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
16017        // carries the offending retries count verbatim,
16018        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
16019        // the offending failure count verbatim).
16020        let mut s = three_member_spec();
16021        s.politicas.rate_limit = Some(RateLimit {
16022            rate: 5_000_000,
16023            window: Duration::from_secs(1),
16024        });
16025        let err = s.validate().unwrap_err();
16026        assert!(
16027            matches!(
16028                err,
16029                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
16030            ),
16031            "got {err:?}"
16032        );
16033        let msg = err.to_string();
16034        assert!(
16035            msg.contains("5000000"),
16036            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
16037        );
16038    }
16039
16040    #[test]
16041    fn policy_rate_limit_cap_pins_canonical_value() {
16042        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
16043        // 1_000_000 — two-to-three orders of magnitude above every
16044        // documented production-playbook recommendation band (Envoy /
16045        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
16046        // Gateway 10_000..=100_000 per-minute) and below the
16047        // clearly-pathological "paste-from-binary blob" floor
16048        // (100_000_000, u32::MAX). Pinning the literal value here
16049        // surfaces a future drift (a relaxation to 10_000_000, a
16050        // tightening to 100_000) as a deliberate test edit, not a
16051        // silent contract narrowing.
16052        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
16053    }
16054
16055    #[test]
16056    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
16057        // Both axes are invalid here: rate == 0 *and* window is
16058        // non-canonical. The validate gate must fire on rate first
16059        // (matching the existing `rejects_zero_rate_limit` ordering),
16060        // so the existing diagnostic continues to lead with the
16061        // simpler "zero rate" framing. Pinning the order of checks
16062        // so a future refactor that reorders the arms surfaces here
16063        // as a test failure rather than a silent diagnostic
16064        // regression.
16065        let mut s = three_member_spec();
16066        s.politicas.rate_limit = Some(RateLimit {
16067            rate: 0,
16068            window: Duration::from_secs(45),
16069        });
16070        assert_eq!(
16071            s.validate().unwrap_err(),
16072            AplicacaoError::PolicyRateLimitZero
16073        );
16074    }
16075
16076    #[test]
16077    fn rate_limit_canonical_windows_validate() {
16078        // The three canonical windows the codec round-trips
16079        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
16080        // unchanged. Pin the full canonical set as a positive case
16081        // (the existing `rate_limit_round_trip_seconds` /
16082        // `rate_limit_round_trip_minutes` tests pin the
16083        // serialize-then-deserialize property at the codec layer; this
16084        // test pins the validate-side complement so a future tightening
16085        // of the canonical set — e.g. dropping `:hour` — surfaces here
16086        // as a test failure rather than a silent contract narrowing).
16087        for secs in [1u64, 60, 3600] {
16088            let mut s = three_member_spec();
16089            s.politicas.rate_limit = Some(RateLimit {
16090                rate: 100,
16091                window: Duration::from_secs(secs),
16092            });
16093            s.validate().expect("canonical window must validate");
16094        }
16095    }
16096
16097    #[test]
16098    fn rate_limit_validated_value_round_trips_through_codec() {
16099        // The structural property the validate gate enforces:
16100        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
16101        // losslessly through the `rate_limit_codec` (serialize → string
16102        // → deserialize → equal value). Pin this end-to-end so a future
16103        // change to either side (the validate gate's accepted window
16104        // set, the codec's parse/render unit set) that breaks the
16105        // alignment surfaces here. The previous-state shape (typed
16106        // slot accepts arbitrary `Duration`, codec only round-trips
16107        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
16108        // window — the validate gate now forecloses that.
16109        for secs in [1u64, 60, 3600] {
16110            let mut s = three_member_spec();
16111            s.politicas.rate_limit = Some(RateLimit {
16112                rate: 250,
16113                window: Duration::from_secs(secs),
16114            });
16115            s.validate().unwrap();
16116            let json = serde_json::to_string(&s.politicas).unwrap();
16117            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16118            assert_eq!(
16119                back.rate_limit, s.politicas.rate_limit,
16120                "every validated :rate-limit must round-trip losslessly through the codec"
16121            );
16122        }
16123    }
16124
16125    #[test]
16126    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
16127        // The hour-window canonical form (`"<n>/h"`) was missing from
16128        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
16129        // pair. Now that the validate gate pins 3600s as part of the
16130        // canonical set, pin its serialize-side render shape too so
16131        // the third leg of the s/m/h tripod is explicitly tested.
16132        let policy = MeshPolicy {
16133            rate_limit: Some(RateLimit {
16134                rate: 10000,
16135                window: Duration::from_secs(3600),
16136            }),
16137            ..Default::default()
16138        };
16139        let json = serde_json::to_string(&policy).unwrap();
16140        assert!(
16141            json.contains("\"10000/h\""),
16142            "hour-window canonical form must render with `h` suffix (got: {json})"
16143        );
16144        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16145        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
16146    }
16147
16148    #[test]
16149    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
16150        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
16151        // typed accessor's accepted-window set against the codec's
16152        // accepted set explicitly. A future addition to the codec
16153        // (e.g. accepting `:day`/`:week` as authoring units) must be
16154        // accompanied by a parallel addition here, and a regression
16155        // that drops one of the three canonical units from either
16156        // side surfaces as a test failure. The accessor is the
16157        // single source of truth for the canonical-window set —
16158        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
16159        // gate and [`rate_limit_codec::render`]'s canonical arm both
16160        // read through it — this test enshrines that its
16161        // `Duration → Option<RateLimitUnit>` projection matches the
16162        // codec's parse / render arms' accepted-window set exactly.
16163        //
16164        // Predecessor: this pin previously read the module-private
16165        // free helper `is_canonical_rate_limit_window` — a delegate
16166        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
16167        // — but the helper had no production consumers left after the
16168        // validate-gate migration onto [`RateLimit::canonical_unit`]
16169        // and was deleted; the closed-set arm-window bijection now
16170        // lives on exactly one typed dispatch on the substrate
16171        // primitive.
16172        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
16173            RateLimit { rate: 1, window }.canonical_unit()
16174        };
16175        assert!(canonical_unit(Duration::from_secs(1)).is_some());
16176        assert!(canonical_unit(Duration::from_secs(60)).is_some());
16177        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
16178        // Non-canonical windows the accessor rejects.
16179        assert!(canonical_unit(Duration::ZERO).is_none());
16180        assert!(canonical_unit(Duration::from_secs(2)).is_none());
16181        assert!(canonical_unit(Duration::from_secs(30)).is_none());
16182        assert!(canonical_unit(Duration::from_secs(120)).is_none());
16183        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
16184        // Sub-second windows: even `Duration::from_millis(1000)` is
16185        // exactly 1s and accepted; `Duration::from_millis(500)` is
16186        // sub-second and rejected.
16187        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
16188        assert!(canonical_unit(Duration::from_millis(500)).is_none());
16189        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
16190    }
16191
16192    #[test]
16193    fn rate_limit_unit_table_projections_are_mutual_inverses() {
16194        // Bidirection pin against the closed-set typed enum
16195        // [`RateLimitUnit`] arm-table (the canonical
16196        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
16197        // of the rate-limit unit surface reads from). The two
16198        // projection directions [`RateLimitUnit::from_suffix`] /
16199        // [`RateLimitUnit::window`] (str → Duration, exposed as one
16200        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
16201        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
16202        // (Duration → str, exposed as one typed dispatch through
16203        // [`RateLimit::canonical_unit`] composed with
16204        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
16205        // codec's parse arm ([`rate_limit_codec::parse`] via
16206        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
16207        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
16208        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
16209        // via [`RateLimit::canonical_unit`]) all key off. A future
16210        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
16211        // sub-second window) is one variant + one arm per method on the
16212        // closed-set enum; the compiler-enforced exhaustiveness on
16213        // every consumer's `match self` arms picks it up by
16214        // construction. This pin enshrines that both projection
16215        // directions agree on every canonical arm row and neither
16216        // leaks a spurious entry the other doesn't recognize.
16217        //
16218        // Predecessor: this test previously read the two vestigial
16219        // module-private free helpers `rate_limit_window_unit` and
16220        // `rate_limit_window_from_unit` on the `Duration → &str` and
16221        // `&str → Duration` axes; the former was deleted after its
16222        // sole production consumer ([`rate_limit_codec::render`])
16223        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
16224        // the latter is folded here into the substrate primitive
16225        // [`RateLimitUnit::window_from_suffix`] so both projection
16226        // directions live on the closed-set enum's arm-table.
16227        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
16228            let window = super::RateLimitUnit::window_from_suffix(unit)
16229                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
16230            assert_eq!(
16231                window,
16232                Duration::from_secs(secs),
16233                "unit {unit:?} must resolve to {secs}s"
16234            );
16235            let projected_suffix = RateLimit { rate: 1, window }
16236                .canonical_unit()
16237                .map(super::RateLimitUnit::as_suffix);
16238            assert_eq!(
16239                projected_suffix,
16240                Some(unit),
16241                "Duration({secs}s) must render as {unit:?} \
16242                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
16243            );
16244        }
16245        // Non-table units yield None on the `unit → Duration`
16246        // projection — a future `"d"` addition to the table would
16247        // flip this arm; today it pins the current three-row table's
16248        // rejection semantics.
16249        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
16250        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
16251        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
16252        // Non-table Durations yield None on the `Duration → unit`
16253        // projection — pins that the two projections agree on the
16254        // "not in the table" semantic too, so a drift where the
16255        // parse-side accepts a value the render-side can't emit is
16256        // a build error at the two-arm pair, not a silent codec
16257        // round-trip break.
16258        let projected_suffix = |window: Duration| -> Option<&'static str> {
16259            RateLimit { rate: 1, window }
16260                .canonical_unit()
16261                .map(super::RateLimitUnit::as_suffix)
16262        };
16263        assert!(projected_suffix(Duration::from_secs(2)).is_none());
16264        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
16265        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
16266    }
16267
16268    #[test]
16269    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
16270        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
16271        // substrate-primitive `&str → Duration` associated method the
16272        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
16273        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
16274        // to the same [`Duration`] the two-step composition
16275        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
16276        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
16277        // `"MIN"`) must project to [`None`] on both paths. A future
16278        // implementation of `window_from_suffix` that took a shortcut
16279        // through a per-suffix `match` table (bypassing the arm-table's
16280        // `Self::from_suffix` scan and the arm-table's `Self::window`
16281        // dispatch) would silently split the accept-set — the parse
16282        // arm would accept a suffix the enum's arm-table doesn't know,
16283        // or reject a suffix the enum's arm-table does; this pin
16284        // surfaces that drift at caixa-core build time rather than at a
16285        // downstream serde round-trip audit on a live `MeshPolicy`.
16286        //
16287        // Same byte-parity discipline the sibling
16288        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
16289        // pin carries on the peer `Duration → RateLimitUnit` axis via
16290        // [`RateLimit::canonical_unit`], and the peer
16291        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16292        // carries on the bidirectional arm-table axis — extended here
16293        // onto the fifth (and last unlifted) projection axis on the
16294        // closed-set enum's arm-table.
16295        let composition = |suffix: &str| -> Option<Duration> {
16296            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
16297        };
16298        for suffix in ["s", "m", "h"] {
16299            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16300            let via_composition = composition(suffix);
16301            assert_eq!(
16302                via_method, via_composition,
16303                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16304                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
16305                 method must delegate to the arm-table's two typed dispatches, \
16306                 not shortcut through a per-suffix match table"
16307            );
16308            assert!(
16309                via_method.is_some(),
16310                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
16311                 RateLimitUnit::window_from_suffix"
16312            );
16313        }
16314        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
16315            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16316            let via_composition = composition(suffix);
16317            assert_eq!(
16318                via_method, via_composition,
16319                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16320                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
16321                 axis too"
16322            );
16323            assert!(
16324                via_method.is_none(),
16325                "non-arm suffix {suffix:?} must project to None via \
16326                 RateLimitUnit::window_from_suffix — a future extension that \
16327                 accepted this suffix without a corresponding arm on the enum \
16328                 would split the codec's parse-accepted set from the enum's \
16329                 arm-table"
16330            );
16331        }
16332        // And the codec's parse arm now reads through this method: a
16333        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
16334        // the same `Duration` the method returns for its unit, closing
16335        // the two-consumer drift surface (the codec's parse arm and the
16336        // enum's arm-table) with one typed dispatch on the substrate
16337        // primitive.
16338        for suffix in ["s", "m", "h"] {
16339            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
16340            let mp: MeshPolicy = serde_json::from_str(&wire)
16341                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
16342            let parsed = mp.rate_limit().expect("rate_limit payload present");
16343            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
16344                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
16345            assert_eq!(
16346                parsed.window(),
16347                via_method,
16348                "codec parse arm on {wire:?} must resolve the window through \
16349                 RateLimitUnit::window_from_suffix, not a divergent path"
16350            );
16351        }
16352    }
16353
16354    #[test]
16355    fn rate_limit_unit_all_enumerates_every_arm_once() {
16356        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
16357        // enumerate every arm of the closed-set enum exactly once, in
16358        // the canonical shortest-to-longest window order (Second before
16359        // Minute before Hour) — the same order the sibling
16360        // [`crate::supervisor::RestartStrategy`] /
16361        // [`crate::supervisor::RestartPolicy`] /
16362        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
16363        // typed enums carry (the arm declared first is the arm listed
16364        // first). A future variant addition that extends the enum
16365        // without appending to [`RateLimitUnit::ALL`] leaves the
16366        // exhaustive iteration surface silently short one arm — the
16367        // codec's parse arm would then reject the new suffix even
16368        // though the enum knows it. This pin closes the drift.
16369        assert_eq!(
16370            super::RateLimitUnit::ALL,
16371            &[
16372                super::RateLimitUnit::Second,
16373                super::RateLimitUnit::Minute,
16374                super::RateLimitUnit::Hour,
16375            ],
16376            "RateLimitUnit::ALL must enumerate every arm exactly once, \
16377             in canonical shortest-to-longest window order"
16378        );
16379    }
16380
16381    #[test]
16382    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
16383        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
16384        // every arm's [`RateLimitUnit::as_suffix`] output must parse
16385        // back through [`RateLimitUnit::from_suffix`] to the same
16386        // variant. A future arm addition that lands `as_suffix` but
16387        // forgets `from_suffix` (`from_suffix` iterates
16388        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
16389        // is the load-bearing carrier of the round-trip; the sibling
16390        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
16391        // the `ALL` half) trips here at caixa-core build time rather
16392        // than surfacing as a codec round-trip miss (a `render` emit
16393        // that lands a suffix the paired `parse` cannot decode).
16394        for unit in super::RateLimitUnit::ALL {
16395            let suffix = unit.as_suffix();
16396            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
16397                panic!(
16398                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
16399                     RateLimitUnit::as_suffix output — got None for {unit:?}"
16400                )
16401            });
16402            assert_eq!(
16403                parsed, *unit,
16404                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
16405                 must return RateLimitUnit::{unit:?}"
16406            );
16407        }
16408    }
16409
16410    #[test]
16411    fn rate_limit_unit_from_window_and_window_round_trip() {
16412        // Total round-trip pin on the `(from_window, window)` pair:
16413        // every arm's [`RateLimitUnit::window`] output must parse back
16414        // through [`RateLimitUnit::from_window`] to the same variant.
16415        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
16416        // on the peer `Duration` axis — the two round-trip pins
16417        // together enshrine that both projections of the typed
16418        // canonical-unit bijection are total on the arm-set.
16419        for unit in super::RateLimitUnit::ALL {
16420            let window = unit.window();
16421            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
16422                panic!(
16423                    "RateLimitUnit::from_window({window:?}) must accept every \
16424                     RateLimitUnit::window output — got None for {unit:?}"
16425                )
16426            });
16427            assert_eq!(
16428                parsed, *unit,
16429                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16430                 must return RateLimitUnit::{unit:?}"
16431            );
16432        }
16433    }
16434
16435    #[test]
16436    fn rate_limit_unit_projections_are_pairwise_distinct() {
16437        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
16438        // [`RateLimitUnit::window`] outputs must be pairwise distinct
16439        // across every arm — an accidental copy-paste flip that
16440        // reroutes one arm's suffix or window to also match another
16441        // silently collapses two arms onto one, so
16442        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
16443        // (both using `find` on `Self::ALL`) would return whichever
16444        // arm the linear scan lands on first — a match-arm-ordering-
16445        // dependent outcome the closed-set typed-enum shape is meant
16446        // to rule out structurally. Peer of the sibling
16447        // `caixa_kind_wire_consts_are_pairwise_distinct` /
16448        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
16449        // other closed-set typed-enum discriminator axes.
16450        let all = super::RateLimitUnit::ALL;
16451        for (i, a) in all.iter().enumerate() {
16452            for (j, b) in all.iter().enumerate() {
16453                if i != j {
16454                    assert_ne!(
16455                        a.as_suffix(),
16456                        b.as_suffix(),
16457                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
16458                         must be distinct — a collision silently collapses two \
16459                         arms onto one under from_suffix's linear scan"
16460                    );
16461                    assert_ne!(
16462                        a.window(),
16463                        b.window(),
16464                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
16465                         must be distinct — a collision silently collapses two \
16466                         arms onto one under from_window's linear scan"
16467                    );
16468                }
16469            }
16470        }
16471    }
16472
16473    #[test]
16474    fn rate_limit_unit_display_routes_through_as_suffix() {
16475        // Route pin: [`std::fmt::Display`] must byte-equal
16476        // [`RateLimitUnit::as_suffix`] on every arm — the single
16477        // source of truth for the canonical suffix. A future
16478        // reimplementation that hand-rolls the arms instead of
16479        // delegating to [`RateLimitUnit::as_suffix`] would silently
16480        // desynchronize `format!("{u}")` from the codec's parse arm
16481        // (which uses `as_suffix` to compare suffixes). Peer of the
16482        // sibling `caixa_kind_display_routes_through_as_str_helper` /
16483        // `placement_strategy_display_routes_through_as_str_helper`
16484        // pins on the peer closed-set typed-enum Display axes.
16485        for unit in super::RateLimitUnit::ALL {
16486            assert_eq!(
16487                unit.to_string(),
16488                unit.as_suffix(),
16489                "RateLimitUnit::{unit:?} Display must route through \
16490                 as_suffix (single source of truth: the canonical suffix \
16491                 the codec parses and renders)"
16492            );
16493        }
16494    }
16495
16496    #[test]
16497    fn rate_limit_unit_from_window_rejects_non_canonical() {
16498        // Rejection pin on the parser's accept-set: any Duration
16499        // outside the three-arm [`RateLimitUnit::window`] output set
16500        // (sub-second residue, or a second-magnitude outside `{1, 60,
16501        // 3600}`) must return `None`. A future accidental widening of
16502        // the accept-set (rounding down sub-second residue to the
16503        // nearest arm, admitting `Duration::from_secs(30)` as a
16504        // half-minute unit) would silently drift the parser's accept-
16505        // set from the emitter's — a validated slot with a
16506        // non-canonical window would then round-trip through the
16507        // codec to a canonical form the author never wrote.
16508        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
16509        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
16510        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
16511        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
16512        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
16513        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
16514        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
16515    }
16516
16517    #[test]
16518    fn rate_limit_unit_from_suffix_rejects_unknown() {
16519        // Rejection pin on the suffix parser's accept-set: any string
16520        // outside the three-arm [`RateLimitUnit::as_suffix`] output
16521        // set must return `None`. Peer of the sibling
16522        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
16523        // the [`crate::CaixaKind`] `from_wire` accept-set.
16524        for bad in [
16525            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
16526            " s",
16527        ] {
16528            assert!(
16529                super::RateLimitUnit::from_suffix(bad).is_none(),
16530                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
16531                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
16532                 outputs"
16533            );
16534        }
16535    }
16536
16537    #[test]
16538    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
16539        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
16540        // every canonical `:window` magnitude the validate gate
16541        // accepts must map to the paired [`RateLimitUnit`] arm through
16542        // this accessor. A future validate-gate rebrand that widened
16543        // the accepted-window set without extending [`RateLimitUnit`]
16544        // would silently split the accessor's `Some`-return set from
16545        // the validate gate's accept-set — a slot that satisfies
16546        // validate would land at the accessor with `None`, so a
16547        // consumer past validate that pattern-matches on the returned
16548        // `Some` would silently miss the newly-accepted magnitude.
16549        for (window_secs, expected) in [
16550            (1u64, super::RateLimitUnit::Second),
16551            (60, super::RateLimitUnit::Minute),
16552            (3600, super::RateLimitUnit::Hour),
16553        ] {
16554            let rl = RateLimit {
16555                rate: 100,
16556                window: Duration::from_secs(window_secs),
16557            };
16558            assert_eq!(
16559                rl.canonical_unit(),
16560                Some(expected),
16561                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
16562                 must return Some({expected:?})"
16563            );
16564        }
16565        // Non-canonical windows the validate gate rejects also return
16566        // None here — the accessor is the typed-enum projection of
16567        // the sibling `is_canonical_rate_limit_window` predicate.
16568        let bad = RateLimit {
16569            rate: 100,
16570            window: Duration::from_secs(30),
16571        };
16572        assert!(
16573            bad.canonical_unit().is_none(),
16574            "RateLimit with a non-canonical window must return None from \
16575             canonical_unit — the validate gate rejects the same set"
16576        );
16577    }
16578
16579    #[test]
16580    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
16581        // Fail-before-pass-after byte-parity pin: for every canonical
16582        // window the [`rate_limit_codec::render`] arm's emitted string
16583        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
16584        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
16585        // the vestigial free helper [`rate_limit_window_unit`] (a
16586        // `find_map`-walked `Duration → &'static str` delegate) onto the
16587        // substrate primitive [`RateLimit::canonical_unit`] typed method
16588        // (a closed-set `match self.window` arm on
16589        // [`RateLimitUnit::from_window`], projected through
16590        // [`RateLimitUnit::as_suffix`] via the enum's
16591        // [`std::fmt::Display`] impl). A future re-routing of the render
16592        // arm through a differently-computed unit projection would break
16593        // this pin at build time rather than as a silent per-consumer
16594        // codec round-trip drift far from the substrate primitive edit.
16595        //
16596        // Sibling to the peer
16597        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16598        // on the free-helper axis: that pin locks the two projections
16599        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
16600        // on the closed-set arm table; this pin locks the codec's render
16601        // arm reads through the typed accessor rather than the free
16602        // helper. Two production consumers of the canonical-unit axis
16603        // now key off one typed dispatch on the substrate primitive.
16604        for (window_secs, unit) in [
16605            (1u64, super::RateLimitUnit::Second),
16606            (60, super::RateLimitUnit::Minute),
16607            (3600, super::RateLimitUnit::Hour),
16608        ] {
16609            let rl = RateLimit {
16610                rate: 42,
16611                window: Duration::from_secs(window_secs),
16612            };
16613            let policy = MeshPolicy {
16614                rate_limit: Some(rl),
16615                ..Default::default()
16616            };
16617            let json = serde_json::to_string(&policy).unwrap();
16618            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
16619            assert!(
16620                json.contains(&expected),
16621                "rate_limit_codec::render must emit {expected} (via \
16622                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
16623                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
16624            );
16625            // And the accessor route resolves to the same typed unit
16626            // the render arm's Display formatting is asked to produce —
16627            // so a future edit that split the two paths (one through
16628            // the accessor, one through a re-introduced free helper)
16629            // trips this pin.
16630            assert_eq!(
16631                rl.canonical_unit(),
16632                Some(unit),
16633                "RateLimit::canonical_unit must return Some({unit:?}) for a \
16634                 {window_secs}s window; the codec render arm reads the same \
16635                 typed unit through this accessor"
16636            );
16637        }
16638    }
16639
16640    #[test]
16641    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
16642        // Fail-before-pass-after byte-parity pin on the validate gate's
16643        // canonical-window shape probe: every non-canonical `:window`
16644        // the free-helper predicate [`is_canonical_rate_limit_window`]
16645        // rejects is also rejected by the substrate primitive
16646        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
16647        // gate now reads through, and vice versa on the accepted set
16648        // (the three canonical windows). Locks the migration from the
16649        // free helper onto the substrate primitive: a future re-routing
16650        // of one of the two paths through a differently-computed unit
16651        // projection would silently split the codec's accepted set from
16652        // the validate gate's accepted set — a two-consumer drift the
16653        // codec-round-trip pin
16654        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
16655        // above closes on the render arm and this pin closes on the
16656        // validate arm.
16657        for canonical_window_secs in [1u64, 60, 3600] {
16658            let mut s = three_member_spec();
16659            let rl = RateLimit {
16660                rate: 100,
16661                window: Duration::from_secs(canonical_window_secs),
16662            };
16663            s.politicas.rate_limit = Some(rl);
16664            assert!(
16665                s.validate().is_ok(),
16666                "canonical {canonical_window_secs}s window must pass \
16667                 validate_politicas — the validate gate now reads \
16668                 RateLimit::canonical_unit().is_none() and the accessor \
16669                 returns Some on every canonical arm"
16670            );
16671            assert!(
16672                rl.canonical_unit().is_some(),
16673                "canonical {canonical_window_secs}s window must resolve to \
16674                 Some on RateLimit::canonical_unit — the validate gate reads \
16675                 this accessor directly"
16676            );
16677        }
16678        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
16679            let mut s = three_member_spec();
16680            let rl = RateLimit {
16681                rate: 100,
16682                window: Duration::from_secs(non_canonical_window_secs),
16683            };
16684            s.politicas.rate_limit = Some(rl);
16685            assert_eq!(
16686                s.validate().unwrap_err(),
16687                AplicacaoError::PolicyRateLimitWindowNotCanonical {
16688                    window: rl.window(),
16689                },
16690                "non-canonical {non_canonical_window_secs}s window must be \
16691                 rejected by validate_politicas — the validate gate now \
16692                 keys off RateLimit::canonical_unit().is_none()"
16693            );
16694            assert!(
16695                rl.canonical_unit().is_none(),
16696                "non-canonical {non_canonical_window_secs}s window must \
16697                 resolve to None on RateLimit::canonical_unit — the two \
16698                 paths (the free helper the validate gate previously read \
16699                 and the substrate primitive the validate gate now reads) \
16700                 must agree on the same rejected set"
16701            );
16702        }
16703        // And the substrate-primitive [`RateLimit::canonical_unit`]
16704        // accessor's accepted-window set matches the codec's parse arm's
16705        // accepted-suffix set on every canonical / non-canonical shape,
16706        // so a future silent drift between the codec's accepted set and
16707        // the validate gate's accepted set is a build error at test time
16708        // (both consumers key off the same closed-set enum's `match self`
16709        // arms). The predecessor free helper `is_canonical_rate_limit_window`
16710        // — a delegate that composed [`RateLimitUnit::from_window`] with
16711        // `.is_some()` — was deleted after this migration; the
16712        // canonical-window set now lives on exactly one typed dispatch
16713        // on the substrate primitive.
16714        for (secs, expected) in [
16715            (1u64, true),
16716            (60, true),
16717            (3600, true),
16718            (2, false),
16719            (30, false),
16720            (86_400, false),
16721        ] {
16722            let window = Duration::from_secs(secs);
16723            let rl = RateLimit { rate: 1, window };
16724            assert_eq!(
16725                rl.canonical_unit().is_some(),
16726                expected,
16727                "RateLimit::canonical_unit().is_some() must agree with the \
16728                 codec-accepted canonical-window set on {secs}s"
16729            );
16730            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
16731                1 => "s",
16732                60 => "m",
16733                3600 => "h",
16734                _ => return,
16735            })
16736            .is_some_and(|d| d == window);
16737            if expected {
16738                assert!(
16739                    suffix_from_axis,
16740                    "the codec's `&str → Duration` axis \
16741                     ({secs}s) must round-trip to the same Duration the \
16742                     substrate primitive's accessor returns Some on"
16743                );
16744            }
16745        }
16746    }
16747
16748    #[test]
16749    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
16750        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16751        // derive: for each of the three variants, exactly one of the
16752        // generated `is_second` / `is_minute` / `is_hour` predicates
16753        // returns `true` and the other two return `false`. Peer of
16754        // the sibling
16755        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
16756        // sibling `IsVariant`-derived closed-set typed-enum pins.
16757        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
16758            (super::RateLimitUnit::Second, [true, false, false]),
16759            (super::RateLimitUnit::Minute, [false, true, false]),
16760            (super::RateLimitUnit::Hour, [false, false, true]),
16761        ];
16762        for (variant, expected) in rows {
16763            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
16764            assert_eq!(
16765                observed, expected,
16766                "RateLimitUnit::{variant:?} is_* predicates must partition \
16767                 the arm set (second, minute, hour); got {observed:?}"
16768            );
16769        }
16770    }
16771
16772    #[test]
16773    fn rejects_policy_timeout_sub_millisecond() {
16774        // A purely sub-millisecond `Duration` (`from_micros(500)` =
16775        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
16776        // arm passes — but `as_millis() == 0`, so the shared codec's
16777        // `render` arm returns the literal `"0s"`, which the
16778        // codec's `parse` arm then deserializes as `Duration::ZERO`
16779        // and the `PolicyTimeoutZero` zero-floor gate would reject
16780        // on re-validate. Pin the rejection at the typed slot's
16781        // canonical-floor gate so the round-trip break surfaces at
16782        // validate time, naming the offending `Duration`, rather
16783        // than at the next serialize → deserialize round-trip far
16784        // from the source `caixa.lisp`.
16785        let mut s = three_member_spec();
16786        let timeout = Duration::from_micros(500);
16787        s.politicas.timeout = Some(timeout);
16788        assert_eq!(
16789            s.validate().unwrap_err(),
16790            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
16791        );
16792    }
16793
16794    #[test]
16795    fn rejects_policy_timeout_non_integer_millisecond() {
16796        // A `Duration` with non-integer-millisecond residue
16797        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
16798        // through the shared codec's `render` arm as `"1ms"` (the
16799        // `as_millis()` floor truncates), which the codec's `parse`
16800        // arm then deserializes as `Duration::from_millis(1)` =
16801        // 1_000_000 ns — silently *different* from the original.
16802        // Pin the rejection so this round-trip break surfaces at
16803        // validate time, where the offending `Duration` is named,
16804        // rather than as a silent value-laundered round-trip on the
16805        // next codec round-trip.
16806        let mut s = three_member_spec();
16807        let timeout = Duration::from_micros(1500);
16808        s.politicas.timeout = Some(timeout);
16809        assert_eq!(
16810            s.validate().unwrap_err(),
16811            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
16812        );
16813    }
16814
16815    #[test]
16816    fn accepts_policy_timeout_integer_millisecond_forms() {
16817        // The codec's accepted set — integer multiples of 1ms — is
16818        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
16819        // `1h` all pass the canonical gate. Pin the canonical-forms
16820        // sweep so a future tightening of the codec's grammar (e.g.
16821        // dropping `:ms`) surfaces here as a test failure rather
16822        // than a silent contract narrowing on the typed slot.
16823        for timeout in [
16824            Duration::from_millis(1),
16825            Duration::from_millis(500),
16826            Duration::from_millis(1500),
16827            Duration::from_secs(30),
16828            Duration::from_secs(120),
16829            Duration::from_secs(3600),
16830        ] {
16831            let mut s = three_member_spec();
16832            s.politicas.timeout = Some(timeout);
16833            s.validate()
16834                .expect("integer-millisecond :timeout must validate");
16835        }
16836    }
16837
16838    #[test]
16839    fn policy_timeout_zero_takes_precedence_over_canonical() {
16840        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
16841        // pass the canonical-millisecond gate; the more self-locating
16842        // `PolicyTimeoutZero` arm (which names the omit-axis
16843        // remediation directly) must fire first. Pin the ordering so
16844        // a future refactor that reorders the arms surfaces here as a
16845        // test failure rather than a silent diagnostic regression.
16846        let mut s = three_member_spec();
16847        s.politicas.timeout = Some(Duration::ZERO);
16848        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16849    }
16850
16851    #[test]
16852    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
16853        // The diagnostic envelope carries the offending `Duration`
16854        // verbatim so the author can grep their `caixa.lisp` for
16855        // `:timeout "<value>"` and fix it in one edit. Same
16856        // diagnostic shape every other typed-slot canonical-form
16857        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
16858        // peer `:rate-limit :window` axis.
16859        let mut s = three_member_spec();
16860        let timeout = Duration::from_nanos(1_000_001);
16861        s.politicas.timeout = Some(timeout);
16862        match s.validate().unwrap_err() {
16863            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
16864                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
16865            }
16866            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
16867        }
16868    }
16869
16870    #[test]
16871    fn rejects_policy_timeout_above_cap() {
16872        // The fail-before-pass-after pin: 3601s = 1h + 1s is
16873        // structurally one canonical-tick past the
16874        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
16875        // integer-millisecond magnitude the canonical-form arm above
16876        // accepts cleanly, that the codec round-trips losslessly as
16877        // `"3601s"`, and that silently passed validate on every
16878        // pre-gate codebase because the typed slot's only checks were
16879        // the zero-floor and canonical-form arms. The mesh-level
16880        // deadline degenerates only at the runtime substrate (Envoy
16881        // / Cilium L7 timeout overlay) far from the source
16882        // `caixa.lisp` with no field naming the offending policy.
16883        let mut s = three_member_spec();
16884        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
16885        s.politicas.timeout = Some(timeout);
16886        assert_eq!(
16887            s.validate().unwrap_err(),
16888            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
16889        );
16890    }
16891
16892    #[test]
16893    fn rejects_policy_timeout_one_millisecond_above_cap() {
16894        // Boundary case: exactly 1ms past the cap (the granularity
16895        // the canonical-form gate enforces). Catches a future
16896        // "strictly less than" half-measure and pins the diagnostic
16897        // to name the offending `Duration` verbatim. Peer of
16898        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
16899        // boundary pin on the sibling `:limits :memory` top edge.
16900        let mut s = three_member_spec();
16901        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
16902        s.politicas.timeout = Some(timeout);
16903        assert_eq!(
16904            s.validate().unwrap_err(),
16905            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
16906        );
16907    }
16908
16909    #[test]
16910    fn rejects_policy_timeout_far_above_cap() {
16911        // The "obvious authoring footgun" case: a `(:timeout "24h")`
16912        // or `(:timeout "86400s")` — values the canonical-form arm
16913        // accepts as integer-millisecond magnitudes, the codec
16914        // round-trips losslessly through serde, but the mesh-level
16915        // policy cannot honor (a 24-hour synchronous-`:contratos`
16916        // deadline is operationally indistinguishable from
16917        // omit-the-axis). Until this gate landed validate accepted
16918        // it. Pin both common above-cap values (24h, 7d) so a future
16919        // relaxation that drops the upper bound surfaces here.
16920        for timeout in [
16921            Duration::from_secs(86_400),    // 24h
16922            Duration::from_secs(604_800),   // 7d
16923            Duration::from_secs(1_000_000), // ~11.5 days
16924        ] {
16925            let mut s = three_member_spec();
16926            s.politicas.timeout = Some(timeout);
16927            assert_eq!(
16928                s.validate().unwrap_err(),
16929                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
16930            );
16931        }
16932    }
16933
16934    #[test]
16935    fn accepts_policy_timeout_at_cap() {
16936        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
16937        // must validate. The cap is inclusive on the top edge,
16938        // matching the [`POLICY_RETRIES_MAX`] /
16939        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
16940        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
16941        // sibling capped axes. Pin the boundary explicitly so a
16942        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
16943        // instead of `>`) surfaces here as a test failure rather
16944        // than a silent contract narrowing.
16945        let mut s = three_member_spec();
16946        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
16947        s.validate()
16948            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
16949    }
16950
16951    #[test]
16952    fn accepts_policy_timeout_typical_values() {
16953        // The documented production-playbook band positive-control
16954        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
16955        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
16956        // plus a sweep through the long-running-workflow band
16957        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
16958        // validated set explicitly so a future tightening of the
16959        // ceiling surfaces here as a deliberate test edit, not a
16960        // silent contract narrowing.
16961        for timeout in [
16962            Duration::from_millis(1),
16963            Duration::from_millis(500),
16964            Duration::from_secs(1),
16965            Duration::from_secs(10),
16966            Duration::from_secs(15), // Envoy default
16967            Duration::from_secs(30),
16968            Duration::from_secs(60), // AWS App Mesh typical
16969            Duration::from_secs(300),
16970            Duration::from_secs(900),
16971            Duration::from_secs(1800),
16972            Duration::from_secs(3600), // exactly 1h, the cap
16973        ] {
16974            let mut s = three_member_spec();
16975            s.politicas.timeout = Some(timeout);
16976            s.validate()
16977                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
16978        }
16979    }
16980
16981    #[test]
16982    fn policy_timeout_zero_takes_precedence_over_cap() {
16983        // The cross-arm ordering pin: `Duration::ZERO` is
16984        // structurally outside both `>= 1ms` (zero-floor) and
16985        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
16986        // diagnostic is the more self-locating one (it directly
16987        // names the omit-axis remediation), so the validate gate
16988        // must fire on zero first. Same shape every other
16989        // zero-then-shape ordering on this surface uses
16990        // ([`AplicacaoError::PolicyRetriesZero`] then
16991        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16992        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16993        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16994        let mut s = three_member_spec();
16995        s.politicas.timeout = Some(Duration::ZERO);
16996        assert_eq!(
16997            s.validate().unwrap_err(),
16998            AplicacaoError::PolicyTimeoutZero,
16999            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17000        );
17001    }
17002
17003    #[test]
17004    fn policy_timeout_canonical_takes_precedence_over_cap() {
17005        // The cross-arm ordering pin: a `Duration` that is *both*
17006        // sub-millisecond (non-canonical-form) and structurally
17007        // above the cap surfaces the canonical-form diagnostic
17008        // first, because the round-trip-shape break is the more
17009        // fundamental issue (the value can't even round-trip
17010        // through the codec, so the cap diagnostic naming
17011        // `1ms..=1h` would be misleading — there's no integer-ms
17012        // form of the offending value). Pin the order so a future
17013        // refactor that reorders the arms surfaces here as a test
17014        // failure rather than a silent diagnostic regression.
17015        let mut s = three_member_spec();
17016        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
17017        // *and* total magnitude above the 1h cap.
17018        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
17019        s.politicas.timeout = Some(timeout);
17020        assert_eq!(
17021            s.validate().unwrap_err(),
17022            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
17023            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17024        );
17025    }
17026
17027    #[test]
17028    fn policy_timeout_cap_diagnostic_carries_offending_value() {
17029        // The diagnostic-shape pin: the offending `Duration` is
17030        // carried verbatim into the
17031        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
17032        // surfaced error message names the value the author wrote
17033        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
17034        // exceeds the mesh-policy ceiling …"`), not just the cap.
17035        // Same self-locating diagnostic shape every other typed-cap
17036        // arm on this surface carries
17037        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17038        // offending retry count verbatim).
17039        let mut s = three_member_spec();
17040        let timeout = Duration::from_secs(7200); // 2h
17041        s.politicas.timeout = Some(timeout);
17042        let err = s.validate().unwrap_err();
17043        assert!(
17044            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
17045            "got {err:?}"
17046        );
17047        let msg = err.to_string();
17048        assert!(
17049            msg.contains("7200"),
17050            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
17051        );
17052    }
17053
17054    #[test]
17055    fn policy_timeout_cap_pins_canonical_value() {
17056        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
17057        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
17058        // the shared duration codec emits as a clean canonical
17059        // string (`"<n>h"`). Pinning the literal value here surfaces
17060        // a future drift (a relaxation to 24h, a tightening to 5m)
17061        // as a deliberate test edit, not a silent contract
17062        // narrowing. Same shape every other typed-cap value pin on
17063        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
17064        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
17065        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
17066    }
17067
17068    #[test]
17069    fn policy_timeout_cap_value_round_trips_through_codec() {
17070        // The codec round-trip property the cap arm preserves: the
17071        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
17072        // the shared duration codec — every value at the cap renders
17073        // to a clean canonical string (`"1h"`) and parses back to
17074        // the same `Duration`. Pin this so a future drift between
17075        // the cap constant and the codec's largest emitted unit
17076        // surfaces here. Same shape every other typed boundary pin
17077        // on this surface uses
17078        // (`wasm32_memory_cap_matches_parsed_4_gib`).
17079        let policy = MeshPolicy {
17080            timeout: Some(POLICY_TIMEOUT_MAX),
17081            ..Default::default()
17082        };
17083        let json = serde_json::to_string(&policy).unwrap();
17084        // The codec emits `"1h"` for the canonical 1-hour magnitude.
17085        assert!(
17086            json.contains("\"1h\""),
17087            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
17088        );
17089        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17090        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
17091    }
17092
17093    #[test]
17094    fn rejects_circuit_breaker_window_sub_millisecond() {
17095        // Peer of the `:timeout` sub-millisecond arm on the second
17096        // typed-`Duration` `:politicas` axis: a purely sub-ms
17097        // `Duration` (`from_micros(500)`) renders through the shared
17098        // codec as `"0s"`, which the codec parses back to
17099        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
17100        // zero-floor gate then rejects on re-validate.
17101        let mut s = three_member_spec();
17102        let window = Duration::from_micros(500);
17103        s.politicas.circuit_breaker = Some(CircuitBreaker {
17104            max_failures: 5,
17105            window,
17106        });
17107        assert_eq!(
17108            s.validate().unwrap_err(),
17109            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17110        );
17111    }
17112
17113    #[test]
17114    fn rejects_circuit_breaker_window_non_integer_millisecond() {
17115        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
17116        // with non-integer-millisecond residue renders through the
17117        // shared codec as the truncated `"<n>ms"` form, parsing back
17118        // to a *different* `Duration` on the next round-trip.
17119        let mut s = three_member_spec();
17120        let window = Duration::from_micros(1500);
17121        s.politicas.circuit_breaker = Some(CircuitBreaker {
17122            max_failures: 5,
17123            window,
17124        });
17125        assert_eq!(
17126            s.validate().unwrap_err(),
17127            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17128        );
17129    }
17130
17131    #[test]
17132    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
17133        // The canonical-forms sweep on the breaker axis: every
17134        // integer-ms multiple the codec round-trips losslessly
17135        // passes the canonical gate.
17136        for window in [
17137            Duration::from_millis(1),
17138            Duration::from_millis(500),
17139            Duration::from_millis(1500),
17140            Duration::from_secs(30),
17141            Duration::from_secs(60),
17142            Duration::from_secs(3600),
17143        ] {
17144            let mut s = three_member_spec();
17145            s.politicas.circuit_breaker = Some(CircuitBreaker {
17146                max_failures: 5,
17147                window,
17148            });
17149            s.validate()
17150                .expect("integer-millisecond :circuit-breaker :window must validate");
17151        }
17152    }
17153
17154    #[test]
17155    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
17156        // `Duration::ZERO` would pass the canonical-ms gate (the
17157        // sub-ns residue is zero) but must surface the narrower
17158        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
17159        // remediation.
17160        let mut s = three_member_spec();
17161        s.politicas.circuit_breaker = Some(CircuitBreaker {
17162            max_failures: 5,
17163            window: Duration::ZERO,
17164        });
17165        assert_eq!(
17166            s.validate().unwrap_err(),
17167            AplicacaoError::PolicyBreakerZeroWindow
17168        );
17169    }
17170
17171    #[test]
17172    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
17173        // Both axes invalid: max_failures == 0 *and* window is
17174        // sub-ms. The validate gate must fire on max_failures first
17175        // (matching the existing ordering pin
17176        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
17177        // the existing diagnostic continues to lead with the simpler
17178        // "zero threshold" framing.
17179        let mut s = three_member_spec();
17180        s.politicas.circuit_breaker = Some(CircuitBreaker {
17181            max_failures: 0,
17182            window: Duration::from_micros(500),
17183        });
17184        assert_eq!(
17185            s.validate().unwrap_err(),
17186            AplicacaoError::PolicyBreakerZeroFailures
17187        );
17188    }
17189
17190    #[test]
17191    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
17192        let mut s = three_member_spec();
17193        let window = Duration::from_nanos(60_000_000_001);
17194        s.politicas.circuit_breaker = Some(CircuitBreaker {
17195            max_failures: 5,
17196            window,
17197        });
17198        match s.validate().unwrap_err() {
17199            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
17200                assert_eq!(w, window, "diagnostic must carry the offending Duration");
17201            }
17202            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
17203        }
17204    }
17205
17206    #[test]
17207    fn rejects_circuit_breaker_window_above_cap() {
17208        // The fail-before-pass-after pin: 3601s = 1h + 1s is
17209        // structurally one canonical-tick past the
17210        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
17211        // integer-millisecond magnitude the canonical-form arm above
17212        // accepts cleanly, that the codec round-trips losslessly as
17213        // `"3601s"`, and that silently passed validate on every
17214        // pre-gate codebase because the typed slot's only checks were
17215        // the zero-floor and canonical-form arms. The
17216        // rolling-window-to-lifetime-counter degeneration surfaces
17217        // only at the runtime substrate (Envoy's outlier_detection
17218        // interval, the future CiliumClusterwideEnvoyConfig overlay)
17219        // far from the source `caixa.lisp` with no field naming the
17220        // offending policy.
17221        let mut s = three_member_spec();
17222        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17223        s.politicas.circuit_breaker = Some(CircuitBreaker {
17224            max_failures: 5,
17225            window,
17226        });
17227        assert_eq!(
17228            s.validate().unwrap_err(),
17229            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17230        );
17231    }
17232
17233    #[test]
17234    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
17235        // Boundary case: exactly 1ms past the cap (the granularity the
17236        // canonical-form gate enforces). Catches a future "strictly
17237        // less than" half-measure and pins the diagnostic to name the
17238        // offending `Duration` verbatim. Peer of
17239        // `rejects_policy_timeout_one_millisecond_above_cap` on the
17240        // sibling duration-typed `:politicas :timeout` top edge.
17241        let mut s = three_member_spec();
17242        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
17243        s.politicas.circuit_breaker = Some(CircuitBreaker {
17244            max_failures: 5,
17245            window,
17246        });
17247        assert_eq!(
17248            s.validate().unwrap_err(),
17249            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17250        );
17251    }
17252
17253    #[test]
17254    fn rejects_circuit_breaker_window_far_above_cap() {
17255        // The "obvious authoring footgun" case: a `(:window "24h")` or
17256        // `(:window "86400s")` — values the canonical-form arm
17257        // accepts as integer-millisecond magnitudes, the codec
17258        // round-trips losslessly through serde, but the
17259        // rolling-window breaker contract cannot honor (a 24-hour
17260        // rolling failure window is operationally a lifetime counter).
17261        // Until this gate landed validate accepted it. Pin both common
17262        // above-cap values (24h, 7d) so a future relaxation that
17263        // drops the upper bound surfaces here.
17264        for window in [
17265            Duration::from_secs(86_400),    // 24h
17266            Duration::from_secs(604_800),   // 7d
17267            Duration::from_secs(1_000_000), // ~11.5 days
17268        ] {
17269            let mut s = three_member_spec();
17270            s.politicas.circuit_breaker = Some(CircuitBreaker {
17271                max_failures: 5,
17272                window,
17273            });
17274            assert_eq!(
17275                s.validate().unwrap_err(),
17276                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17277            );
17278        }
17279    }
17280
17281    #[test]
17282    fn accepts_circuit_breaker_window_at_cap() {
17283        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
17284        // (1h) — must validate. The cap is inclusive on the top edge,
17285        // matching the [`POLICY_TIMEOUT_MAX`] /
17286        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
17287        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17288        // sibling capped axes. Pin the boundary explicitly so a
17289        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
17290        // instead of `>`) surfaces here as a test failure rather than
17291        // a silent contract narrowing.
17292        let mut s = three_member_spec();
17293        s.politicas.circuit_breaker = Some(CircuitBreaker {
17294            max_failures: 5,
17295            window: POLICY_BREAKER_WINDOW_MAX,
17296        });
17297        s.validate()
17298            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
17299    }
17300
17301    #[test]
17302    fn accepts_circuit_breaker_window_typical_values() {
17303        // The documented production-playbook band positive-control
17304        // sweep — every value Hystrix / resilience4j / Istio / Envoy
17305        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
17306        // through the long-tail failure-detection band (15m, 30m, 1h)
17307        // the cap accepts. Pin the inclusive validated set explicitly
17308        // so a future tightening of the ceiling surfaces here as a
17309        // deliberate test edit, not a silent contract narrowing.
17310        for window in [
17311            Duration::from_millis(1),
17312            Duration::from_millis(500),
17313            Duration::from_secs(1),
17314            Duration::from_secs(10), // Hystrix / Istio / Envoy default
17315            Duration::from_secs(30),
17316            Duration::from_secs(60),  // resilience4j typical
17317            Duration::from_secs(300), // AWS App Mesh typical
17318            Duration::from_secs(900),
17319            Duration::from_secs(1800),
17320            Duration::from_secs(3600), // exactly 1h, the cap
17321        ] {
17322            let mut s = three_member_spec();
17323            s.politicas.circuit_breaker = Some(CircuitBreaker {
17324                max_failures: 5,
17325                window,
17326            });
17327            s.validate()
17328                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
17329        }
17330    }
17331
17332    #[test]
17333    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
17334        // The cross-arm ordering pin: `Duration::ZERO` is structurally
17335        // outside both `>= 1ms` (zero-floor) and
17336        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
17337        // diagnostic is the more self-locating one (it directly names
17338        // the omit-axis remediation), so the validate gate must fire
17339        // on zero first. Same shape every other zero-then-cap
17340        // ordering on this surface uses
17341        // ([`AplicacaoError::PolicyTimeoutZero`] then
17342        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
17343        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17344        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17345        let mut s = three_member_spec();
17346        s.politicas.circuit_breaker = Some(CircuitBreaker {
17347            max_failures: 5,
17348            window: Duration::ZERO,
17349        });
17350        assert_eq!(
17351            s.validate().unwrap_err(),
17352            AplicacaoError::PolicyBreakerZeroWindow,
17353            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17354        );
17355    }
17356
17357    #[test]
17358    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
17359        // The cross-arm ordering pin: a `Duration` that is *both*
17360        // sub-millisecond (non-canonical-form) and structurally above
17361        // the cap surfaces the canonical-form diagnostic first,
17362        // because the round-trip-shape break is the more fundamental
17363        // issue (the value can't even round-trip through the codec, so
17364        // the cap diagnostic naming `1ms..=1h` would be misleading —
17365        // there's no integer-ms form of the offending value). Pin the
17366        // order so a future refactor that reorders the arms surfaces
17367        // here as a test failure rather than a silent diagnostic
17368        // regression. Peer of
17369        // `policy_timeout_canonical_takes_precedence_over_cap` on the
17370        // sibling duration-typed `:politicas :timeout` axis.
17371        let mut s = three_member_spec();
17372        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
17373        s.politicas.circuit_breaker = Some(CircuitBreaker {
17374            max_failures: 5,
17375            window,
17376        });
17377        assert_eq!(
17378            s.validate().unwrap_err(),
17379            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
17380            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17381        );
17382    }
17383
17384    #[test]
17385    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
17386        // The cross-arm ordering pin between the two breaker axes: a
17387        // `CircuitBreaker` whose *both* `max_failures` is above its
17388        // cap *and* `window` is above its cap surfaces the
17389        // max-failures cap diagnostic first, because the validate
17390        // gate visits the failures arm before the window arm. Pin the
17391        // order so a future refactor that reorders the breaker arms
17392        // surfaces here.
17393        let mut s = three_member_spec();
17394        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17395        s.politicas.circuit_breaker = Some(CircuitBreaker {
17396            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17397            window,
17398        });
17399        assert_eq!(
17400            s.validate().unwrap_err(),
17401            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17402                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
17403            },
17404            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
17405        );
17406    }
17407
17408    #[test]
17409    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
17410        // The diagnostic-shape pin: the offending `Duration` is
17411        // carried verbatim into the
17412        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
17413        // the surfaced error message names the value the author wrote
17414        // (`":politicas :circuit-breaker :window (Duration { secs:
17415        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
17416        // just the cap. Same self-locating diagnostic shape every
17417        // other typed-cap arm on this surface carries
17418        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
17419        // offending `Duration` verbatim).
17420        let mut s = three_member_spec();
17421        let window = Duration::from_secs(7200); // 2h
17422        s.politicas.circuit_breaker = Some(CircuitBreaker {
17423            max_failures: 5,
17424            window,
17425        });
17426        let err = s.validate().unwrap_err();
17427        assert!(
17428            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
17429            "got {err:?}"
17430        );
17431        let msg = err.to_string();
17432        assert!(
17433            msg.contains("7200"),
17434            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
17435        );
17436    }
17437
17438    #[test]
17439    fn circuit_breaker_window_cap_pins_canonical_value() {
17440        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
17441        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
17442        // shared duration codec emits as a clean canonical string
17443        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
17444        // the sibling duration-typed `:politicas :timeout` axis (the
17445        // two duration-typed `:politicas` axes share a uniform top
17446        // edge). Pinning the literal value here surfaces a future
17447        // drift (a relaxation to 24h, a tightening to 5m) as a
17448        // deliberate test edit, not a silent contract narrowing. Same
17449        // shape every other typed-cap value pin on this surface uses
17450        // (`policy_timeout_cap_pins_canonical_value`).
17451        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
17452        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
17453        assert_eq!(
17454            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
17455            "the two duration-typed `:politicas` caps share the same top edge"
17456        );
17457    }
17458
17459    #[test]
17460    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
17461        // The codec round-trip property the cap arm preserves: the
17462        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
17463        // through the shared duration codec — every value at the cap
17464        // renders to a clean canonical string (`"1h"`) and parses back
17465        // to the same `Duration`. Pin this so a future drift between
17466        // the cap constant and the codec's largest emitted unit
17467        // surfaces here. Same shape every other typed boundary pin on
17468        // this surface uses
17469        // (`policy_timeout_cap_value_round_trips_through_codec`).
17470        let policy = MeshPolicy {
17471            circuit_breaker: Some(CircuitBreaker {
17472                max_failures: 5,
17473                window: POLICY_BREAKER_WINDOW_MAX,
17474            }),
17475            ..Default::default()
17476        };
17477        let json = serde_json::to_string(&policy).unwrap();
17478        // The codec emits `"1h"` for the canonical 1-hour magnitude.
17479        assert!(
17480            json.contains("\"1h\""),
17481            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
17482        );
17483        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17484        assert_eq!(
17485            back.circuit_breaker.unwrap().window,
17486            POLICY_BREAKER_WINDOW_MAX
17487        );
17488    }
17489
17490    #[test]
17491    fn is_integer_millisecond_duration_predicate_tracks_codec() {
17492        // Pin the predicate's accepted set against the codec's
17493        // accepted set explicitly. The codec parses
17494        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
17495        // accepted value is an integer-millisecond multiple — so the
17496        // predicate must accept exactly that set. Same shape every
17497        // other predicate-on-the-typed-slot helper carries
17498        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
17499        // Read directly from the codec-owned predicate — the crate's
17500        // single source of truth every typed-`Duration` axis now routes
17501        // through via
17502        // [`crate::render::require_positive_canonical_bounded_duration`].
17503        use super::supervisor::duration_codec::is_integer_millisecond_duration;
17504        assert!(is_integer_millisecond_duration(Duration::ZERO));
17505        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
17506        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
17507        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
17508        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
17509        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
17510        // Non-integer-millisecond residue: rejected.
17511        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
17512        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
17513        assert!(!is_integer_millisecond_duration(Duration::from_micros(
17514            1500
17515        )));
17516        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
17517        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17518            999_999
17519        )));
17520        // The 1-ns-past-1ms boundary: rejected (no longer a clean
17521        // integer-millisecond multiple).
17522        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17523            1_000_001
17524        )));
17525    }
17526
17527    #[test]
17528    fn policy_timeout_validated_value_round_trips_through_codec() {
17529        // The structural property the canonical-ms gate enforces:
17530        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
17531        // round-trips losslessly through the shared `duration_codec`
17532        // (serialize → string → deserialize → equal value). Pin this
17533        // end-to-end so a future change to either side (the validate
17534        // gate's accepted granularity, the codec's parse/render unit
17535        // set) that breaks the alignment surfaces here. The
17536        // previous-state shape (typed slot accepts arbitrary
17537        // `Duration`, codec only round-trips integer-ms) would fail
17538        // this test for any `Duration::from_micros(1500)` timeout —
17539        // the validate gate now forecloses that.
17540        for timeout in [
17541            Duration::from_millis(1),
17542            Duration::from_millis(1500),
17543            Duration::from_secs(30),
17544            Duration::from_secs(3600),
17545        ] {
17546            let mut s = three_member_spec();
17547            s.politicas.timeout = Some(timeout);
17548            s.validate().unwrap();
17549            let json = serde_json::to_string(&s.politicas).unwrap();
17550            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17551            assert_eq!(
17552                back.timeout, s.politicas.timeout,
17553                "every validated :timeout must round-trip losslessly through the codec"
17554            );
17555        }
17556    }
17557
17558    #[test]
17559    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
17560        // Peer of the `:timeout` round-trip property on the breaker
17561        // axis.
17562        for window in [
17563            Duration::from_millis(1),
17564            Duration::from_millis(1500),
17565            Duration::from_secs(30),
17566            Duration::from_secs(3600),
17567        ] {
17568            let mut s = three_member_spec();
17569            s.politicas.circuit_breaker = Some(CircuitBreaker {
17570                max_failures: 5,
17571                window,
17572            });
17573            s.validate().unwrap();
17574            let json = serde_json::to_string(&s.politicas).unwrap();
17575            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17576            assert_eq!(
17577                back.circuit_breaker.unwrap().window,
17578                window,
17579                "every validated :circuit-breaker :window must round-trip losslessly"
17580            );
17581        }
17582    }
17583
17584    #[test]
17585    fn empty_politicas_validates() {
17586        // Omitting every policy axis is fine — defaults express "no
17587        // policy on this axis", not "policy = 0". The fixture's typical
17588        // values continue to validate; this test pins that
17589        // MeshPolicy::default() is a clean pass through validate().
17590        let mut s = three_member_spec();
17591        s.politicas = MeshPolicy::default();
17592        s.validate().unwrap();
17593    }
17594
17595    #[test]
17596    fn typical_politicas_validates_with_every_axis_set() {
17597        // The full §III.1 example block (timeout + retries + breaker +
17598        // mtls + rate-limit) — every axis nonzero — must remain a
17599        // clean pass.
17600        let mut s = three_member_spec();
17601        s.politicas = MeshPolicy {
17602            timeout: Some(Duration::from_secs(30)),
17603            retries: Some(3),
17604            circuit_breaker: Some(CircuitBreaker {
17605                max_failures: 5,
17606                window: Duration::from_secs(60),
17607            }),
17608            mtls_required: Some(true),
17609            rate_limit: Some(RateLimit {
17610                rate: 100,
17611                window: Duration::from_secs(1),
17612            }),
17613        };
17614        s.validate().unwrap();
17615    }
17616
17617    #[test]
17618    fn rejects_empty_cluster_name() {
17619        let mut s = three_member_spec();
17620        s.placement.clusters = vec!["rio".into(), "".into()];
17621        assert_eq!(
17622            s.validate().unwrap_err(),
17623            AplicacaoError::PlacementClusterEmpty
17624        );
17625    }
17626
17627    #[test]
17628    fn rejects_duplicate_cluster_names() {
17629        let mut s = three_member_spec();
17630        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
17631        let err = s.validate().unwrap_err();
17632        assert!(
17633            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
17634            "got {err:?}"
17635        );
17636    }
17637
17638    #[test]
17639    fn rejects_placement_cluster_with_uppercase() {
17640        // The canonical "I copied the cluster's display name verbatim"
17641        // typo — K8s context names are lowercase per DNS-1123 label
17642        // rule, but org docs often round-trip a TitleCase identifier
17643        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
17644        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
17645        // on the peer name axis.
17646        let mut s = three_member_spec();
17647        s.placement.clusters = vec!["Rio".into(), "mar".into()];
17648        let err = s.validate().unwrap_err();
17649        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17650            panic!("expected PlacementClusterInvalid, got other variant");
17651        };
17652        assert_eq!(cluster, "Rio");
17653        assert!(
17654            reason.contains("uppercase"),
17655            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
17656        );
17657        assert!(
17658            reason.contains("\"rio\""),
17659            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
17660        );
17661    }
17662
17663    #[test]
17664    fn rejects_placement_cluster_with_underscore() {
17665        // The canonical "I'm thinking of an env var / hostname slug"
17666        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
17667        // schema. K8s context filtering on `my_cluster` silently misses
17668        // the cluster the author intended; the gate moves it to caixa-
17669        // build time. Same shape as `rejects_membro_caixa_with_underscore`
17670        // (3f9d7a0).
17671        let mut s = three_member_spec();
17672        s.placement.clusters = vec!["my_cluster".into()];
17673        let err = s.validate().unwrap_err();
17674        assert!(
17675            matches!(
17676                err,
17677                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17678                    if cluster == "my_cluster" && reason.contains('_')
17679            ),
17680            "got {err:?}"
17681        );
17682    }
17683
17684    #[test]
17685    fn rejects_placement_cluster_with_dot() {
17686        // A `:placement :clusters` entry is a single DNS-1123 *label*,
17687        // not a subdomain — even though K8s context names sometimes
17688        // carry a dotted form via kubeconfig conventions, the strictest
17689        // floor among the use sites (DNS-1035 cluster.x-k8s.io
17690        // `metadata.name`, Cilium identity label values) wins. The "I
17691        // want to namespace my cluster names with `.`" intent is
17692        // expressed via `-` (`mar-east`).
17693        let mut s = three_member_spec();
17694        s.placement.clusters = vec!["team.rio".into()];
17695        let err = s.validate().unwrap_err();
17696        assert!(
17697            matches!(
17698                err,
17699                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17700                    if cluster == "team.rio" && reason.contains('.')
17701            ),
17702            "got {err:?}"
17703        );
17704    }
17705
17706    #[test]
17707    fn rejects_placement_cluster_with_leading_hyphen() {
17708        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
17709        // with an alphanumeric. The K8s apiserver rejects `-rio`
17710        // outright; the rendered fan-out would emit a `metadata.name:
17711        // "-rio"` that fails admission far from the source caixa.lisp.
17712        let mut s = three_member_spec();
17713        s.placement.clusters = vec!["-rio".into()];
17714        let err = s.validate().unwrap_err();
17715        assert!(
17716            matches!(
17717                err,
17718                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17719                    if cluster == "-rio" && reason.contains("start and end")
17720            ),
17721            "got {err:?}"
17722        );
17723    }
17724
17725    #[test]
17726    fn rejects_placement_cluster_with_trailing_hyphen() {
17727        // The symmetric arm of the boundary rule. Pin separately so
17728        // both ends are covered against a future relaxation that only
17729        // checks one boundary (parallel to
17730        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
17731        let mut s = three_member_spec();
17732        s.placement.clusters = vec!["rio-".into()];
17733        let err = s.validate().unwrap_err();
17734        assert!(
17735            matches!(
17736                err,
17737                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17738                    if cluster == "rio-"
17739            ),
17740            "got {err:?}"
17741        );
17742    }
17743
17744    #[test]
17745    fn rejects_placement_cluster_with_unicode() {
17746        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
17747        // before it reaches K8s. The byte-by-byte ASCII validity check
17748        // rejects multi-byte UTF-8 sequences by the first byte that
17749        // fails `[a-z0-9-]`.
17750        let mut s = three_member_spec();
17751        s.placement.clusters = vec!["rió".into()];
17752        let err = s.validate().unwrap_err();
17753        assert!(
17754            matches!(
17755                err,
17756                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17757                    if cluster == "rió"
17758            ),
17759            "got {err:?}"
17760        );
17761    }
17762
17763    #[test]
17764    fn rejects_placement_cluster_with_whitespace() {
17765        // Whitespace is the canonical "I pasted from a sketch / doc"
17766        // footgun. The apiserver rejects every cluster `metadata.name`
17767        // value carrying whitespace.
17768        let mut s = three_member_spec();
17769        s.placement.clusters = vec!["rio cluster".into()];
17770        let err = s.validate().unwrap_err();
17771        assert!(
17772            matches!(
17773                err,
17774                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17775                    if cluster == "rio cluster"
17776            ),
17777            "got {err:?}"
17778        );
17779    }
17780
17781    #[test]
17782    fn rejects_placement_cluster_too_long() {
17783        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
17784        // pin. The diagnostic names both the cap (63) and the actual
17785        // length so the author can shorten in one edit. Mirrors
17786        // `rejects_membro_caixa_too_long` (3f9d7a0).
17787        let mut s = three_member_spec();
17788        let too_long = "a".repeat(64);
17789        s.placement.clusters = vec![too_long.clone()];
17790        let err = s.validate().unwrap_err();
17791        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17792            panic!("expected PlacementClusterInvalid");
17793        };
17794        assert_eq!(cluster, too_long);
17795        assert!(
17796            reason.contains("63") && reason.contains("64"),
17797            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
17798        );
17799    }
17800
17801    #[test]
17802    fn placement_cluster_max_length_validates() {
17803        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
17804        // future tightening (e.g. dropping to 62) surfaces here as a
17805        // regression, mirroring `membro_caixa_max_length_validates`
17806        // (3f9d7a0).
17807        let mut s = three_member_spec();
17808        s.placement.clusters = vec!["a".repeat(63)];
17809        s.validate().unwrap();
17810    }
17811
17812    #[test]
17813    fn accepts_canonical_placement_cluster_forms() {
17814        // The DNS-1123 label shapes a caixa author is realistically
17815        // going to write for cluster names: single-word lowercase
17816        // (`rio`), regional hyphen-joined (`mar-east`), single
17817        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
17818        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
17819        // Pin every leg so a future tightening that bans (e.g.) digit-
17820        // start identifiers surfaces here.
17821        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
17822            let mut s = three_member_spec();
17823            s.placement.clusters = vec![form.into()];
17824            s.validate().unwrap_or_else(|e| {
17825                panic!("canonical cluster form {form:?} must validate, got {e:?}")
17826            });
17827        }
17828    }
17829
17830    #[test]
17831    fn placement_cluster_empty_takes_precedence_over_invalid() {
17832        // Order pin: the existing `PlacementClusterEmpty` diagnostic
17833        // (which doesn't try to parse) fires before the new
17834        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
17835        // `:clusters` entry keeps its narrower error message — the new
17836        // gate would also reject `""`, but the empty-string arm is the
17837        // more self-locating diagnostic. Mirrors the
17838        // `membro_caixa_empty_takes_precedence_over_invalid` pin
17839        // (3f9d7a0).
17840        let mut s = three_member_spec();
17841        s.placement.clusters = vec!["rio".into(), "".into()];
17842        let err = s.validate().unwrap_err();
17843        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
17844    }
17845
17846    #[test]
17847    fn placement_cluster_invalid_fires_before_duplicate_check() {
17848        // Order pin: a malformed-shape `:clusters` entry surfaces *its
17849        // own* diagnostic, even when a later entry would otherwise
17850        // collapse onto a duplicate name. The per-entry shape gate runs
17851        // inline before the duplicate-key insert, parallel to
17852        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
17853        let mut s = three_member_spec();
17854        s.placement.clusters = vec!["Rio".into(), "rio".into()];
17855        let err = s.validate().unwrap_err();
17856        assert!(
17857            matches!(
17858                err,
17859                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
17860            ),
17861            "got {err:?}"
17862        );
17863    }
17864
17865    #[test]
17866    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
17867        // The diagnostic-shape pin: the error names the offending
17868        // `:clusters` value verbatim so the author can grep their
17869        // caixa.lisp without re-running the build, and carries a
17870        // non-empty `reason` naming the specific violation. Same shape
17871        // every typed-shape gate enshrines
17872        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
17873        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
17874        let mut s = three_member_spec();
17875        s.placement.clusters = vec!["BAD_CLUSTER".into()];
17876        let err = s.validate().unwrap_err();
17877        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17878            panic!("expected PlacementClusterInvalid");
17879        };
17880        assert_eq!(cluster, "BAD_CLUSTER");
17881        assert!(
17882            !reason.is_empty(),
17883            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
17884        );
17885    }
17886
17887    #[test]
17888    fn rejects_sharded_with_empty_clusters() {
17889        // §III.1: Sharded uses :clusters as the shard pool. An empty
17890        // pool means "shard across no clusters" — meaningless, same as
17891        // Replicated with no hosts.
17892        let mut s = three_member_spec();
17893        s.placement.estrategia = PlacementStrategy::Sharded;
17894        s.placement.shard_key = Some("$tenantId".into());
17895        s.placement.clusters = vec![];
17896        assert!(matches!(
17897            s.validate().unwrap_err(),
17898            AplicacaoError::PlacementWithoutClusters {
17899                estrategia: PlacementStrategy::Sharded
17900            }
17901        ));
17902    }
17903
17904    #[test]
17905    fn rejects_sharded_with_empty_shard_key() {
17906        let mut s = three_member_spec();
17907        s.placement.estrategia = PlacementStrategy::Sharded;
17908        s.placement.shard_key = Some("".into());
17909        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
17910    }
17911
17912    #[test]
17913    fn rejects_shard_key_under_replicated_strategy() {
17914        // The fail-before-pass-after pin: a `:placement (:estrategia
17915        // Replicated :shard-key "tenantId")` manifest carries the
17916        // hash-keyed-distribution slot on a strategy that never consumes
17917        // it. Before the gate the typed slot's value silently vanished
17918        // at the renderer layer (caixa-mesh emits `placement.shardKey`
17919        // verbatim regardless of strategy; the Akka-style cluster-
17920        // sharding reconciler keys off `estrategia == Sharded` and
17921        // ignores the slot otherwise), with no diagnostic. Lifting the
17922        // rejection to a build-time gate makes the
17923        // `shard_key.is_some() == matches!(estrategia, Sharded)`
17924        // partition a structural property of every validated
17925        // [`Placement`].
17926        let mut s = three_member_spec();
17927        // The fixture already uses Replicated; just add a shard-key.
17928        s.placement.shard_key = Some("$tenantId".into());
17929        let err = s.validate().unwrap_err();
17930        let AplicacaoError::ShardKeyOnNonSharded {
17931            estrategia,
17932            shard_key,
17933        } = err
17934        else {
17935            panic!("expected ShardKeyOnNonSharded, got {err:?}");
17936        };
17937        assert_eq!(estrategia, PlacementStrategy::Replicated);
17938        assert_eq!(shard_key, "$tenantId");
17939    }
17940
17941    #[test]
17942    fn rejects_shard_key_under_singlenode_strategy() {
17943        // Peer of the Replicated case above on the SingleNode arm: OTP
17944        // distributed-app takeover (one cluster runs at a time) has no
17945        // hash-keyed routing axis to consume `:shard-key` either, so
17946        // the rejection fires on both non-Sharded arms uniformly.
17947        let mut s = three_member_spec();
17948        s.placement.estrategia = PlacementStrategy::SingleNode;
17949        s.placement.shard_key = Some("$tenantId".into());
17950        let err = s.validate().unwrap_err();
17951        let AplicacaoError::ShardKeyOnNonSharded {
17952            estrategia,
17953            shard_key,
17954        } = err
17955        else {
17956            panic!("expected ShardKeyOnNonSharded, got {err:?}");
17957        };
17958        assert_eq!(estrategia, PlacementStrategy::SingleNode);
17959        assert_eq!(shard_key, "$tenantId");
17960    }
17961
17962    #[test]
17963    fn rejects_empty_shard_key_under_replicated_strategy() {
17964        // The `Some("")` case under non-Sharded is rejected by
17965        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
17966        // fires before the empty-value gate), not
17967        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
17968        // the `Sharded` arm). Pin the partition so a future reorder of
17969        // the validate_placement match arms doesn't silently swap which
17970        // diagnostic the author sees — both are author errors, but
17971        // ShardKeyOnNonSharded names which strategy is the actual fix
17972        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
17973        // only says "pick a non-empty key".
17974        let mut s = three_member_spec();
17975        s.placement.shard_key = Some(String::new());
17976        let err = s.validate().unwrap_err();
17977        assert!(
17978            matches!(
17979                err,
17980                AplicacaoError::ShardKeyOnNonSharded {
17981                    estrategia: PlacementStrategy::Replicated,
17982                    ref shard_key,
17983                } if shard_key.is_empty()
17984            ),
17985            "got {err:?}"
17986        );
17987    }
17988
17989    #[test]
17990    fn replicated_without_shard_key_validates() {
17991        // The complement of the rejection: `:placement :estrategia
17992        // Replicated` with `:shard-key None` is the canonical happy
17993        // path on every existing fixture. Pin the no-shard-key case so
17994        // the new gate doesn't accidentally fire on `None`.
17995        let mut s = three_member_spec();
17996        assert!(matches!(
17997            s.placement.estrategia,
17998            PlacementStrategy::Replicated
17999        ));
18000        s.placement.shard_key = None;
18001        s.validate().unwrap();
18002    }
18003
18004    #[test]
18005    fn singlenode_without_shard_key_validates() {
18006        // Peer of the Replicated no-shard-key case on the SingleNode
18007        // arm — both non-Sharded strategies must validate cleanly when
18008        // the slot is omitted.
18009        let mut s = three_member_spec();
18010        s.placement.estrategia = PlacementStrategy::SingleNode;
18011        s.placement.shard_key = None;
18012        s.validate().unwrap();
18013    }
18014
18015    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
18016        // Fixture builder for the `:placement :shard-key` shape gate
18017        // tests: a three-member Aplicacao on the `Sharded` strategy
18018        // with the supplied `:shard-key` slot. Co-locates the
18019        // arm-construction so every test below carries one line of
18020        // setup (the offending `:shard-key` value) and the assertion.
18021        let mut s = three_member_spec();
18022        s.placement.estrategia = PlacementStrategy::Sharded;
18023        s.placement.shard_key = Some(key.into());
18024        s
18025    }
18026
18027    #[test]
18028    fn rejects_shard_key_with_embedded_space() {
18029        // The canonical paste-from-aligned-doc footgun:
18030        // `:shard-key "$tenant Id"` — the Akka-style entity-id
18031        // extractor reads the slot as a single-token reference, and an
18032        // embedded space breaks the token boundary at the runtime
18033        // hash-extractor pass with no diagnostic naming the offending
18034        // entry.
18035        let s = sharded_spec_with_key("$tenant Id");
18036        let err = s.validate().unwrap_err();
18037        assert!(
18038            matches!(
18039                err,
18040                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18041                    if shard_key == "$tenant Id" && reason.contains("space")
18042            ),
18043            "got {err:?}"
18044        );
18045    }
18046
18047    #[test]
18048    fn rejects_shard_key_with_leading_space() {
18049        // Leading-space arm of the embedded-whitespace footgun — the
18050        // paste-from-aligned-doc / paste-from-CSV-cell variant where
18051        // the leading column-padding leaked into the slot.
18052        let s = sharded_spec_with_key(" $tenantId");
18053        let err = s.validate().unwrap_err();
18054        assert!(
18055            matches!(
18056                err,
18057                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
18058                    if shard_key == " $tenantId"
18059            ),
18060            "got {err:?}"
18061        );
18062    }
18063
18064    #[test]
18065    fn rejects_shard_key_with_trailing_newline() {
18066        // The canonical paste-from-shell-heredoc footgun — every
18067        // `<<EOF` heredoc terminator paste leaves a trailing newline
18068        // the YAML emitter then folds away inconsistently across
18069        // emitter implementations.
18070        let s = sharded_spec_with_key("$tenantId\n");
18071        let err = s.validate().unwrap_err();
18072        assert!(
18073            matches!(
18074                err,
18075                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18076                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
18077            ),
18078            "got {err:?}"
18079        );
18080    }
18081
18082    #[test]
18083    fn rejects_shard_key_with_embedded_tab() {
18084        // The paste-from-aligned-doc tab-stop variant — tabs land
18085        // alongside spaces in copy-paste from formatted columns.
18086        let s = sharded_spec_with_key("$tenant\tId");
18087        let err = s.validate().unwrap_err();
18088        assert!(
18089            matches!(
18090                err,
18091                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18092                    if shard_key == "$tenant\tId" && reason.contains("tab")
18093            ),
18094            "got {err:?}"
18095        );
18096    }
18097
18098    #[test]
18099    fn rejects_shard_key_with_control_character() {
18100        // The paste-from-binary / paste-from-screen-cleared-terminal
18101        // footgun — an embedded `\x01` (SOH) byte that some YAML
18102        // emitters silently strip and others escape as ``,
18103        // breaking round-trip across emitter implementations.
18104        let s = sharded_spec_with_key("$tenant\u{0001}Id");
18105        let err = s.validate().unwrap_err();
18106        assert!(
18107            matches!(
18108                err,
18109                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18110                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
18111            ),
18112            "got {err:?}"
18113        );
18114    }
18115
18116    #[test]
18117    fn rejects_shard_key_with_non_ascii() {
18118        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
18119        // footgun — non-ASCII bytes normalize differently between the
18120        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
18121        // YAML parser, the same entity ID can silently map to two
18122        // distinct shards on a re-render.
18123        let s = sharded_spec_with_key("$tenàntId");
18124        let err = s.validate().unwrap_err();
18125        assert!(
18126            matches!(
18127                err,
18128                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18129                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
18130            ),
18131            "got {err:?}"
18132        );
18133    }
18134
18135    #[test]
18136    fn rejects_shard_key_too_long() {
18137        // Length cap pin: 64 bytes — one byte over the
18138        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
18139        // here is a paste-from-doc multi-line blob landing in
18140        // `:shard-key` instead of a single-token extractor expression.
18141        let too_long = "a".repeat(64);
18142        let s = sharded_spec_with_key(&too_long);
18143        let err = s.validate().unwrap_err();
18144        let AplicacaoError::ShardKeyInvalid {
18145            ref shard_key,
18146            ref reason,
18147        } = err
18148        else {
18149            panic!("expected ShardKeyInvalid, got {err:?}");
18150        };
18151        assert_eq!(shard_key, &too_long);
18152        assert!(
18153            reason.contains("63") && reason.contains("64"),
18154            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18155        );
18156    }
18157
18158    #[test]
18159    fn shard_key_max_length_validates() {
18160        // Boundary pin: 63 bytes exactly — the
18161        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
18162        // dropping to 62) surfaces here as a regression, mirroring
18163        // `placement_cluster_max_length_validates` /
18164        // `placement_affinity_max_length_validates` on the peer
18165        // identifier-shaped slots.
18166        let s = sharded_spec_with_key(&"a".repeat(63));
18167        s.validate().unwrap();
18168    }
18169
18170    #[test]
18171    fn accepts_canonical_shard_key_forms() {
18172        // The Akka-style entity-id extractor shapes a caixa author is
18173        // realistically going to write — pin every leg so a future
18174        // tightening that bans (e.g.) the `${...}` interpolation
18175        // variant or the `metadata.<field>` JSONPath form surfaces
18176        // here as a regression. The canonical forms span:
18177        //
18178        //   - bare property name (`tenantId`, `customerId`)
18179        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
18180        //   - JSONPath-style nested reference (`metadata.tenantId`,
18181        //     `$.user.id`)
18182        //   - interpolation-style template (`${tenant}`)
18183        //   - snake_case property name (`customer_id`)
18184        //   - kebab-case property name (`customer-id` — accepted
18185        //     because the slot is a printable-ASCII single-token
18186        //     reference, not a DNS-1123 label like
18187        //     `:placement :affinity` / `:clusters`)
18188        //   - single character (`a`, `$` — boundary)
18189        for form in [
18190            "tenantId",
18191            "customerId",
18192            "$tenantId",
18193            "metadata.tenantId",
18194            "$.user.id",
18195            "${tenant}",
18196            "customer_id",
18197            "customer-id",
18198            "a",
18199            "$",
18200        ] {
18201            let s = sharded_spec_with_key(form);
18202            s.validate().unwrap_or_else(|e| {
18203                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
18204            });
18205        }
18206    }
18207
18208    #[test]
18209    fn shard_key_empty_takes_precedence_over_invalid() {
18210        // Order pin: the existing `ShardedKeyEmpty` diagnostic
18211        // (reserved for the `Sharded` `Some("")` arm) fires before the
18212        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
18213        // `:shard-key` keeps its narrower error message — the new gate
18214        // would also reject `""` defensively, but the empty-string arm
18215        // is the more self-locating diagnostic. Mirrors the
18216        // `placement_cluster_empty_takes_precedence_over_invalid` pin
18217        // on the peer identifier-shaped slot.
18218        let s = sharded_spec_with_key("");
18219        let err = s.validate().unwrap_err();
18220        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
18221    }
18222
18223    #[test]
18224    fn shard_key_invalid_diagnostic_carries_offending_value() {
18225        // The diagnostic-shape pin: the error names the offending
18226        // `:shard-key` value verbatim so the author can grep their
18227        // caixa.lisp without re-running the build, and carries a
18228        // parser-shaped `reason:` naming the specific violation —
18229        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18230        // on the peer identifier-shaped slot.
18231        let s = sharded_spec_with_key("$tenant Id");
18232        let err = s.validate().unwrap_err();
18233        let AplicacaoError::ShardKeyInvalid {
18234            ref shard_key,
18235            ref reason,
18236        } = err
18237        else {
18238            panic!("expected ShardKeyInvalid, got {err:?}");
18239        };
18240        assert_eq!(shard_key, "$tenant Id");
18241        assert!(
18242            !reason.is_empty(),
18243            "reason must name the specific violation, got empty string"
18244        );
18245    }
18246
18247    #[test]
18248    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
18249        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
18250        // `:shard-key` carried on non-Sharded strategies) fires before
18251        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
18252        // a `Replicated` strategy surfaces the more self-locating
18253        // strategy-mismatch diagnostic (naming the actual fix — drop
18254        // the slot, or switch to Sharded) rather than the shape
18255        // diagnostic. The strategy-mismatch arm is the more actionable
18256        // diagnostic: a malformed shard-key on Replicated is "you
18257        // shouldn't have a :shard-key here at all", not "your
18258        // :shard-key value is malformed".
18259        let mut s = three_member_spec();
18260        // Replicated is the default fixture strategy.
18261        s.placement.shard_key = Some("$tenant Id".into());
18262        let err = s.validate().unwrap_err();
18263        assert!(
18264            matches!(
18265                err,
18266                AplicacaoError::ShardKeyOnNonSharded {
18267                    estrategia: PlacementStrategy::Replicated,
18268                    ..
18269                }
18270            ),
18271            "got {err:?}"
18272        );
18273    }
18274
18275    #[test]
18276    fn rejects_empty_affinity_hint() {
18277        let mut s = three_member_spec();
18278        s.placement.affinity = Some("".into());
18279        assert_eq!(
18280            s.validate().unwrap_err(),
18281            AplicacaoError::PlacementAffinityEmpty
18282        );
18283    }
18284
18285    #[test]
18286    fn placement_without_affinity_validates() {
18287        // Omitting :affinity is fine — the placement engine falls back
18288        // to the default heuristic. Pin the no-hint case so the
18289        // affinity-empty rejection doesn't accidentally fire on `None`.
18290        let mut s = three_member_spec();
18291        s.placement.affinity = None;
18292        s.validate().unwrap();
18293    }
18294
18295    #[test]
18296    fn rejects_placement_affinity_with_uppercase() {
18297        // The canonical "I copied the ADR's display name verbatim" typo
18298        // — placement hints land verbatim in K8s label-selector
18299        // territory, where the apiserver enforces the DNS-1123 label
18300        // rule (lowercase-only) on every identity-keyed admission axis.
18301        // Mirrors `rejects_placement_cluster_with_uppercase` on the
18302        // sibling slot.
18303        let mut s = three_member_spec();
18304        s.placement.affinity = Some("DataLocality".into());
18305        let err = s.validate().unwrap_err();
18306        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18307            panic!("expected PlacementAffinityInvalid, got other variant");
18308        };
18309        assert_eq!(affinity, "DataLocality");
18310        assert!(
18311            reason.contains("uppercase"),
18312            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18313        );
18314        assert!(
18315            reason.contains("\"datalocality\""),
18316            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18317        );
18318    }
18319
18320    #[test]
18321    fn rejects_placement_affinity_with_underscore() {
18322        // The canonical "I'm thinking of an env var / Python identifier"
18323        // leak — `_` is forbidden by every DNS-1123 label schema. Same
18324        // shape as `rejects_placement_cluster_with_underscore` on the
18325        // sibling slot.
18326        let mut s = three_member_spec();
18327        s.placement.affinity = Some("data_locality".into());
18328        let err = s.validate().unwrap_err();
18329        assert!(
18330            matches!(
18331                err,
18332                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18333                    if affinity == "data_locality" && reason.contains('_')
18334            ),
18335            "got {err:?}"
18336        );
18337    }
18338
18339    #[test]
18340    fn rejects_placement_affinity_with_dot() {
18341        // A `:placement :affinity` value is a single DNS-1123 *label*
18342        // (it lands as a K8s label value selector key), not a subdomain.
18343        // The "I want to namespace my hint with `.`" intent is expressed
18344        // via `-` (`data-locality-east`).
18345        let mut s = three_member_spec();
18346        s.placement.affinity = Some("data.locality".into());
18347        let err = s.validate().unwrap_err();
18348        assert!(
18349            matches!(
18350                err,
18351                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18352                    if affinity == "data.locality" && reason.contains('.')
18353            ),
18354            "got {err:?}"
18355        );
18356    }
18357
18358    #[test]
18359    fn rejects_placement_affinity_with_unicode() {
18360        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18361        // before it reaches K8s. The byte-by-byte ASCII validity check
18362        // rejects multi-byte UTF-8 sequences by the first byte that
18363        // fails `[a-z0-9-]`.
18364        let mut s = three_member_spec();
18365        s.placement.affinity = Some("data-localité".into());
18366        let err = s.validate().unwrap_err();
18367        assert!(
18368            matches!(
18369                err,
18370                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18371                    if affinity == "data-localité"
18372            ),
18373            "got {err:?}"
18374        );
18375    }
18376
18377    #[test]
18378    fn rejects_placement_affinity_with_leading_hyphen() {
18379        // DNS-1123 boundary rule: labels must start with an
18380        // alphanumeric. Pin separately from the trailing-hyphen arm so
18381        // a future relaxation that only checks one boundary surfaces
18382        // here as a regression (parallel to
18383        // `rejects_placement_cluster_with_leading_hyphen`).
18384        let mut s = three_member_spec();
18385        s.placement.affinity = Some("-data-locality".into());
18386        let err = s.validate().unwrap_err();
18387        assert!(
18388            matches!(
18389                err,
18390                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18391                    if affinity == "-data-locality" && reason.contains("start and end")
18392            ),
18393            "got {err:?}"
18394        );
18395    }
18396
18397    #[test]
18398    fn rejects_placement_affinity_with_trailing_hyphen() {
18399        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
18400        // ends are covered against a future relaxation.
18401        let mut s = three_member_spec();
18402        s.placement.affinity = Some("data-locality-".into());
18403        let err = s.validate().unwrap_err();
18404        assert!(
18405            matches!(
18406                err,
18407                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18408                    if affinity == "data-locality-"
18409            ),
18410            "got {err:?}"
18411        );
18412    }
18413
18414    #[test]
18415    fn rejects_placement_affinity_with_whitespace() {
18416        // Whitespace is the canonical "I pasted from a sketch / doc"
18417        // footgun. The apiserver rejects every label-selector value
18418        // carrying whitespace.
18419        let mut s = three_member_spec();
18420        s.placement.affinity = Some("data locality".into());
18421        let err = s.validate().unwrap_err();
18422        assert!(
18423            matches!(
18424                err,
18425                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18426                    if affinity == "data locality"
18427            ),
18428            "got {err:?}"
18429        );
18430    }
18431
18432    #[test]
18433    fn rejects_placement_affinity_too_long() {
18434        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18435        // pin. The diagnostic names both the cap (63) and the actual
18436        // length so the author can shorten in one edit. Mirrors
18437        // `rejects_placement_cluster_too_long`.
18438        let mut s = three_member_spec();
18439        let too_long = "a".repeat(64);
18440        s.placement.affinity = Some(too_long.clone());
18441        let err = s.validate().unwrap_err();
18442        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18443            panic!("expected PlacementAffinityInvalid");
18444        };
18445        assert_eq!(affinity, too_long);
18446        assert!(
18447            reason.contains("63") && reason.contains("64"),
18448            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18449        );
18450    }
18451
18452    #[test]
18453    fn placement_affinity_max_length_validates() {
18454        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18455        // future tightening (e.g. dropping to 62) surfaces here as a
18456        // regression, mirroring `placement_cluster_max_length_validates`.
18457        let mut s = three_member_spec();
18458        s.placement.affinity = Some("a".repeat(63));
18459        s.validate().unwrap();
18460    }
18461
18462    #[test]
18463    fn accepts_canonical_placement_affinity_forms() {
18464        // The DNS-1123 label shapes a caixa author is realistically
18465        // going to write for placement hints: the M3 canonical examples
18466        // (`data-locality`, `low-latency`, `anti-affinity`), the
18467        // single-token form (`affinity`), the single-character boundary
18468        // (`a`), the digit-start (DNS-1123 allows this, unlike
18469        // DNS-1035), and a regional-suffixed form. Pin every leg so a
18470        // future tightening that bans (e.g.) digit-start identifiers
18471        // surfaces here.
18472        for form in [
18473            "data-locality",
18474            "low-latency",
18475            "anti-affinity",
18476            "affinity",
18477            "a",
18478            "3-tier",
18479            "locality-east",
18480        ] {
18481            let mut s = three_member_spec();
18482            s.placement.affinity = Some(form.into());
18483            s.validate().unwrap_or_else(|e| {
18484                panic!("canonical affinity form {form:?} must validate, got {e:?}")
18485            });
18486        }
18487    }
18488
18489    #[test]
18490    fn placement_affinity_empty_takes_precedence_over_invalid() {
18491        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
18492        // (which doesn't try to parse) fires before the new
18493        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
18494        // `:affinity` keeps its narrower error message — the new gate
18495        // would also reject `""`, but the empty-string arm is the more
18496        // self-locating diagnostic. Mirrors the
18497        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
18498        let mut s = three_member_spec();
18499        s.placement.affinity = Some(String::new());
18500        let err = s.validate().unwrap_err();
18501        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
18502    }
18503
18504    #[test]
18505    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
18506        // The diagnostic shape pin: every rejection carries the offending
18507        // `affinity:` verbatim plus a parser-shaped `reason:` so the
18508        // author can grep their caixa.lisp for `:affinity "<hint>"` and
18509        // fix it in one edit. Mirrors the
18510        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18511        // pin on the sibling slot.
18512        let mut s = three_member_spec();
18513        s.placement.affinity = Some("Data_Locality".into());
18514        let err = s.validate().unwrap_err();
18515        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18516            panic!("expected PlacementAffinityInvalid");
18517        };
18518        assert_eq!(affinity, "Data_Locality");
18519        assert!(
18520            !reason.is_empty(),
18521            "diagnostic reason must not be empty (got: {reason:?})"
18522        );
18523    }
18524
18525    #[test]
18526    fn singlenode_with_takeover_candidates_validates() {
18527        // OTP distributed-application convention (MESH-COMPOSITION
18528        // §II.1): SingleNode runs on one cluster at a time but the
18529        // :clusters list enumerates the takeover candidates. Multiple
18530        // entries are not a contradiction — they are the failover pool.
18531        let mut s = three_member_spec();
18532        s.placement.estrategia = PlacementStrategy::SingleNode;
18533        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
18534        s.validate().unwrap();
18535    }
18536
18537    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
18538
18539    #[test]
18540    fn mesh_policy_default_is_empty() {
18541        // The Default impl carries None on every axis — the typed
18542        // analog of an unset `:politicas (())` slot. Renderers that
18543        // overlay the policy onto a cluster artifact key off this
18544        // predicate to skip the slot entirely; pinning so a future
18545        // axis added to MeshPolicy can't silently break the contract
18546        // (a new field whose Default is non-None would flip is_empty
18547        // to false on every existing caixa, surfacing here).
18548        assert!(MeshPolicy::default().is_empty());
18549    }
18550
18551    #[test]
18552    fn mesh_policy_with_only_timeout_is_not_empty() {
18553        let p = MeshPolicy {
18554            timeout: Some(Duration::from_secs(30)),
18555            ..Default::default()
18556        };
18557        assert!(!p.is_empty());
18558    }
18559
18560    #[test]
18561    fn mesh_policy_with_only_retries_is_not_empty() {
18562        let p = MeshPolicy {
18563            retries: Some(3),
18564            ..Default::default()
18565        };
18566        assert!(!p.is_empty());
18567    }
18568
18569    #[test]
18570    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
18571        let p = MeshPolicy {
18572            circuit_breaker: Some(CircuitBreaker {
18573                max_failures: 5,
18574                window: Duration::from_secs(60),
18575            }),
18576            ..Default::default()
18577        };
18578        assert!(!p.is_empty());
18579    }
18580
18581    #[test]
18582    fn mesh_policy_with_only_mtls_required_is_not_empty() {
18583        // Even `mtls_required: Some(false)` (an explicit opt-out) is
18584        // not empty — the author *named* the axis, the renderer needs
18585        // to honor that vs. fall back to the cluster default.
18586        let p = MeshPolicy {
18587            mtls_required: Some(false),
18588            ..Default::default()
18589        };
18590        assert!(!p.is_empty());
18591    }
18592
18593    #[test]
18594    fn mesh_policy_with_only_rate_limit_is_not_empty() {
18595        let p = MeshPolicy {
18596            rate_limit: Some(RateLimit {
18597                rate: 100,
18598                window: Duration::from_secs(1),
18599            }),
18600            ..Default::default()
18601        };
18602        assert!(!p.is_empty());
18603    }
18604
18605    #[test]
18606    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
18607        // The three-member happy-path fixture sets timeout + retries +
18608        // mtls_required — every populated axis must read non-empty.
18609        // Pin the round-trip so the M3.x per-:politicas emitter (the
18610        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
18611        // on is_empty() to decide whether to emit at all without
18612        // re-deriving the contract from inline field probes.
18613        assert!(!three_member_spec().politicas.is_empty());
18614    }
18615
18616    // ── shared duration codec: cross-slot integer-magnitude gate ──
18617    //
18618    // The integer-magnitude discipline applied to
18619    // `supervisor::duration_codec::parse` lifts onto every typed slot
18620    // that routes through the shared codec — `MeshPolicy::timeout`
18621    // (`:politicas :timeout`) and `CircuitBreaker::window`
18622    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
18623    // These cross-slot tests pin that the gate fires at the serde
18624    // layer for both typed slots, not just for the supervisor side.
18625
18626    #[test]
18627    fn policy_timeout_serde_rejects_fractional_seconds() {
18628        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
18629        // so the shared codec's integer-magnitude gate applies on
18630        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
18631        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
18632        // deserialize with the canonical-form diagnostic naming the
18633        // offending `"1.5"` and the remediation `"1500ms"`.
18634        let payload = r#"{"timeout":"1.5s"}"#;
18635        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18636        let msg = err.to_string();
18637        assert!(
18638            msg.contains("not a non-negative integer"),
18639            "expected integer-magnitude diagnostic in {msg:?}"
18640        );
18641        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
18642        assert!(
18643            msg.contains("\"1500ms\""),
18644            "missing canonical-form remediation in {msg:?}"
18645        );
18646    }
18647
18648    #[test]
18649    fn policy_timeout_serde_rejects_leading_plus_sign() {
18650        // Pin the leading-`+` arm cross-slot — the prior f64 parser
18651        // accepted `"+30s"` silently and round-tripped to `"30s"`.
18652        let payload = r#"{"timeout":"+30s"}"#;
18653        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18654        let msg = err.to_string();
18655        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
18656    }
18657
18658    #[test]
18659    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
18660        // `CircuitBreaker::window` uses `with =
18661        // "supervisor::duration_codec_required"` (the required-Duration
18662        // variant that delegates to the same shared parser). `"0.5m"`
18663        // parsed to 30s and round-tripped to `"30s"` on next emit —
18664        // DRIFT closed.
18665        let payload = format!(
18666            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
18667            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
18668            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
18669        );
18670        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
18671        let msg = err.to_string();
18672        assert!(
18673            msg.contains("not a non-negative integer"),
18674            "expected integer-magnitude diagnostic in {msg:?}"
18675        );
18676        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
18677        assert!(
18678            msg.contains("\"30s\""),
18679            "missing canonical-form remediation in {msg:?}"
18680        );
18681    }
18682
18683    #[test]
18684    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
18685        // Pin the happy-path on the cross-slot side: every canonical
18686        // author shape `render` ever emits parses cleanly through the
18687        // shared codec on the `CircuitBreaker` slot. The
18688        // codec's accepted set (post-gate) is exactly its emitted set
18689        // for the integer-magnitude class.
18690        for window_lit in ["30s", "500ms", "2m", "1h"] {
18691            let payload = format!(
18692                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
18693                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
18694                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
18695            );
18696            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
18697                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
18698            });
18699            assert_eq!(cb.max_failures, 5);
18700        }
18701    }
18702
18703    // ── rate_limit_codec: integer-magnitude gate ──
18704    //
18705    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
18706    // / 737a676 / d53c922 trajectory landed on every typed-duration /
18707    // typed-byte-size codec in caixa-core lifts onto the fifth typed
18708    // codec — `rate_limit_codec` — through the digit-only magnitude
18709    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
18710    // These tests pin the gate at the serde layer for `:politicas
18711    // :rate-limit` (the only typed slot the codec backs), and at the
18712    // codec-internal `parse` layer for the canonical positive cases.
18713
18714    #[test]
18715    fn rate_limit_serde_rejects_fractional_rate() {
18716        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
18717        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
18718        // wording, which didn't name the canonical-form remediation or
18719        // the round-trip drift the next emit would produce. Now refused
18720        // at deserialize with the canonical-form diagnostic naming the
18721        // offending `"1.5"` magnitude and the round-trip drift wording.
18722        let payload = r#"{"rateLimit":"1.5/s"}"#;
18723        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18724        let msg = err.to_string();
18725        assert!(
18726            msg.contains("not a non-negative integer"),
18727            "expected integer-magnitude diagnostic in {msg:?}"
18728        );
18729        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
18730        assert!(
18731            msg.contains("THEORY.md"),
18732            "missing render-determinism contract citation in {msg:?}"
18733        );
18734    }
18735
18736    #[test]
18737    fn rate_limit_serde_rejects_leading_plus_sign() {
18738        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
18739        // permissive-`+` parse), so `"+100/s"` silently parsed to
18740        // `RateLimit { 100, 1s }` and round-tripped through `render` to
18741        // `"100/s"` — a *different* canonical string on the next emit,
18742        // breaking the THEORY.md Part V render-determinism contract
18743        // exactly the way the peer duration codecs' `"+30s"` case did.
18744        // This is the load-bearing class the digit-only gate closes
18745        // beyond what `u32::from_str`'s strictness covers on its own.
18746        let payload = r#"{"rateLimit":"+100/s"}"#;
18747        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18748        let msg = err.to_string();
18749        assert!(
18750            msg.contains("not a non-negative integer"),
18751            "expected integer-magnitude diagnostic in {msg:?}"
18752        );
18753        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
18754    }
18755
18756    #[test]
18757    fn rate_limit_serde_rejects_leading_minus_sign() {
18758        // The signed-negative arm: `"-1/s"` lands on the
18759        // non-canonical-but-numeric branch via the `i64` fallback (the
18760        // `f64` parse also succeeds), surfacing the canonical-form
18761        // diagnostic. Replaces the prior value-laundered "not a u32"
18762        // wording with the unified diagnostic across signs.
18763        let payload = r#"{"rateLimit":"-1/s"}"#;
18764        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18765        let msg = err.to_string();
18766        assert!(
18767            msg.contains("not a non-negative integer"),
18768            "expected integer-magnitude diagnostic in {msg:?}"
18769        );
18770        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
18771    }
18772
18773    #[test]
18774    fn rate_limit_serde_rejects_decimal_shaped_integer() {
18775        // `"100.0/s"` is integer-valued numerically but not in the
18776        // codec's accepted set — `render` emits `"100/s"`, so the
18777        // round-trip would drift. Lifted to the canonical-form
18778        // diagnostic peer with the duration codec's `"1.0s"` case
18779        // (1c55a2a).
18780        let payload = r#"{"rateLimit":"100.0/s"}"#;
18781        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18782        let msg = err.to_string();
18783        assert!(
18784            msg.contains("not a non-negative integer"),
18785            "expected integer-magnitude diagnostic in {msg:?}"
18786        );
18787        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
18788    }
18789
18790    #[test]
18791    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
18792        // Non-numeric, non-digit-only input lands on the existing
18793        // narrower `"not a u32"` arm (preserved for diagnostic-shape
18794        // stability on the parser-shape footgun case). Pin this so a
18795        // future relaxation of the numeric-fallback predicate doesn't
18796        // silently collapse garbage onto the canonical-form arm — same
18797        // partition the peer duration codecs draw between
18798        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
18799        let payload = r#"{"rateLimit":"abc/s"}"#;
18800        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18801        let msg = err.to_string();
18802        assert!(
18803            msg.contains("not a u32"),
18804            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
18805        );
18806        assert!(
18807            !msg.contains("not a non-negative integer"),
18808            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
18809        );
18810    }
18811
18812    #[test]
18813    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
18814        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
18815        // u32's range. The digit-only gate passes; `u32::from_str`
18816        // fails on overflow. Surface that with the overflow-shaped
18817        // diagnostic naming the offending magnitude verbatim, peer
18818        // with `supervisor::duration_codec`'s overflow arm. Pinning
18819        // the wording so a future refactor doesn't silently collapse
18820        // overflow onto the canonical-form arm.
18821        let payload = r#"{"rateLimit":"4294967296/s"}"#;
18822        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18823        let msg = err.to_string();
18824        assert!(
18825            msg.contains("overflows u32"),
18826            "expected overflow diagnostic in {msg:?}"
18827        );
18828        assert!(
18829            msg.contains("\"4294967296\""),
18830            "missing offending magnitude in {msg:?}"
18831        );
18832    }
18833
18834    #[test]
18835    fn rate_limit_serde_rejects_leading_zero_magnitude() {
18836        // `"0100/s"` is digit-only, so the existing
18837        // non-digit-only / sign / fractional arm doesn't catch it —
18838        // `u32::from_str("0100")` returns `Ok(100)`, so before this
18839        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
18840        // round-tripped through `render` to `"100/s"` — a *different*
18841        // canonical string on the next emit, breaking the THEORY.md
18842        // Part V render-determinism contract exactly the way the
18843        // peer `"+100/s"` case did before the leading-`+` arm landed.
18844        // This is the load-bearing class the leading-zero gate closes
18845        // beyond what the existing digit-only / sign / fractional
18846        // gates cover, and the peer arm to the leading-`+` test
18847        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
18848        // canonical-form-drift axis.
18849        let payload = r#"{"rateLimit":"0100/s"}"#;
18850        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18851        let msg = err.to_string();
18852        assert!(
18853            msg.contains("non-canonical leading zero"),
18854            "expected leading-zero diagnostic in {msg:?}"
18855        );
18856        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
18857        assert!(
18858            msg.contains("THEORY.md"),
18859            "missing render-determinism contract citation in {msg:?}"
18860        );
18861    }
18862
18863    #[test]
18864    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
18865        // `"00/s"` is the degenerate leading-zero case — every byte
18866        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
18867        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
18868        // a *different* canonical string, same render-determinism
18869        // violation. The single-byte `"0/s"` itself is in the
18870        // accepted set (round-trips losslessly through `render`,
18871        // refused downstream by `PolicyRateLimitZero`); the
18872        // multi-byte `"00/s"` is not. Pins the boundary between the
18873        // accepted single-`0` and the rejected leading-zero class.
18874        let payload = r#"{"rateLimit":"00/s"}"#;
18875        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18876        let msg = err.to_string();
18877        assert!(
18878            msg.contains("non-canonical leading zero"),
18879            "expected leading-zero diagnostic in {msg:?}"
18880        );
18881        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
18882    }
18883
18884    #[test]
18885    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
18886        // Cross-window pin — the gate is window-agnostic; the
18887        // leading-zero class is a property of the magnitude, not the
18888        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
18889        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
18890        // single-window coverage extended across the three canonical
18891        // windows the codec accepts.
18892        let payload = r#"{"rateLimit":"007/h"}"#;
18893        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18894        let msg = err.to_string();
18895        assert!(
18896            msg.contains("non-canonical leading zero"),
18897            "expected leading-zero diagnostic in {msg:?}"
18898        );
18899        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
18900    }
18901
18902    #[test]
18903    fn rate_limit_serde_rejects_leading_whitespace() {
18904        // `" 100/s"` — the canonical paste-from-aligned-doc /
18905        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
18906        // the top-level `s.trim()` silently ate the leading space and
18907        // parsed the value to `RateLimit { 100, 1s }`, which then
18908        // round-tripped through `render` to `"100/s"` (a *different*
18909        // canonical string on the next emit) — the exact
18910        // canonical-form-drift class the leading-`+` / leading-zero
18911        // arms already close, extended to the whitespace byte class.
18912        let payload = r#"{"rateLimit":" 100/s"}"#;
18913        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18914        let msg = err.to_string();
18915        assert!(
18916            msg.contains("contains whitespace byte"),
18917            "expected whitespace diagnostic in {msg:?}"
18918        );
18919        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
18920        assert!(
18921            msg.contains("THEORY.md"),
18922            "missing render-determinism contract citation in {msg:?}"
18923        );
18924    }
18925
18926    #[test]
18927    fn rate_limit_serde_rejects_trailing_whitespace() {
18928        // `"100/s "` — the canonical shell-history / trailing-space
18929        // paste footgun. Before this gate the top-level `s.trim()`
18930        // silently ate the trailing space and parsed to
18931        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
18932        // next emit — same canonical-form drift as the leading-space
18933        // sibling, closed on the same whitespace-byte arm.
18934        let payload = r#"{"rateLimit":"100/s "}"#;
18935        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18936        let msg = err.to_string();
18937        assert!(
18938            msg.contains("contains whitespace byte"),
18939            "expected whitespace diagnostic in {msg:?}"
18940        );
18941        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
18942    }
18943
18944    #[test]
18945    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
18946        // `"100 / s"` — the canonical typographically-spaced author
18947        // shape (the same idiom every prose reference to a rate limit
18948        // renders as, mistakenly retained when the value is pasted
18949        // into a codec-shaped slot). Before this gate the per-part
18950        // `rate_str.trim()` / `unit.trim()` calls silently ate both
18951        // spaces on either side of `/` and parsed to
18952        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
18953        // codec's *internal* whitespace-tolerance vector, orthogonal
18954        // to the leading / trailing surface but the same canonical-
18955        // form-drift class. Pins the arm as strictly stronger than the
18956        // pre-existing top-level `s.trim()` behavior: it fires on
18957        // whitespace anywhere in the value, not just at the string
18958        // boundary.
18959        let payload = r#"{"rateLimit":"100 / s"}"#;
18960        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18961        let msg = err.to_string();
18962        assert!(
18963            msg.contains("contains whitespace byte"),
18964            "expected whitespace diagnostic in {msg:?}"
18965        );
18966        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
18967    }
18968
18969    #[test]
18970    fn rate_limit_serde_rejects_tab_byte() {
18971        // `"\t100/s"` — the canonical paste-from-indented-doc /
18972        // paste-from-YAML-block-scalar footgun where a tab byte leads
18973        // the magnitude. Pins that the gate covers tab (`0x09`) as
18974        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
18975        // members and both would be silently swallowed by `s.trim()`
18976        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
18977        // space alone to the full ASCII-whitespace set (space `0x20`,
18978        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
18979        // the tab arm as a representative of the non-space members.
18980        let payload = r#"{"rateLimit":"\t100/s"}"#;
18981        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18982        let msg = err.to_string();
18983        assert!(
18984            msg.contains("contains whitespace byte"),
18985            "expected whitespace diagnostic in {msg:?}"
18986        );
18987        assert!(
18988            msg.contains("0x09"),
18989            "missing offending tab byte in {msg:?}"
18990        );
18991    }
18992
18993    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
18994    //
18995    // Successor to the ASCII-whitespace arm (1ad7755) on
18996    // `rate_limit_codec` — closes the strictly-complementary class the
18997    // byte-scan cannot see, through the lifted
18998    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
18999
19000    #[test]
19001    fn rate_limit_serde_rejects_leading_nbsp() {
19002        // NBSP prefix — paste-from-typography footgun. Byte-scan
19003        // misses, `str::trim` silently strips it, value drifts to
19004        // `"100/s"` on next serialize.
19005        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
19006        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19007        let msg = err.to_string();
19008        assert!(
19009            msg.contains("non-ASCII Unicode whitespace character"),
19010            "expected non-ASCII whitespace diagnostic in {msg:?}"
19011        );
19012        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
19013    }
19014
19015    #[test]
19016    fn rate_limit_serde_rejects_internal_em_space() {
19017        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
19018        // paste-from-typography footgun on the `<integer>/<unit>`
19019        // shape.
19020        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
19021        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19022        let msg = err.to_string();
19023        assert!(
19024            msg.contains("non-ASCII Unicode whitespace character"),
19025            "expected non-ASCII whitespace diagnostic in {msg:?}"
19026        );
19027        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
19028    }
19029
19030    #[test]
19031    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
19032        // Positive-control pin: every ASCII-only canonical form the
19033        // renderer emits stays accepted through the new arm.
19034        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
19035            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
19036            let p: MeshPolicy = serde_json::from_str(&payload)
19037                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
19038            assert!(p.rate_limit.is_some());
19039        }
19040    }
19041
19042    #[test]
19043    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
19044        // The boundary case — `"0/s"` is the canonical form
19045        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
19046        // it at the parse layer; the downstream
19047        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
19048        // `rate == 0` at the typed-validate layer above. Pins the
19049        // partition: the leading-zero gate at the codec layer does
19050        // not poach the rate-zero semantic-validation arm at the
19051        // typed-validate layer above (a future stricter codec must
19052        // not reject `"0/s"` here, or it'd collapse the diagnostic
19053        // partitioning that lets `PolicyRateLimitZero` name the
19054        // offending typed slot).
19055        let payload = r#"{"rateLimit":"0/s"}"#;
19056        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
19057            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
19058        });
19059        let rl = policy.rate_limit.expect("rate_limit must be Some");
19060        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
19061        assert_eq!(
19062            rl.window,
19063            Duration::from_secs(1),
19064            "single-`0` magnitude with `s` unit must parse to window=1s"
19065        );
19066    }
19067
19068    #[test]
19069    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
19070        // The complementary boundary pin — every magnitude
19071        // `render` emits starts with `[1-9]` (or is the single byte
19072        // `"0"`), so the canonical-form predicate is `(len == 1) ||
19073        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
19074        // '1'` case explicitly so a future tightening of the gate
19075        // (e.g. an over-eager "no leading digit < 5" rule, or a
19076        // mistakenly anchored start-of-magnitude byte check) lands
19077        // here before the canonical-forms-iterating test would catch
19078        // it.
19079        let payload = r#"{"rateLimit":"100/s"}"#;
19080        let policy: MeshPolicy = serde_json::from_str(payload)
19081            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
19082        let rl = policy.rate_limit.expect("rate_limit must be Some");
19083        assert_eq!(
19084            rl.rate, 100,
19085            "canonical-100 magnitude must parse to rate=100"
19086        );
19087    }
19088
19089    #[test]
19090    fn rate_limit_serde_accepts_integer_canonical_forms() {
19091        // Pin the happy-path: every canonical author shape `render`
19092        // ever emits parses cleanly through the codec post-gate. The
19093        // codec's accepted set (post-gate) is exactly its emitted set
19094        // for the integer-magnitude class — same property
19095        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
19096        // gates guarantee on the peer codecs. Iterating across rate
19097        // magnitudes (including `"0"`, which the codec accepts even
19098        // though `validate_politicas` rejects `rate == 0` at the typed
19099        // layer above) closes the codec contract at the parse layer
19100        // independently of the validate layer.
19101        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
19102            for unit_lit in ["s", "m", "h"] {
19103                let lit = format!("{rate_lit}/{unit_lit}");
19104                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
19105                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
19106                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
19107                });
19108                let rl = policy.rate_limit.expect("rate_limit must be Some");
19109                assert_eq!(
19110                    rl.rate,
19111                    rate_lit.parse::<u32>().unwrap(),
19112                    "rate mismatch for {lit:?}"
19113                );
19114            }
19115        }
19116    }
19117
19118    #[test]
19119    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
19120        // The structural property the gate enforces: serialize ∘
19121        // deserialize is the identity on every canonical author shape.
19122        // Peer of `parse_byte_size`'s and `parse_duration`'s
19123        // `_round_trips_through_render_for_every_canonical_form` tests
19124        // on the rate-limit axis. Before the gate, `"+100/s"` violated
19125        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
19126        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
19127        for rate in [1u32, 100, 5000, 1_000_000] {
19128            for (window, unit) in [
19129                (Duration::from_secs(1), "s"),
19130                (Duration::from_secs(60), "m"),
19131                (Duration::from_secs(3600), "h"),
19132            ] {
19133                let policy = MeshPolicy {
19134                    rate_limit: Some(RateLimit { rate, window }),
19135                    ..Default::default()
19136                };
19137                let json = serde_json::to_string(&policy).unwrap();
19138                let expected = format!("\"{rate}/{unit}\"");
19139                assert!(
19140                    json.contains(&expected),
19141                    "expected {expected:?} in {json:?}"
19142                );
19143                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19144                assert_eq!(
19145                    back.rate_limit, policy.rate_limit,
19146                    "round-trip for {json:?}"
19147                );
19148            }
19149        }
19150    }
19151
19152    // ── self-membership cross-slot gate ──────────────────────────────
19153
19154    #[test]
19155    fn validate_no_self_membership_rejects_self_named_membro() {
19156        // An Aplicacao whose `:membros` lists its own `:nome` is a
19157        // one-node lacre-closure recursion — rejected, naming the parent.
19158        let membros = vec![
19159            membro("catalog", "^0.1"),
19160            membro("checkout", "^0.1"),
19161            membro("cart", "^0.1"),
19162        ];
19163        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
19164        assert!(
19165            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
19166            "got {err:?}"
19167        );
19168    }
19169
19170    #[test]
19171    fn validate_no_self_membership_accepts_distinct_membros() {
19172        // Positive control: distinct member names (including a member
19173        // that is itself an Aplicacao — recursive composition is valid,
19174        // MESH-COMPOSITION §V) pass the gate.
19175        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
19176        validate_no_self_membership(&membros, "checkout").unwrap();
19177    }
19178
19179    #[test]
19180    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
19181        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
19182        // `NoMembros` arm (the more-fundamental "graph must have nodes"
19183        // gate), not by this cross-slot self-edge gate. Keeping the
19184        // self-membership predicate vacuously-ok on the empty input
19185        // matches its supervisor-axis peer
19186        // (`validate_no_self_supervision_empty_children_is_ok`) and
19187        // makes the gate composable from any future call site (an M4
19188        // CR materializer's per-membros validator) without re-checking
19189        // emptiness.
19190        validate_no_self_membership(&[], "checkout").unwrap();
19191    }
19192
19193    #[test]
19194    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
19195        // Pinning the Display: the self-membership diagnostic must name
19196        // the offending caixa verbatim + the "lists itself" framing the
19197        // author can grep for, so the cluster-far failure surfaces at
19198        // build time with one-line remediation. Same diagnostic shape
19199        // as the supervisor-axis `ChildSupervisesSelf` peer.
19200        let membros = vec![membro("orquestra", "^0.1")];
19201        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
19202        let msg = err.to_string();
19203        assert!(
19204            msg.contains("orquestra"),
19205            "diagnostic must name the offending caixa nome (got: {msg:?})"
19206        );
19207        assert!(
19208            msg.contains("lists itself"),
19209            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
19210        );
19211    }
19212
19213    #[test]
19214    fn default_servico_port_constant_pins_canonical_8080_literal() {
19215        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
19216        // at the verbatim `8080` literal both consumers (the
19217        // `Entrada::port` serde default via [`default_port`] and the
19218        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
19219        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
19220        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
19221        // discipline (a085b26) on the per-renderer canonical-K8s-axis
19222        // string-constant axis: a future refactor that drifts the
19223        // constant out from under either consumer surfaces here ahead
19224        // of every per-renderer's first emission. The literal value
19225        // matches the well-known HTTP-alt port the `pleme-computeunit`
19226        // library chart already emits as its `trigger.service.port`
19227        // default — by construction the same value the substrate
19228        // assumes about every Servico's in-cluster L4 listener.
19229        assert_eq!(
19230            DEFAULT_SERVICO_PORT, 8080,
19231            "canonical Servico port literal must remain `8080` verbatim — \
19232             this is the value both the `Entrada::port` serde default and the \
19233             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
19234        );
19235    }
19236
19237    #[test]
19238    fn default_port_helper_returns_canonical_servico_port_constant() {
19239        // The bridge-arm — pins that the [`default_port`] helper
19240        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
19241        // attribute hooks routes through the lifted
19242        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
19243        // literal. A future refactor that re-introduces the `8080`
19244        // literal at the helper's return site (silently re-opening
19245        // the drift footgun this lift closed) surfaces here ahead of
19246        // every author-side `(:entrada (:host … :para …))` slot
19247        // without an explicit `:port`. Peer with the
19248        // `default_namespace_re_export_points_at_caixa_core_canonical`
19249        // pin on the caixa-mesh-side re-export axis.
19250        assert_eq!(
19251            default_port(),
19252            DEFAULT_SERVICO_PORT,
19253            "the serde-default helper must route through the lifted constant"
19254        );
19255    }
19256
19257    #[test]
19258    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
19259        // The end-to-end pin — an author-surface `(:entrada (:host …
19260        // :para …))` without an explicit `:port` slot deserializes to
19261        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
19262        // verbatim. Routes the canonical lifted constant through both
19263        // the serde-default machinery (the `#[serde(default =
19264        // "default_port")]` attribute) and the typed-value-shape
19265        // contract (the resulting [`Entrada::port`] value). A future
19266        // refactor that drifts either axis — replacing the serde
19267        // hook's helper, changing the typed slot's wire shape — would
19268        // surface here before any per-renderer's CNP / Gateway /
19269        // HTTPRoute emission consumed the drifted default.
19270        let entrada: Entrada =
19271            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
19272        assert_eq!(
19273            entrada.port, DEFAULT_SERVICO_PORT,
19274            "the serde default must materialize as the lifted canonical Servico port"
19275        );
19276    }
19277
19278    #[test]
19279    fn servico_port_min_pins_canonical_accept_set_floor() {
19280        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
19281        // verbatim `1` literal every typed `:entrada :port` acceptance
19282        // gate keys off. Peer with the
19283        // [`default_servico_port_constant_pins_canonical_8080_literal`]
19284        // discipline on the canonical-Servico-port-constant axis: a
19285        // future refactor that drifts the accept-set floor out from
19286        // under the sole consumer at [`AplicacaoSpec::validate`]'s
19287        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
19288        // every per-`:entrada` `EntradaPortZero` diagnostic. The
19289        // literal value matches the IANA-registered TCP/UDP port
19290        // space floor (`1..=65535` — port `0` is the "any ephemeral"
19291        // sentinel, not a well-defined destination the substrate's
19292        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
19293        // axis can honor).
19294        assert_eq!(
19295            SERVICO_PORT_MIN, 1,
19296            "canonical Servico port accept-set floor must remain `1` verbatim — \
19297             this is the value the `AplicacaoSpec::validate` gate at \
19298             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
19299        );
19300    }
19301
19302    #[test]
19303    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
19304        // The cross-const invariant pin — the substrate's canonical
19305        // default port must satisfy its own accept-set floor by
19306        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
19307        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
19308        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
19309        // override the operator pins through a future
19310        // `:placement :default-port` slot that lands out-of-range, a
19311        // per-edition Servico-port migration that lifted the floor
19312        // above the previous default without coordinating the pair —
19313        // would silently invalidate the serde-default emission at
19314        // every author-side `(:entrada (:host … :para …))` slot
19315        // without an explicit `:port`: the default port would fall
19316        // below the accept-set floor, the `AplicacaoSpec::validate`
19317        // gate would reject every default-carrying Aplicacao as
19318        // `EntradaPortZero`, and the substrate's typed
19319        // `(defcaixa … :kind Aplicacao)` surface would fail validate
19320        // on every Aplicacao whose author omitted `:entrada :port`
19321        // for the substrate's chosen default — a class of authoring-
19322        // surface footguns the compile-time pin structurally closes.
19323        // Peer with the
19324        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
19325        // (27f9b34) cross-const invariant pin discipline on the peer
19326        // canonical-Helm-per-values-block child-chart-enablement-toggle
19327        // axis pair.
19328        assert!(
19329            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
19330            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
19331             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
19332             every default-carrying `(:entrada (:host … :para …))` slot without an \
19333             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
19334             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
19335        );
19336    }
19337
19338    #[test]
19339    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
19340        // The gate-site pin — asserts the `AplicacaoSpec::validate`
19341        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
19342        // `EntradaPortZero` diagnostic on the below-floor input
19343        // `port: 0` (the only below-floor value the `u16` field can
19344        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
19345        // is the singleton `{0}`). A future refactor that drifts the
19346        // gate off the lifted const (silently re-introducing an
19347        // inline `if e.port == 0` byte-check) surfaces here — the
19348        // pin cannot distinguish `< 1` from `== 0` on the current
19349        // floor, but it *does* pin that the diagnostic fires on `0`
19350        // through whichever gate is wired, so any future accept-set
19351        // floor migration (a hypothetical unprivileged-only
19352        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
19353        // update this test alongside the const declaration —
19354        // structurally guaranteeing the gate + accept-set + pin
19355        // trio move together. Peer with the
19356        // [`rejects_zero_entrada_port`] behavioral pin on the same
19357        // per-`:entrada :port` axis — that pin asserts the pre-lift
19358        // behavioral contract (`port: 0` → `EntradaPortZero`); this
19359        // pin adds the structural link to the lifted floor const.
19360        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
19361        let mut s = three_member_spec();
19362        s.entrada.as_mut().unwrap().port = 0;
19363        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19364    }
19365
19366    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
19367
19368    #[test]
19369    fn membro_serde_keys_match_lifted_membro_key_consts() {
19370        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
19371        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
19372        // name the exact camelCase JSON keys the
19373        // `#[serde(rename_all = "camelCase")]` attribute on
19374        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
19375        // that each canonical byte-sequence appears verbatim in the
19376        // JSON — a future accidental `rename_all = "snake_case"` /
19377        // `"kebab-case"` / verbatim-field-name flip at the derive
19378        // attribute (any of which would silently break every downstream
19379        // JSON consumer that reaches for one of the two consts via
19380        // `Value::get(...)`) surfaces here as a build-time test failure
19381        // at `aplicacao.rs`, not as an apply-time
19382        // `.get(<stale-canonical-const>)` returning `None` far from the
19383        // derive-attr drift's commit. Peer with the sibling
19384        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
19385        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
19386        // same discipline the SupervisorSpec top-level lift established,
19387        // extended here to the M3 [`Membro`] per-`:membros` axis.
19388        let m = Membro {
19389            caixa: "catalog".into(),
19390            versao: "^0.1".into(),
19391        };
19392        let json = serde_json::to_string(&m).unwrap();
19393        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
19394            let quoted = format!("\"{key}\"");
19395            assert!(
19396                json.contains(&quoted),
19397                "serialized Membro must carry the lifted MEMBRO_KEY_* \
19398                 byte-sequence {quoted} verbatim in the JSON emission \
19399                 (got: {json})",
19400            );
19401        }
19402    }
19403
19404    #[test]
19405    fn membro_key_consts_are_pairwise_distinct() {
19406        // Cross-axis drift-detection pin: a future collapse of the two
19407        // canonical [`Membro`] per-entry byte-strings onto the same
19408        // value (e.g. an accidental copy-paste flip of
19409        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
19410        // silently reroute every downstream probe on one axis onto the
19411        // sibling axis's overlay entry and pass every propagation-probe
19412        // test that expected only the stale axis's value. Peer of the
19413        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
19414        // (40cc4e5).
19415        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
19416        for (i, a) in all.iter().enumerate() {
19417            for b in all.iter().skip(i + 1) {
19418                assert_ne!(
19419                    a, b,
19420                    "MEMBRO_KEY_* consts must be pairwise-distinct \
19421                     canonical byte-sequences — got `{a}` == `{b}`",
19422                );
19423            }
19424        }
19425    }
19426
19427    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
19428    //    URL-path fallback resolver every HTTPRoute-aware renderer
19429    //    reaching for a per-rule path-list resolution routes through.
19430    //    The four pin tests below fix the four-way accept-set the
19431    //    resolver must always honor: (:paths-non-empty-verbatim,
19432    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
19433    //    :paths-preserves-order-across-multiple-entries) — drift on any
19434    //    arm surfaces at caixa-core build time rather than at cluster-
19435    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
19436    //    sibling `:politicas` typed-primitive dispatch axis.
19437
19438    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
19439        Entrada {
19440            host: "example.com".into(),
19441            para: "cart".into(),
19442            paths: paths.into_iter().map(String::from).collect(),
19443            port: DEFAULT_SERVICO_PORT,
19444        }
19445    }
19446
19447    #[test]
19448    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
19449        // The typed `:entrada :paths` slot carries an author-declared
19450        // list — the resolver returns each entry verbatim, no
19451        // catch-all substitution. The canonical "author declared
19452        // paths, honor them verbatim" arm of the path-list dispatch.
19453        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19454        assert_eq!(
19455            e.resolved_paths(),
19456            vec!["/api/cart", "/api/products"],
19457            "resolved_paths must return each `:entrada :paths` entry \
19458             verbatim when the typed slot is non-empty (got {:?})",
19459            e.resolved_paths(),
19460        );
19461    }
19462
19463    #[test]
19464    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
19465        // Empty `:entrada :paths` slot — the resolver substitutes the
19466        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19467        // catch-all fallback verbatim. Pins the empty-arm of the
19468        // resolver's four-way accept-set against a future silent
19469        // detour that returned an empty Vec (which would emit an
19470        // HTTPRoute with zero rules — silently dropping every
19471        // external `:entrada` flow at admission time), routed to a
19472        // different fallback shape, or dropped the catch-all
19473        // altogether.
19474        let e = entrada_with_paths(vec![]);
19475        assert_eq!(
19476            e.resolved_paths(),
19477            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19478            "resolved_paths on empty `:entrada :paths` must fall back \
19479             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
19480             all — got {:?}",
19481            e.resolved_paths(),
19482        );
19483    }
19484
19485    #[test]
19486    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
19487        // Single-entry `:entrada :paths` — the resolver returns the
19488        // single declared path verbatim, NOT the catch-all fallback
19489        // (author declared a path, honor it — the empty-arm and the
19490        // len-1 arm are semantically distinct axes of the resolver's
19491        // accept-set). Pins that the resolver treats "author declared
19492        // one path" as authored input, not as the empty case.
19493        let e = entrada_with_paths(vec!["/api/only"]);
19494        assert_eq!(
19495            e.resolved_paths(),
19496            vec!["/api/only"],
19497            "resolved_paths on single-entry `:entrada :paths` must \
19498             return the declared path verbatim, NOT the catch-all \
19499             fallback (got {:?})",
19500            e.resolved_paths(),
19501        );
19502    }
19503
19504    #[test]
19505    fn resolved_paths_preserves_author_declared_order() {
19506        // The `:entrada :paths` list is author-ordered — the resolver
19507        // preserves the author's declaration order verbatim, since
19508        // per-rule dispatch order at the K8s Gateway API HTTPRoute
19509        // consumer is significant (first-match-wins under the
19510        // path-prefix matcher). Pins against a future silent
19511        // re-sort / dedup / normalize detour that reordered author
19512        // input.
19513        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
19514        assert_eq!(
19515            e.resolved_paths(),
19516            vec!["/z/last", "/a/first", "/m/mid"],
19517            "resolved_paths must preserve author-declared `:entrada \
19518             :paths` order verbatim — got {:?}",
19519            e.resolved_paths(),
19520        );
19521    }
19522
19523    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
19524    //    slot `&[String]` slice accessor every per-`:entrada` consumer
19525    //    that must see the author's declaration verbatim (not the
19526    //    fallback-applied projection the sibling `resolved_paths`
19527    //    returns) routes through. The three pin tests below fix the
19528    //    accept-set the accessor must honor: (:non-empty-byte-equal,
19529    //    :empty-projects-empty-slice, :preserves-author-declared-order)
19530    //    — drift on any arm surfaces at caixa-core build time rather
19531    //    than at cluster-apply time. Peer discipline with the sibling
19532    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
19533    //    peer M3 mesh-slot `Vec<String>`-carry axis.
19534
19535    #[test]
19536    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
19537        // Byte-equal pin: [`Entrada::paths`] must project the raw
19538        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
19539        // slice borrowed from the typed slot's own [`Vec<String>`]
19540        // storage — no re-ordering, no dedup, no per-entry normalization,
19541        // no fallback substitution (the fallback-applying projection is
19542        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
19543        // a future silent detour that re-normalized the list, dropped
19544        // duplicates the [`AplicacaoSpec::validate`]
19545        // `EntradaPathDuplicate` refusal already rejects at build time,
19546        // or (most severe) accidentally routed through the fallback-
19547        // applying sibling and returned the substrate catch-all when
19548        // the author declared an empty list — collapsing the raw-slot
19549        // and fallback-applied axes into one and breaking the
19550        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
19551        //
19552        // Peer of the sibling
19553        // [`Placement::clusters`]-shape byte-equal pin
19554        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19555        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
19556        let fixtures: Vec<Vec<String>> = vec![
19557            Vec::new(),
19558            vec!["/api/cart".into()],
19559            vec!["/api/cart".into(), "/api/products".into()],
19560            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
19561        ];
19562        for paths in fixtures {
19563            let e = Entrada {
19564                host: "example.com".into(),
19565                para: "cart".into(),
19566                paths: paths.clone(),
19567                port: DEFAULT_SERVICO_PORT,
19568            };
19569            assert_eq!(
19570                e.paths(),
19571                paths.as_slice(),
19572                "Entrada::paths must return :entrada :paths verbatim \
19573                 (got {:?}, expected {:?})",
19574                e.paths(),
19575                paths.as_slice(),
19576            );
19577            assert_eq!(
19578                e.paths(),
19579                e.paths.as_slice(),
19580                "Entrada::paths accessor and .paths.as_slice() field \
19581                 access must byte-equal — the accessor is the substrate-\
19582                 primitive typed dispatch every downstream per-`:entrada` \
19583                 raw-slot path-list consumer must route through",
19584            );
19585            assert_eq!(
19586                e.paths().len(),
19587                e.paths.len(),
19588                "Entrada::paths().len() must byte-equal self.paths.len() \
19589                 — a length drift would silently split the paired \
19590                 pre-flight cascade-head `.is_empty()` probe input in \
19591                 the sibling [`Entrada::resolved_paths`] resolver from \
19592                 the per-entry validate loop's traversal input in \
19593                 [`AplicacaoSpec::validate`]",
19594            );
19595        }
19596    }
19597
19598    #[test]
19599    fn resolved_paths_reads_through_lifted_paths_accessor() {
19600        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
19601        // pre-flight `.paths().is_empty()` cascade-head probe (which
19602        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19603        // catch-all fallback arm when the accessor projects the empty
19604        // slice) and the per-entry `.paths().iter().map(String::as_str)`
19605        // projection (which must reach every entry in the same order
19606        // the accessor projects, so the sibling
19607        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
19608        // per-entry projection stay in lockstep by construction) must
19609        // both key off the lifted accessor. Pins the two-site coherence
19610        // by exercising each production consumer end-to-end: (1) the
19611        // catch-all-fallback arm under the empty slice, (2) the
19612        // author-declared-verbatim arm under a two-entry cohort whose
19613        // per-entry projection must byte-equal the input's per-entry
19614        // author-declared paths in the author's declared order.
19615        //
19616        // Peer of the sibling M3
19617        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
19618        // `validate_placement_reads_through_lifted_clusters_accessor`
19619        // on the sibling `Placement::clusters` reader-site convergence.
19620        let empty = entrada_with_paths(vec![]);
19621        assert_eq!(
19622            empty.resolved_paths(),
19623            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19624            "resolved_paths on empty :entrada :paths must trip the \
19625             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
19626             catch-all fallback — routing through the lifted paths() \
19627             accessor must not silently drop the fallback arm",
19628        );
19629
19630        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19631        assert_eq!(
19632            declared.resolved_paths(),
19633            vec!["/api/cart", "/api/products"],
19634            "resolved_paths on non-empty :entrada :paths must return each \
19635             entry verbatim in the author's declared order — routing \
19636             through the lifted paths() accessor must not silently \
19637             reorder or drop entries",
19638        );
19639        // Byte-equal pin against the raw-slot accessor to keep the
19640        // fallback-applying resolver's per-entry projection input in
19641        // lockstep with the raw-slot accessor's projection.
19642        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
19643        assert_eq!(
19644            declared.resolved_paths(),
19645            raw_projected,
19646            "resolved_paths non-empty projection must byte-equal the \
19647             lifted paths() accessor's per-entry String::as_str projection \
19648             — the two projections share the same input slice by \
19649             construction, so any drift here would surface a silent \
19650             re-ordering / dedup / normalization detour in the resolver",
19651        );
19652    }
19653
19654    #[test]
19655    fn validate_reads_through_lifted_entrada_paths_accessor() {
19656        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
19657        // per-entry value-shape gate's `for p in e.paths()` traversal
19658        // (which must reach every entry in the same order the accessor
19659        // projects, so both the per-entry `EntradaPathEmpty` /
19660        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
19661        // the duplicate-detection HashSet insert that trips
19662        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
19663        // projection) must route through the lifted accessor. Pins the
19664        // coherence by exercising each production consumer end-to-end:
19665        // (1) the `EntradaPathEmpty` refusal fires on the second entry
19666        // of a two-entry cohort whose head is valid but tail is empty
19667        // (which requires the loop to reach the second entry through
19668        // the accessor), and (2) the `EntradaPathDuplicate` refusal
19669        // fires on the second entry of a two-entry cohort that shares
19670        // a path (which requires the loop to reach both entries — a
19671        // first-entry-only projection would silently pass since the
19672        // dedup HashSet has room for the first insert).
19673        //
19674        // Peer of the sibling
19675        // `validate_placement_reads_through_lifted_clusters_accessor`
19676        // on the sibling `Placement::clusters` reader-site convergence.
19677        let base = crate::AplicacaoSpec {
19678            membros: vec![crate::Membro {
19679                caixa: "cart".into(),
19680                versao: "^0.1".into(),
19681            }],
19682            contratos: Vec::new(),
19683            politicas: crate::MeshPolicy::default(),
19684            placement: crate::Placement {
19685                estrategia: crate::PlacementStrategy::SingleNode,
19686                clusters: vec!["rio".into()],
19687                shard_key: None,
19688                affinity: None,
19689            },
19690            entrada: Some(Entrada {
19691                host: "example.com".into(),
19692                para: "cart".into(),
19693                paths: vec!["/api/cart".into(), String::new()],
19694                port: DEFAULT_SERVICO_PORT,
19695            }),
19696        };
19697        assert_eq!(
19698            base.validate(),
19699            Err(crate::AplicacaoError::EntradaPathEmpty),
19700            "validate must trip EntradaPathEmpty on the second entry of \
19701             a two-entry cohort — routing through the lifted paths() \
19702             accessor must not silently short-circuit the loop at the \
19703             valid head entry",
19704        );
19705
19706        let mut dup = base;
19707        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
19708        assert_eq!(
19709            dup.validate(),
19710            Err(crate::AplicacaoError::EntradaPathDuplicate {
19711                path: "/api/cart".into(),
19712            }),
19713            "validate must trip EntradaPathDuplicate on the second entry \
19714             of a two-entry cohort that shares a path — routing through \
19715             the lifted paths() accessor must not silently short-circuit \
19716             the dedup HashSet insert at the first entry",
19717        );
19718    }
19719
19720    // ── Entrada::hostname / Entrada::hostnames — the substrate-
19721    //    canonical per-`:entrada` DNS-hostname resolver pair every
19722    //    Gateway-API-aware renderer reaching for a per-listener
19723    //    singular `hostname:` filter (Gateway) or a per-route plural
19724    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
19725    //    The three pin tests below fix the two-way accept-set the pair
19726    //    must always honor: (:singular-byte-equal-to-host,
19727    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
19728    //    on any arm surfaces at caixa-core build time rather than at
19729    //    cluster-apply time when the API server refuses the HTTPRoute
19730    //    for non-intersecting hostname filters. Peer discipline with
19731    //    the sibling `resolved_paths` accept-set pin block above on the
19732    //    per-`:entrada` path-list resolver axis.
19733
19734    fn entrada_with_host(host: &str) -> Entrada {
19735        Entrada {
19736            host: host.into(),
19737            para: "cart".into(),
19738            paths: Vec::new(),
19739            port: DEFAULT_SERVICO_PORT,
19740        }
19741    }
19742
19743    #[test]
19744    fn hostname_returns_entrada_host_byte_equal() {
19745        // The canonical singular-axis pin: [`Entrada::hostname`] must
19746        // return the `:entrada :host` field byte-for-byte, borrowed
19747        // from the typed slot's own [`String`] storage. Pins against a
19748        // future silent detour that re-normalized the host (an
19749        // accidental `.to_lowercase()` — validate_entrada_host already
19750        // enforces lowercase, so any re-normalization is redundant + a
19751        // drift surface between the validator and the accessor), a
19752        // trailing-`.` fully-qualified DNS shape substitution, or a
19753        // Punycode round-trip that lowered a Unicode host through IDNA.
19754        let e = entrada_with_host("checkout.quero.cloud");
19755        assert_eq!(
19756            e.hostname(),
19757            "checkout.quero.cloud",
19758            "Entrada::hostname must return :entrada :host verbatim \
19759             (got {:?})",
19760            e.hostname(),
19761        );
19762        assert_eq!(
19763            e.hostname(),
19764            e.host.as_str(),
19765            "Entrada::hostname must byte-equal the .host field access",
19766        );
19767    }
19768
19769    #[test]
19770    fn hostnames_returns_singleton_of_hostname_accessor() {
19771        // The pair-invariant pin: [`Entrada::hostnames`] must always
19772        // return exactly `vec![hostname()]` — the singleton list whose
19773        // sole entry is the substrate's canonical per-`:entrada`
19774        // singular hostname. Pins the two-consumer coherence axis: the
19775        // Gateway listener's singular `hostname:` filter and the
19776        // HTTPRoute's plural `spec.hostnames[]` filter list must
19777        // agree, else the Gateway API v1.x conformance layer rejects
19778        // the HTTPRoute at attach time with
19779        // `Accepted:False/NoMatchingParent` (the parent Gateway's
19780        // listener hostname doesn't intersect the route's hostname
19781        // filter list) — a divergence whose apply-time symptom is far
19782        // from any single-site commit and never surfaces in the
19783        // emitted YAML. Pinning the pair-invariant here makes any
19784        // future accidental split (an accidental `.to_string() + "."`
19785        // trailing-`.` on the plural side that didn't land on the
19786        // singular side, an accidental prefix stripping on one axis,
19787        // an accidental wildcard prepend the SNI fan-out overlay
19788        // authors on the plural side without a paired singular
19789        // migration) trip at caixa-core build time.
19790        let e = entrada_with_host("checkout.quero.cloud");
19791        assert_eq!(
19792            e.hostnames(),
19793            vec![e.hostname()],
19794            "Entrada::hostnames must return `vec![hostname()]` under \
19795             the pair-invariant — got {:?} vs. singleton {:?}",
19796            e.hostnames(),
19797            vec![e.hostname()],
19798        );
19799    }
19800
19801    #[test]
19802    fn hostnames_is_singleton_under_single_host_author_surface() {
19803        // The singleton-shape pin: under today's single-hostname-per-
19804        // `:entrada` author surface (the `:host` slot is a single
19805        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
19806        // must always return a list of length exactly one. Pins
19807        // against a future silent detour that returned an empty list
19808        // (which would emit an HTTPRoute with `spec.hostnames: []` —
19809        // matching every incoming Host header regardless of the
19810        // Aplicacao's declared ingress apex, silently over-matching
19811        // every foreign VirtualHost the parent Gateway also fronts) or
19812        // a duplicated entry (which the Gateway API v1.x parser
19813        // accepts as a `[]-length-2 list of equal hostnames]` but
19814        // whose semantics differ from the intended singleton). The
19815        // author-surface extension point ("a future `:entrada
19816        // :alt-hosts` list overlay" the docstring names) is the sole
19817        // future axis that flips this pin — that migration will re-
19818        // author this test to pin the new plural cardinality.
19819        let e = entrada_with_host("checkout.quero.cloud");
19820        assert_eq!(
19821            e.hostnames().len(),
19822            1,
19823            "Entrada::hostnames must be a singleton under today's \
19824             single-hostname-per-`:entrada` author surface — got \
19825             length {}: {:?}",
19826            e.hostnames().len(),
19827            e.hostnames(),
19828        );
19829    }
19830
19831    // ── Entrada::destination — the substrate-canonical per-`:entrada`
19832    //    destination-Servico scalar accessor every Gateway-API
19833    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
19834    //    discriminator arg (HTTPRoute name composer) or a per-rule
19835    //    `backendRefs[0].name` axis routes through. The two pin tests
19836    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
19837    //    either arm surfaces at caixa-core build time rather than at
19838    //    cluster-apply time when an HTTPRoute's `metadata.name` and
19839    //    `backendRefs[]` silently disagree on which destination Servico
19840    //    the ingress fronts. Peer discipline with the sibling
19841    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
19842    //    blocks above on the per-`:entrada` path-list / DNS-hostname
19843    //    resolver axes.
19844
19845    #[test]
19846    fn destination_returns_entrada_para_byte_equal() {
19847        // The canonical destination-scalar pin: [`Entrada::destination`]
19848        // must return the `:entrada :para` field byte-for-byte, borrowed
19849        // from the typed slot's own [`String`] storage. Pins against a
19850        // future silent detour that re-normalized the destination (an
19851        // accidental `.to_lowercase()` — the destination Servico is
19852        // already validated as a DNS-1123 label upstream, so any
19853        // re-normalization is redundant + a drift surface between the
19854        // validator and the accessor), a namespace-prefix rewrite (an
19855        // accidental `format!("{namespace}/{para}")` per-CR fully-
19856        // qualified rewrite that didn't land on the peer axis), or a
19857        // per-cluster suffix stamp the operator authors on one
19858        // consumer without the other.
19859        for para in ["cart", "checkout", "catalog", "orders-v2"] {
19860            let e = Entrada {
19861                host: "checkout.quero.cloud".into(),
19862                para: para.into(),
19863                paths: Vec::new(),
19864                port: DEFAULT_SERVICO_PORT,
19865            };
19866            assert_eq!(
19867                e.destination(),
19868                para,
19869                "Entrada::destination must return :entrada :para verbatim \
19870                 (got {:?}, expected {para:?})",
19871                e.destination(),
19872            );
19873            assert_eq!(
19874                e.destination(),
19875                e.para.as_str(),
19876                "Entrada::destination must byte-equal the .para field access",
19877            );
19878        }
19879    }
19880
19881    #[test]
19882    fn destination_borrows_from_entrada_para_storage() {
19883        // The borrow-not-copy pin: [`Entrada::destination`] must
19884        // return a `&str` slice that borrows from the typed slot's
19885        // own [`String`] storage — same-address invariant with
19886        // `entrada.para.as_str()`. Pins against a future silent detour
19887        // that allocated a fresh `String` (`self.para.clone()` in the
19888        // body would type-check but silently drop the borrow, and
19889        // every downstream consumer that assumed the returned slice
19890        // outlives `&self` would break on a stale-reference use-after-
19891        // free). Peer with the sibling `hostname_returns_entrada_
19892        // host_byte_equal` on the singular-DNS-hostname axis.
19893        let e = entrada_with_host("checkout.quero.cloud");
19894        let dest = e.destination();
19895        let para_slice = e.para.as_str();
19896        assert_eq!(
19897            dest.as_ptr(),
19898            para_slice.as_ptr(),
19899            "Entrada::destination must borrow from the .para String's \
19900             backing storage — a fresh allocation here means the \
19901             accessor no longer names the substrate-primitive typed \
19902             dispatch and every downstream consumer would silently \
19903             carry a detached copy",
19904        );
19905        assert_eq!(
19906            dest.len(),
19907            para_slice.len(),
19908            "Entrada::destination and .para.as_str() must byte-equal in \
19909             length as well as in address",
19910        );
19911    }
19912
19913    #[test]
19914    fn port_returns_entrada_port_verbatim_across_permutations() {
19915        // The canonical L4-port-scalar pin: [`Entrada::port`] must
19916        // return the `:entrada :port` field verbatim as a `u16` across
19917        // every author-declared value in the validated accept-set
19918        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
19919        // silent detour that clamped the port (an accidental
19920        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
19921        // land on the peer [`AplicacaoSpec::port_for_destination`]
19922        // resolver), rewrote it through a per-cluster port-remap table
19923        // the operator authors on one consumer without the other, or
19924        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
19925        // serde-default value (which would silently collapse the
19926        // distinction between "author explicitly declared `:port 8080`"
19927        // and "author omitted the slot and inherited the default" the
19928        // future per-cluster override slot depends on). Peer with the
19929        // sibling `destination_returns_entrada_para_byte_equal` +
19930        // `hostname_returns_entrada_host_byte_equal` pins on the
19931        // per-`:entrada` `&str` scalar axes.
19932        for port in [
19933            SERVICO_PORT_MIN,
19934            DEFAULT_SERVICO_PORT,
19935            8443u16,
19936            9090u16,
19937            u16::MAX,
19938        ] {
19939            let e = Entrada {
19940                host: "checkout.quero.cloud".into(),
19941                para: "cart".into(),
19942                paths: Vec::new(),
19943                port,
19944            };
19945            assert_eq!(
19946                e.port(),
19947                port,
19948                "Entrada::port must return :entrada :port verbatim \
19949                 (got {}, expected {port})",
19950                e.port(),
19951            );
19952            assert_eq!(
19953                e.port(),
19954                e.port,
19955                "Entrada::port accessor and .port field access must \
19956                 byte-equal — the accessor is the substrate-primitive \
19957                 typed dispatch every downstream L4-port consumer must \
19958                 route through",
19959            );
19960        }
19961    }
19962
19963    #[test]
19964    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
19965        // Two-consumer coherence pin: the
19966        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
19967        // (which reads through [`Entrada::port`] to compare against
19968        // [`SERVICO_PORT_MIN`]) and the
19969        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
19970        // through [`Entrada::port`] to emit the per-destination
19971        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
19972        // lifted accessor, so any future rebrand on the typed slot's
19973        // reader shape lands at exactly one place. Pins the two-site
19974        // coherence by exercising a below-floor port through validate
19975        // (which must reject) and a validated in-accept-set port through
19976        // port_for_destination (which must emit the same value the
19977        // accessor returns).
19978        let mut spec = three_member_spec();
19979        if let Some(e) = spec.entrada.as_mut() {
19980            e.port = 0;
19981        }
19982        assert_eq!(
19983            spec.validate().unwrap_err(),
19984            AplicacaoError::EntradaPortZero,
19985            "validate must reject `:entrada :port 0` through the lifted \
19986             Entrada::port accessor — port zero lies below \
19987             SERVICO_PORT_MIN and the validator routes through port() \
19988             to name the floor",
19989        );
19990
19991        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
19992            let mut spec = three_member_spec();
19993            if let Some(e) = spec.entrada.as_mut() {
19994                e.port = port;
19995            }
19996            spec.validate().expect(
19997                "entrada with in-accept-set :port must validate — the \
19998                 structural-floor gate reads through Entrada::port",
19999            );
20000            let entrada_ref = spec.entrada().expect(":entrada present");
20001            assert_eq!(
20002                spec.port_for_destination(entrada_ref.destination()),
20003                entrada_ref.port(),
20004                "port_for_destination(entrada.destination()) must equal \
20005                 entrada.port() — the two consumers of the per-:entrada \
20006                 L4-port axis (validator, per-destination resolver) both \
20007                 route through Entrada::port",
20008            );
20009        }
20010    }
20011
20012    #[test]
20013    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
20014        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
20015        // must return the `:contratos :de` field byte-for-byte, borrowed
20016        // from the typed slot's own [`String`] storage. Peer of the
20017        // sibling `destination_returns_entrada_para_byte_equal` pin on
20018        // the per-`:entrada` axis — same "the substrate-primitive
20019        // accessor must byte-equal the raw field access verbatim across
20020        // every author-declared value" discipline extended to the
20021        // per-`:contratos` caller arm. Pins against a future silent
20022        // detour that re-normalized the caller (an accidental
20023        // `.to_lowercase()` — every `:contratos :de` is validated as a
20024        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
20025        // re-normalization is redundant + a drift surface between the
20026        // validator and the accessor), a namespace-prefix rewrite (an
20027        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
20028        // rewrite that didn't land on the peer axis), or a per-cluster
20029        // suffix stamp the operator authors on one consumer without the
20030        // other.
20031        for de in ["cart", "checkout", "catalog", "orders-v2"] {
20032            let c = WitContract {
20033                de: de.into(),
20034                para: "downstream".into(),
20035                wit: "wasi:http/proxy".into(),
20036                endpoint: Some("/lookup".into()),
20037                subject: None,
20038                slot: None,
20039            };
20040            assert_eq!(
20041                c.source(),
20042                de,
20043                "WitContract::source must return :contratos :de verbatim \
20044                 (got {:?}, expected {de:?})",
20045                c.source(),
20046            );
20047            assert_eq!(
20048                c.source(),
20049                c.de.as_str(),
20050                "WitContract::source must byte-equal the .de field access",
20051            );
20052        }
20053    }
20054
20055    #[test]
20056    fn wit_contract_source_borrows_from_de_storage() {
20057        // The borrow-not-copy pin: [`WitContract::source`] must return a
20058        // `&str` slice that borrows from the typed slot's own [`String`]
20059        // storage — same-address invariant with `c.de.as_str()`. Pins
20060        // against a future silent detour that allocated a fresh `String`
20061        // (`self.de.clone()` in the body would type-check but silently
20062        // drop the borrow, and every downstream consumer that assumed
20063        // the returned slice outlives `&self` would break on a stale-
20064        // reference use-after-free). Peer of the sibling
20065        // `destination_borrows_from_entrada_para_storage` on the
20066        // per-`:entrada` axis.
20067        let c = WitContract {
20068            de: "cart".into(),
20069            para: "catalog".into(),
20070            wit: "wasi:http/proxy".into(),
20071            endpoint: Some("/lookup".into()),
20072            subject: None,
20073            slot: None,
20074        };
20075        let src = c.source();
20076        let de_slice = c.de.as_str();
20077        assert_eq!(
20078            src.as_ptr(),
20079            de_slice.as_ptr(),
20080            "WitContract::source must borrow from the .de String's \
20081             backing storage — a fresh allocation here means the \
20082             accessor no longer names the substrate-primitive typed \
20083             dispatch and every downstream consumer would silently \
20084             carry a detached copy",
20085        );
20086        assert_eq!(
20087            src.len(),
20088            de_slice.len(),
20089            "WitContract::source and .de.as_str() must byte-equal in \
20090             length as well as in address",
20091        );
20092    }
20093
20094    #[test]
20095    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
20096        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
20097        // must return the `:contratos :para` field byte-for-byte,
20098        // borrowed from the typed slot's own [`String`] storage. Peer of
20099        // the sibling `destination_returns_entrada_para_byte_equal` on
20100        // the per-`:entrada` axis — both accessors name "the destination-
20101        // Servico byte-string" concept on their respective mesh-slot
20102        // atoms (per-ingress apex vs. per-typed-edge callee) and both
20103        // must project the underlying `.para` field verbatim so every
20104        // downstream renderer that composes them with peer accessors
20105        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
20106        // per-edge L4 port emit site) reads the same byte-string the
20107        // author declared.
20108        for para in ["catalog", "payment", "orders", "inventory-v3"] {
20109            let c = WitContract {
20110                de: "cart".into(),
20111                para: para.into(),
20112                wit: "wasi:http/proxy".into(),
20113                endpoint: Some("/lookup".into()),
20114                subject: None,
20115                slot: None,
20116            };
20117            assert_eq!(
20118                c.destination(),
20119                para,
20120                "WitContract::destination must return :contratos :para \
20121                 verbatim (got {:?}, expected {para:?})",
20122                c.destination(),
20123            );
20124            assert_eq!(
20125                c.destination(),
20126                c.para.as_str(),
20127                "WitContract::destination must byte-equal the .para \
20128                 field access",
20129            );
20130        }
20131    }
20132
20133    #[test]
20134    fn wit_contract_destination_borrows_from_para_storage() {
20135        // The borrow-not-copy pin: [`WitContract::destination`] must
20136        // return a `&str` slice that borrows from the typed slot's own
20137        // [`String`] storage — same-address invariant with
20138        // `c.para.as_str()`. Peer of the sibling
20139        // `destination_borrows_from_entrada_para_storage` on the
20140        // per-`:entrada` axis.
20141        let c = WitContract {
20142            de: "cart".into(),
20143            para: "catalog".into(),
20144            wit: "wasi:http/proxy".into(),
20145            endpoint: Some("/lookup".into()),
20146            subject: None,
20147            slot: None,
20148        };
20149        let dest = c.destination();
20150        let para_slice = c.para.as_str();
20151        assert_eq!(
20152            dest.as_ptr(),
20153            para_slice.as_ptr(),
20154            "WitContract::destination must borrow from the .para \
20155             String's backing storage — a fresh allocation here means \
20156             the accessor no longer names the substrate-primitive typed \
20157             dispatch and every downstream consumer would silently \
20158             carry a detached copy",
20159        );
20160        assert_eq!(
20161            dest.len(),
20162            para_slice.len(),
20163            "WitContract::destination and .para.as_str() must byte-equal \
20164             in length as well as in address",
20165        );
20166    }
20167
20168    #[test]
20169    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
20170        // The canonical per-`:contratos` WIT-world-reference scalar pin:
20171        // [`WitContract::world_ref`] must return the `:contratos :wit`
20172        // field byte-for-byte, borrowed from the typed slot's own
20173        // [`String`] storage. Sibling of the peer per-`:contratos`
20174        // [`WitContract::source`] / [`WitContract::destination`]
20175        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
20176        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
20177        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
20178        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
20179        // "the substrate-primitive accessor must byte-equal the raw
20180        // field access verbatim across every author-declared value"
20181        // discipline extended to the per-`:contratos` WIT-world arm.
20182        // Pins against a future silent detour that re-canonicalized the
20183        // WIT world reference (an accidental `.to_lowercase()` pass that
20184        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
20185        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
20186        // gate is already lowercase-prefixed so any re-normalization is
20187        // redundant + a drift surface between the validator and the
20188        // accessor), an M4-promotion-shape rewrite that formatted a
20189        // typed WIT-world enum through [`Display`] and silently drifted
20190        // the printer output from the source `caixa.lisp`, or a per-
20191        // cluster WIT-alias rewrite that didn't land on the peer field-
20192        // access sites. Five values sweep the shape-dispatch accept-set
20193        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
20194        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
20195        // `wasi:keyvalue/`).
20196        for (wit, endpoint, subject, slot) in [
20197            ("wasi:http/proxy", Some("/lookup"), None, None),
20198            ("http:proxy", Some("/health"), None, None),
20199            ("nats:pub-sub", None, Some("orders.paid"), None),
20200            ("kafka:events", None, Some("checkout-events"), None),
20201            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
20202        ] {
20203            let c = WitContract {
20204                de: "cart".into(),
20205                para: "downstream".into(),
20206                wit: wit.into(),
20207                endpoint: endpoint.map(str::to_string),
20208                subject: subject.map(str::to_string),
20209                slot: slot.map(str::to_string),
20210            };
20211            assert_eq!(
20212                c.world_ref(),
20213                wit,
20214                "WitContract::world_ref must return :contratos :wit \
20215                 verbatim (got {:?}, expected {wit:?})",
20216                c.world_ref(),
20217            );
20218            assert_eq!(
20219                c.world_ref(),
20220                c.wit.as_str(),
20221                "WitContract::world_ref must byte-equal the .wit field \
20222                 access",
20223            );
20224        }
20225    }
20226
20227    #[test]
20228    fn wit_contract_world_ref_borrows_from_wit_storage() {
20229        // The borrow-not-copy pin: [`WitContract::world_ref`] must
20230        // return a `&str` slice that borrows from the typed slot's own
20231        // [`String`] storage — same-address invariant with
20232        // `c.wit.as_str()`. Pins against a future silent detour that
20233        // allocated a fresh `String` (`self.wit.clone()` in the body
20234        // would type-check but silently drop the borrow, and every
20235        // downstream consumer that assumed the returned slice outlives
20236        // `&self` would break on a stale-reference use-after-free — the
20237        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
20238        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
20239        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
20240        // / [`is_pubsub`][WitContract::is_pubsub] /
20241        // [`is_store`][WitContract::is_store] methods route through —
20242        // each borrow from the WitContract's own storage and each would
20243        // silently misbehave if this accessor produced a detached copy).
20244        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
20245        // [`WitContract::destination`] and per-`:entrada`
20246        // [`Entrada::destination`] / [`Entrada::hostname`] and
20247        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
20248        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
20249        let c = WitContract {
20250            de: "cart".into(),
20251            para: "catalog".into(),
20252            wit: "wasi:http/proxy".into(),
20253            endpoint: Some("/lookup".into()),
20254            subject: None,
20255            slot: None,
20256        };
20257        let world = c.world_ref();
20258        let wit_slice = c.wit.as_str();
20259        assert_eq!(
20260            world.as_ptr(),
20261            wit_slice.as_ptr(),
20262            "WitContract::world_ref must borrow from the .wit String's \
20263             backing storage — a fresh allocation here means the \
20264             accessor no longer names the substrate-primitive typed \
20265             dispatch and every downstream consumer would silently carry \
20266             a detached copy",
20267        );
20268        assert_eq!(
20269            world.len(),
20270            wit_slice.len(),
20271            "WitContract::world_ref and .wit.as_str() must byte-equal in \
20272             length as well as in address",
20273        );
20274    }
20275
20276    #[test]
20277    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
20278        // Sibling-triple invariant pin composing all three per-`:contratos`
20279        // substrate-primitive typed dispatches — [`WitContract::source`]
20280        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
20281        // [`WitContract::world_ref`] — at the joint
20282        // `(source(), destination(), world_ref())` call shape every
20283        // renderer that fans on per-edge caller-callee-shape identity
20284        // keys off. The invariant, evaluated per-contract:
20285        //
20286        //   (c.source(), c.destination(), c.world_ref())
20287        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
20288        //
20289        // Closes the last unlifted per-`:contratos` scalar axis — every
20290        // downstream consumer that reads the triple now routes through
20291        // exactly three typed dispatches on the substrate primitive,
20292        // not two typed + one open-coded field access. A future refactor
20293        // that silently split any one accessor's projection (an
20294        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
20295        // canonicalization that didn't reach the peer `source`/
20296        // `destination` arms, an accidental `source()` per-cluster
20297        // caller-alias rewrite that didn't land on the `world_ref` peer)
20298        // surfaces at caixa-core build time. Peer of the sibling per-
20299        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
20300        // per-`:entrada` `(hostname(), destination())` (6db982c /
20301        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
20302        // axes, extended to the per-`:contratos` triple.
20303        for (de, para, wit, endpoint, subject, slot) in [
20304            (
20305                "cart",
20306                "catalog",
20307                "wasi:http/proxy",
20308                Some("/lookup"),
20309                None,
20310                None,
20311            ),
20312            (
20313                "checkout",
20314                "orders",
20315                "nats:pub-sub",
20316                None,
20317                Some("orders.paid"),
20318                None,
20319            ),
20320            (
20321                "cart",
20322                "kv",
20323                "wasi:keyvalue/store",
20324                None,
20325                None,
20326                Some("carts/{cart_id}"),
20327            ),
20328            (
20329                "orders-v2",
20330                "inventory-v3",
20331                "http:proxy",
20332                Some("/reserve"),
20333                None,
20334                None,
20335            ),
20336        ] {
20337            let c = WitContract {
20338                de: de.into(),
20339                para: para.into(),
20340                wit: wit.into(),
20341                endpoint: endpoint.map(str::to_string),
20342                subject: subject.map(str::to_string),
20343                slot: slot.map(str::to_string),
20344            };
20345            assert_eq!(
20346                (c.source(), c.destination(), c.world_ref()),
20347                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
20348                "(WitContract::source, ::destination, ::world_ref) must \
20349                 project (.de, .para, .wit) verbatim across every author-\
20350                 declared triple (got ({:?}, {:?}, {:?}), expected \
20351                 ({de:?}, {para:?}, {wit:?}))",
20352                c.source(),
20353                c.destination(),
20354                c.world_ref(),
20355            );
20356        }
20357    }
20358
20359    #[test]
20360    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
20361        // The canonical per-`:contratos` owned-form caller-callee-pair
20362        // pin: [`WitContract::edge_pair`] must return the
20363        // `(source(), destination())` tuple in owned form byte-for-byte,
20364        // projected through the lifted [`WitContract::source`] /
20365        // [`WitContract::destination`] scalar accessors. Pins the
20366        // composite-projection invariant on the per-`:contratos`
20367        // mesh-slot atom — every author-declared `(de, para)` pair must
20368        // round-trip verbatim through the substrate primitive's typed
20369        // dispatch, so the nine [`AplicacaoError`] diagnostic-
20370        // construction sites the accessor now feeds
20371        // ([`AplicacaoError::EmptyWit`],
20372        // [`AplicacaoError::ContratoEndpointEmpty`],
20373        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
20374        // [`AplicacaoError::ContratoEndpointInvalid`],
20375        // [`AplicacaoError::ContratoSubjectEmpty`],
20376        // [`AplicacaoError::ContratoSubjectInvalid`],
20377        // [`AplicacaoError::ContratoSlotEmpty`],
20378        // [`AplicacaoError::ContratoSlotInvalid`],
20379        // [`AplicacaoError::ContratoDuplicate`]) all read the same
20380        // `(de, para)` label pair every author sees at the source
20381        // `caixa.lisp`. Pins against a future silent detour that swapped
20382        // the `.0` / `.1` arms (an accidental `(destination(),
20383        // source())` re-order in the body would silently invert every
20384        // downstream diagnostic's `de:` / `para:` label pair, silently
20385        // reversing the direction of every operator-facing typed error
20386        // arrow), a fresh-allocation shape drift (an accidental
20387        // `.to_string()` on one arm but not the other would leave the
20388        // owned/borrowed pair mismatched vs. the sibling `source()` /
20389        // `destination()` returns), or an M4 per-cluster caller/callee-
20390        // alias rewrite that landed on `source()` without reaching
20391        // `destination()` (or vice versa). Peer of the sibling per-
20392        // `:contratos` `(source, destination, world_ref)` triple
20393        // pin above on the mesh-slot-atom scalar-value axes, extended
20394        // to the owned-form pair-projection axis.
20395        for (de, para, wit, endpoint, subject, slot) in [
20396            (
20397                "cart",
20398                "catalog",
20399                "wasi:http/proxy",
20400                Some("/lookup"),
20401                None,
20402                None,
20403            ),
20404            (
20405                "checkout",
20406                "orders",
20407                "nats:pub-sub",
20408                None,
20409                Some("orders.paid"),
20410                None,
20411            ),
20412            (
20413                "cart",
20414                "kv",
20415                "wasi:keyvalue/store",
20416                None,
20417                None,
20418                Some("carts/{cart_id}"),
20419            ),
20420            (
20421                "orders-v2",
20422                "inventory-v3",
20423                "http:proxy",
20424                Some("/reserve"),
20425                None,
20426                None,
20427            ),
20428        ] {
20429            let c = WitContract {
20430                de: de.into(),
20431                para: para.into(),
20432                wit: wit.into(),
20433                endpoint: endpoint.map(str::to_string),
20434                subject: subject.map(str::to_string),
20435                slot: slot.map(str::to_string),
20436            };
20437            assert_eq!(
20438                c.edge_pair(),
20439                (de.to_string(), para.to_string()),
20440                "WitContract::edge_pair must return (:contratos :de, \
20441                 :contratos :para) as an owned tuple verbatim (got {:?}, \
20442                 expected ({de:?}, {para:?}))",
20443                c.edge_pair(),
20444            );
20445        }
20446    }
20447
20448    #[test]
20449    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
20450        // The composition pin: [`WitContract::edge_pair`] must return
20451        // exactly `(source().to_string(), destination().to_string())` —
20452        // the owned form of the sibling accessor pair — so any future
20453        // refactor that silently re-authored the caller-arm / callee-arm
20454        // projection to bypass the lifted scalar accessors (an accidental
20455        // `(self.de.clone(), self.para.clone())` regression back to the
20456        // raw field-access shape, an M4-typed-caller-enum `Display`
20457        // re-canonicalization on `source()` that didn't reach
20458        // `edge_pair()`, a per-cluster alias rewrite the operator lands
20459        // on `destination()` without reaching this composite projection)
20460        // trips at caixa-core build time. Pins the "typed dispatch
20461        // composes with typed dispatch, not with raw field access"
20462        // discipline every downstream diagnostic-construction site now
20463        // routes through — a `de:` / `para:` label pair whose
20464        // projection silently drifted off the substrate primitive's
20465        // scalar accessors would silently split the diagnostic's self-
20466        // locating signal from the source `caixa.lisp` author's view.
20467        // Peer of the sibling per-`:politicas` `is_empty` /
20468        // `validate_politicas` accessor-routing-pin family on the M3
20469        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
20470        let c = WitContract {
20471            de: "cart".into(),
20472            para: "catalog".into(),
20473            wit: "wasi:http/proxy".into(),
20474            endpoint: Some("/lookup".into()),
20475            subject: None,
20476            slot: None,
20477        };
20478        assert_eq!(
20479            c.edge_pair(),
20480            (c.source().to_string(), c.destination().to_string()),
20481            "WitContract::edge_pair must compose exactly \
20482             (source().to_string(), destination().to_string()) — a \
20483             bypass of either sibling accessor here would silently \
20484             decouple the composite-projection axis from the \
20485             substrate-primitive scalar accessors every downstream \
20486             consumer routes through",
20487        );
20488    }
20489
20490    #[test]
20491    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
20492     {
20493        // The canonical per-`:contratos` owned-form
20494        // caller-callee-world-ref-triple pin:
20495        // [`WitContract::edge_triple`] must return the
20496        // `(source(), destination(), world_ref())` tuple in owned form
20497        // byte-for-byte, projected through the lifted
20498        // [`WitContract::source`] / [`WitContract::destination`] /
20499        // [`WitContract::world_ref`] scalar accessors. Pins the
20500        // composite-projection invariant on the per-`:contratos`
20501        // mesh-slot atom — every author-declared `(de, para, wit)`
20502        // triple must round-trip verbatim through the substrate
20503        // primitive's typed dispatch, so the nine
20504        // [`AplicacaoError`] diagnostic-construction sites the
20505        // accessor now feeds (the [`WitTarget`]-dispatch's eight
20506        // wrong-target / missing-target / invalid-wit / capability-
20507        // with-payload arms in [`WitContract::target`], plus the
20508        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
20509        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
20510        // read the same `(de, para, wit)` triple every author sees at
20511        // the source `caixa.lisp`. Pins against a future silent
20512        // detour that swapped any two arms (an accidental `(destination(),
20513        // source(), world_ref())` re-order in the body would silently
20514        // invert every downstream diagnostic's `de:` / `para:` label
20515        // pair, silently reversing the direction of every operator-
20516        // facing typed error arrow), a fresh-allocation shape drift
20517        // (an accidental `.to_string()` skipped on one arm would leave
20518        // the owned/borrowed triple mismatched vs. the sibling
20519        // `source()` / `destination()` / `world_ref()` returns), or an
20520        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
20521        // canonicalization pass that landed on one accessor without
20522        // reaching the peers. Peer of the sibling per-`:contratos`
20523        // caller-callee-pair
20524        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
20525        // pin on the mesh-slot-atom composite-projection axis,
20526        // extended to the triple-projection axis.
20527        for (de, para, wit, endpoint, subject, slot) in [
20528            (
20529                "cart",
20530                "catalog",
20531                "wasi:http/proxy",
20532                Some("/lookup"),
20533                None,
20534                None,
20535            ),
20536            (
20537                "checkout",
20538                "orders",
20539                "nats:pub-sub",
20540                None,
20541                Some("orders.paid"),
20542                None,
20543            ),
20544            (
20545                "cart",
20546                "kv",
20547                "wasi:keyvalue/store",
20548                None,
20549                None,
20550                Some("carts/{cart_id}"),
20551            ),
20552            (
20553                "orders-v2",
20554                "inventory-v3",
20555                "http:proxy",
20556                Some("/reserve"),
20557                None,
20558                None,
20559            ),
20560        ] {
20561            let c = WitContract {
20562                de: de.into(),
20563                para: para.into(),
20564                wit: wit.into(),
20565                endpoint: endpoint.map(str::to_string),
20566                subject: subject.map(str::to_string),
20567                slot: slot.map(str::to_string),
20568            };
20569            assert_eq!(
20570                c.edge_triple(),
20571                (de.to_string(), para.to_string(), wit.to_string()),
20572                "WitContract::edge_triple must return (:contratos :de, \
20573                 :contratos :para, :contratos :wit) as an owned triple \
20574                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
20575                c.edge_triple(),
20576            );
20577        }
20578    }
20579
20580    #[test]
20581    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
20582        // The composition pin: [`WitContract::edge_triple`] must return
20583        // exactly `(source().to_string(), destination().to_string(),
20584        // world_ref().to_string())` — the owned form of the sibling
20585        // scalar-accessor triple — so any future refactor that silently
20586        // re-authored one arm's projection to bypass the lifted scalar
20587        // accessors (an accidental `(self.de.clone(), self.para.clone(),
20588        // self.wit.clone())` regression back to the raw field-access
20589        // shape the internal `edge` closure and the ContratoDuplicate
20590        // diagnostic both carried before this lift landed, an
20591        // M4-typed-caller-enum `Display` re-canonicalization on
20592        // `source()` that didn't reach `edge_triple()`, a per-cluster
20593        // alias rewrite the operator lands on `destination()` /
20594        // `world_ref()` without reaching this composite projection)
20595        // trips at caixa-core build time. Pins the "typed dispatch
20596        // composes with typed dispatch, not with raw field access"
20597        // discipline every downstream diagnostic-construction site now
20598        // routes through — a `de:` / `para:` / `wit:` triple whose
20599        // projection silently drifted off the substrate primitive's
20600        // scalar accessors would silently split the diagnostic's self-
20601        // locating signal from the source `caixa.lisp` author's view.
20602        // Peer of the sibling per-`:contratos` edge_pair composition-
20603        // pin above on the mesh-slot-atom composite-projection axis.
20604        let c = WitContract {
20605            de: "cart".into(),
20606            para: "catalog".into(),
20607            wit: "wasi:http/proxy".into(),
20608            endpoint: Some("/lookup".into()),
20609            subject: None,
20610            slot: None,
20611        };
20612        assert_eq!(
20613            c.edge_triple(),
20614            (
20615                c.source().to_string(),
20616                c.destination().to_string(),
20617                c.world_ref().to_string(),
20618            ),
20619            "WitContract::edge_triple must compose exactly \
20620             (source().to_string(), destination().to_string(), \
20621             world_ref().to_string()) — a bypass of any sibling accessor \
20622             here would silently decouple the composite-projection axis \
20623             from the substrate-primitive scalar accessors every \
20624             downstream consumer routes through",
20625        );
20626    }
20627
20628    #[test]
20629    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
20630        // The canonical semantics-pin: [`WitContract::edge_triple`] must
20631        // project the full `(de, para, wit)` identity of a `:contratos`
20632        // edge — the sub-triple every triple-carrying
20633        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
20634        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
20635        // missing-target, capability-with-payload, invalid-wit, and the
20636        // duplicate-gate). Rejects a drift in shape (an accidental
20637        // silent detour that returned a `(de, para)` pair or added an
20638        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
20639        // would trip here because the return type would no longer
20640        // pattern-match the eight `let (de, para, wit) = edge();`
20641        // destructures the [`WitContract::target`] dispatch feeds off
20642        // + the paired duplicate-gate `let (de, para, wit) =
20643        // c.edge_triple();` destructure in
20644        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
20645        // `:contratos` caller-callee-pair pin above extended to the
20646        // triple projection surface: closes the "one composite
20647        // accessor per typed diagnostic-construction sub-tuple"
20648        // discipline on the per-`:contratos` mesh-slot-atom axis.
20649        let c = WitContract {
20650            de: "checkout".into(),
20651            para: "orders".into(),
20652            wit: "nats:pub-sub".into(),
20653            endpoint: None,
20654            subject: Some("orders.paid".into()),
20655            slot: None,
20656        };
20657        let (de, para, wit) = c.edge_triple();
20658        assert_eq!(de, "checkout");
20659        assert_eq!(para, "orders");
20660        assert_eq!(wit, "nats:pub-sub");
20661    }
20662
20663    #[test]
20664    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
20665     {
20666        // The composition pin: [`WitContract::identity`] must return
20667        // exactly `(source(), destination(), world_ref(), endpoint(),
20668        // subject(), slot())` — the borrowed form of the six-scalar-
20669        // accessor identity axis. Any future refactor that silently
20670        // re-authored one arm's projection to bypass a scalar accessor
20671        // (a `self.de.as_str()` regression back to raw field access on
20672        // any of the three required arms, a `self.endpoint.as_deref()`
20673        // regression on any of the three optional arms, an M4 per-
20674        // cluster caller/callee-alias rewrite the operator lands on
20675        // `source()` / `destination()` without reaching this composite
20676        // projection) trips at caixa-core build time. Sweeps four
20677        // permutations of the WIT-shape × payload lattice — HTTP with
20678        // endpoint, pub-sub with subject, store with slot, payload-less
20679        // capability — so every payload arm is exercised. Peer of the
20680        // sibling per-`:contratos`
20681        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
20682        // composition pin on the mesh-slot-atom composite-projection
20683        // axis; extends the discipline from the (de, para, wit) prefix
20684        // onto the full-identity axis carrying the three payload arms.
20685        for (de, para, wit, endpoint, subject, slot) in [
20686            (
20687                "cart",
20688                "catalog",
20689                "wasi:http/proxy",
20690                Some("/lookup"),
20691                None,
20692                None,
20693            ),
20694            (
20695                "checkout",
20696                "orders",
20697                "nats:pub-sub",
20698                None,
20699                Some("orders.paid"),
20700                None,
20701            ),
20702            (
20703                "cart",
20704                "kv",
20705                "wasi:keyvalue/store",
20706                None,
20707                None,
20708                Some("carts/{cart_id}"),
20709            ),
20710            ("audit", "sink", "wasi:logging", None, None, None),
20711        ] {
20712            let c = WitContract {
20713                de: de.into(),
20714                para: para.into(),
20715                wit: wit.into(),
20716                endpoint: endpoint.map(str::to_owned),
20717                subject: subject.map(str::to_owned),
20718                slot: slot.map(str::to_owned),
20719            };
20720            assert_eq!(
20721                c.identity(),
20722                (
20723                    c.source(),
20724                    c.destination(),
20725                    c.world_ref(),
20726                    c.endpoint(),
20727                    c.subject(),
20728                    c.slot(),
20729                ),
20730                "WitContract::identity must compose exactly \
20731                 (source(), destination(), world_ref(), endpoint(), \
20732                 subject(), slot()) — a bypass of any sibling accessor \
20733                 here would silently decouple the identity-projection \
20734                 axis from the substrate-primitive scalar accessors \
20735                 every dedup-key consumer routes through",
20736            );
20737        }
20738    }
20739
20740    #[test]
20741    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
20742        // The canonical semantics-pin: [`WitContract::identity`] must
20743        // project the six-axis (de, para, wit, endpoint, subject, slot)
20744        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
20745        // gate keys off — two `WitContract`s that agree on all six axes
20746        // are the same typed edge declared twice, the graph-edge
20747        // analogue of duplicate `:membros` / `:placement :clusters` /
20748        // `:entrada :paths` entries. Rejects a shape drift (an
20749        // accidental silent detour that returned a prefix tuple or
20750        // added an extra field) by pattern-matching the six-arm shape.
20751        // Peer of the sibling per-`:contratos`
20752        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
20753        // pin extended from the (de, para, wit) prefix onto the full
20754        // six-axis identity that the dedup key rides.
20755        let c = WitContract {
20756            de: "cart".into(),
20757            para: "catalog".into(),
20758            wit: "wasi:http/proxy".into(),
20759            endpoint: Some("/products/:id".into()),
20760            subject: None,
20761            slot: None,
20762        };
20763        let (de, para, wit, endpoint, subject, slot) = c.identity();
20764        assert_eq!(de, "cart");
20765        assert_eq!(para, "catalog");
20766        assert_eq!(wit, "wasi:http/proxy");
20767        assert_eq!(endpoint, Some("/products/:id"));
20768        assert_eq!(subject, None);
20769        assert_eq!(slot, None);
20770
20771        // Two byte-identical contracts must produce equal identities —
20772        // the dedup key's foundational invariant.
20773        let c2 = c.clone();
20774        assert_eq!(c.identity(), c2.identity());
20775
20776        // Any change on any of the six axes must break the identity —
20777        // sweeps by mutating one axis at a time.
20778        let mut mutated = c.clone();
20779        mutated.de = "search".into();
20780        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
20781        let mut mutated = c.clone();
20782        mutated.para = "warehouse".into();
20783        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
20784        let mut mutated = c.clone();
20785        mutated.wit = "http:legacy".into();
20786        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
20787        let mut mutated = c.clone();
20788        mutated.endpoint = Some("/search".into());
20789        assert_ne!(
20790            c.identity(),
20791            mutated.identity(),
20792            "endpoint axis must partition"
20793        );
20794        let mut mutated = c.clone();
20795        mutated.subject = Some("orders.paid".into());
20796        assert_ne!(
20797            c.identity(),
20798            mutated.identity(),
20799            "subject axis must partition"
20800        );
20801        let mut mutated = c;
20802        mutated.slot = Some("carts/{id}".into());
20803        assert_ne!(mutated.identity().5, None, "slot axis must partition");
20804    }
20805
20806    #[test]
20807    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
20808        // The canonical per-`:contratos` structural-self-edge pin:
20809        // [`WitContract::is_self_loop`] must return `true` when the
20810        // `:de` and `:para` fields agree byte-for-byte, across every
20811        // WIT-shape variant the per-edge shape family carries. Pins
20812        // the shape-agnostic identity-space partition the
20813        // [`AplicacaoSpec::validate`] self-edge gate at
20814        // caixa-core/src/aplicacao.rs:5559 fires against — all four
20815        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
20816        // under the same one predicate. Four permutations sweep the
20817        // accept-set: HTTP with endpoint, pub-sub with subject, KV
20818        // store with slot, and payload-less capability.
20819        for (nome, wit, endpoint, subject, slot) in [
20820            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
20821            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
20822            (
20823                "kv",
20824                "wasi:keyvalue/store",
20825                None,
20826                None,
20827                Some("carts/{cart_id}"),
20828            ),
20829            ("audit", "wasi:logging", None, None, None),
20830        ] {
20831            let c = WitContract {
20832                de: nome.into(),
20833                para: nome.into(),
20834                wit: wit.into(),
20835                endpoint: endpoint.map(str::to_string),
20836                subject: subject.map(str::to_string),
20837                slot: slot.map(str::to_string),
20838            };
20839            assert!(
20840                c.is_self_loop(),
20841                "WitContract::is_self_loop must return true when \
20842                 :contratos :de == :contratos :para (got false on \
20843                 {nome:?} under {wit:?})",
20844            );
20845        }
20846    }
20847
20848    #[test]
20849    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
20850        // The complement pin: [`WitContract::is_self_loop`] must return
20851        // `false` on every well-shaped inter-Servico contract (the
20852        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
20853        // names — "Servico A calls Servico B" between two distinct
20854        // graph nodes). Pins against a future silent detour that
20855        // inverted the predicate (an accidental `!= ` swap for `==`
20856        // would silently reject every legitimate inter-Servico edge
20857        // and admit every self-edge — the exact inversion of the
20858        // author-intended shape). Four permutations sweep the same
20859        // WIT-shape accept-set the sibling positive-arm test carries.
20860        for (de, para, wit, endpoint, subject, slot) in [
20861            (
20862                "cart",
20863                "catalog",
20864                "wasi:http/proxy",
20865                Some("/lookup"),
20866                None,
20867                None,
20868            ),
20869            (
20870                "checkout",
20871                "orders",
20872                "nats:pub-sub",
20873                None,
20874                Some("orders.paid"),
20875                None,
20876            ),
20877            (
20878                "cart",
20879                "kv",
20880                "wasi:keyvalue/store",
20881                None,
20882                None,
20883                Some("carts/{cart_id}"),
20884            ),
20885            ("audit", "sink", "wasi:logging", None, None, None),
20886        ] {
20887            let c = WitContract {
20888                de: de.into(),
20889                para: para.into(),
20890                wit: wit.into(),
20891                endpoint: endpoint.map(str::to_string),
20892                subject: subject.map(str::to_string),
20893                slot: slot.map(str::to_string),
20894            };
20895            assert!(
20896                !c.is_self_loop(),
20897                "WitContract::is_self_loop must return false when \
20898                 :contratos :de differs from :contratos :para (got true \
20899                 on {de:?} → {para:?} under {wit:?})",
20900            );
20901        }
20902    }
20903
20904    #[test]
20905    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
20906        // The composition pin: [`WitContract::is_self_loop`] must
20907        // resolve to exactly `self.source() == self.destination()` —
20908        // the equality probe of the sibling scalar-accessor pair — so
20909        // any future refactor that silently re-authored the predicate
20910        // to bypass the lifted scalar accessors (an accidental
20911        // `self.de == self.para` regression back to the raw field-
20912        // access shape, an M4-typed-caller-enum identity-comparison
20913        // rule that landed on `source()` without reaching
20914        // `destination()`, a per-cluster alias rewrite the operator
20915        // pins on `destination()` without reaching this predicate)
20916        // trips at caixa-core build time. Pins the "typed dispatch
20917        // composes with typed dispatch, not with raw field access"
20918        // discipline the sibling [`WitContract::edge_pair`] /
20919        // [`WitContract::edge_triple`] composite-projection accessors
20920        // already carry, extended onto the per-edge endpoint-equality
20921        // predicate axis. Positive and complement arms both fire.
20922        let self_edge = WitContract {
20923            de: "cart".into(),
20924            para: "cart".into(),
20925            wit: "wasi:http/proxy".into(),
20926            endpoint: Some("/lookup".into()),
20927            subject: None,
20928            slot: None,
20929        };
20930        assert_eq!(
20931            self_edge.is_self_loop(),
20932            self_edge.source() == self_edge.destination(),
20933            "WitContract::is_self_loop must compose exactly \
20934             `source() == destination()` — a bypass of either sibling \
20935             accessor here would silently decouple the endpoint-\
20936             equality predicate from the substrate-primitive scalar \
20937             accessors every downstream consumer routes through",
20938        );
20939        let inter_edge = WitContract {
20940            de: "cart".into(),
20941            para: "catalog".into(),
20942            wit: "wasi:http/proxy".into(),
20943            endpoint: Some("/lookup".into()),
20944            subject: None,
20945            slot: None,
20946        };
20947        assert_eq!(
20948            inter_edge.is_self_loop(),
20949            inter_edge.source() == inter_edge.destination(),
20950            "WitContract::is_self_loop must compose exactly \
20951             `source() == destination()` on the complement arm too",
20952        );
20953    }
20954
20955    #[test]
20956    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
20957        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
20958        // pin: [`WitContract::endpoint`] must return the `:contratos
20959        // :endpoint` field byte-for-byte, borrowed from the typed slot's
20960        // own `Option<String>` storage. Peer of the sibling
20961        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
20962        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
20963        // mesh-slot `Option<String>` optional-scalar axes — same "the
20964        // substrate-primitive accessor must byte-equal the raw field
20965        // access verbatim across every author-declared value" discipline
20966        // extended to the per-`:contratos` HTTP-payload-carrier arm.
20967        // Pins against a future silent detour that re-canonicalized the
20968        // endpoint (an accidental percent-encoding pass that didn't
20969        // reach the peer field-access site at the dedup key, a per-CR
20970        // fully-qualified prefix rewrite the operator authors on one
20971        // consumer without the other, or an M4 typed-path-template
20972        // `Display` re-canonicalization that silently drifted the
20973        // printer output from the source `caixa.lisp`). Four values
20974        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
20975        // gate upstream admits (short root-path, dashed, param-shaped,
20976        // deep-hierarchy).
20977        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
20978            let c = WitContract {
20979                de: "cart".into(),
20980                para: "catalog".into(),
20981                wit: "wasi:http/proxy".into(),
20982                endpoint: Some(endpoint.into()),
20983                subject: None,
20984                slot: None,
20985            };
20986            assert_eq!(
20987                c.endpoint(),
20988                Some(endpoint),
20989                "WitContract::endpoint must return :contratos :endpoint \
20990                 verbatim (got {:?}, expected Some({endpoint:?}))",
20991                c.endpoint(),
20992            );
20993            assert_eq!(
20994                c.endpoint(),
20995                c.endpoint.as_deref(),
20996                "WitContract::endpoint must byte-equal the .endpoint \
20997                 field's `.as_deref()` projection",
20998            );
20999        }
21000    }
21001
21002    #[test]
21003    fn wit_contract_endpoint_none_when_field_is_none() {
21004        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
21005        // payload-carrier accessor pin: when the typed slot is absent —
21006        // the canonical shape under a non-HTTP `:wit` world per the
21007        // [`WitContract::target`]-enforced shape ↔ target partition
21008        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
21009        // carries `:slot`, [`WitTarget::Capability`] carries none) —
21010        // [`WitContract::endpoint`] must return `None`. Pins against a
21011        // future silent detour that projected the absent slot to a
21012        // `Some("")` empty-string default (the canonical `Option<String>`
21013        // → `String` collapse footgun the sibling M2
21014        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21015        // emptiness predicates already guard on the peer M2 typed-slot
21016        // surfaces), a `Some("None")` stringified-None round-trip, or a
21017        // `Some` arm whose contents were derived from a sibling slot (an
21018        // accidental fallback to the `:subject` / `:slot` payload that
21019        // read the pub-sub / store payload into the endpoint axis).
21020        // Three contracts sweep the accept-set every non-HTTP `:wit`
21021        // world lands on — pub-sub NATS, key/value, and payload-less
21022        // capability.
21023        for (wit, subject, slot) in [
21024            ("nats:pub-sub", Some("orders.paid"), None),
21025            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21026            ("wasi:cli/environment", None, None),
21027        ] {
21028            let c = WitContract {
21029                de: "cart".into(),
21030                para: "downstream".into(),
21031                wit: wit.into(),
21032                endpoint: None,
21033                subject: subject.map(str::to_string),
21034                slot: slot.map(str::to_string),
21035            };
21036            assert!(
21037                c.endpoint().is_none(),
21038                "WitContract::endpoint must return None when the typed \
21039                 slot is absent under :wit {wit:?} (got {:?})",
21040                c.endpoint(),
21041            );
21042            assert_eq!(
21043                c.endpoint(),
21044                c.endpoint.as_deref(),
21045                "WitContract::endpoint must byte-equal the .endpoint \
21046                 field's `.as_deref()` projection in the absent arm",
21047            );
21048        }
21049    }
21050
21051    #[test]
21052    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
21053        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
21054        // an `Option<&str>` whose `Some` arm borrows from the typed
21055        // slot's own [`String`] storage — same-address invariant with
21056        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
21057        // detour that allocated a fresh `String`
21058        // (`self.endpoint.clone().map(...)` in the body would type-check
21059        // but silently drop the borrow, and every downstream consumer
21060        // that assumed the returned slice outlives `&self` would break
21061        // on a stale-reference use-after-free — the [`WitContract::target`]
21062        // Http-arm payload extraction rebinds the returned `Option<&str>`
21063        // through `.ok_or_else(...)` and threads the `&str` payload into
21064        // [`WitTarget::Http { endpoint: &'a str }`], the
21065        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
21066        // [`ContratoIdentity`] dedup key threads the returned
21067        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
21068        // from the WitContract's own storage and each would silently
21069        // misbehave if this accessor produced a detached copy). Peer of
21070        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21071        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21072        // shaped optional-scalar axes — first extension of the
21073        // `Option<&str>` borrow-not-copy discipline onto the
21074        // per-`:contratos` HTTP-shaped payload-carrier axis.
21075        let c = WitContract {
21076            de: "cart".into(),
21077            para: "catalog".into(),
21078            wit: "wasi:http/proxy".into(),
21079            endpoint: Some("/lookup".into()),
21080            subject: None,
21081            slot: None,
21082        };
21083        let ep = c.endpoint().expect("Some arm");
21084        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
21085        assert_eq!(
21086            ep.as_ptr(),
21087            storage_slice.as_ptr(),
21088            "WitContract::endpoint must borrow from the .endpoint \
21089             String's backing storage — a fresh allocation here means \
21090             the accessor no longer names the substrate-primitive typed \
21091             dispatch and every downstream consumer would silently \
21092             carry a detached copy",
21093        );
21094        assert_eq!(
21095            ep.len(),
21096            storage_slice.len(),
21097            "WitContract::endpoint and .endpoint.as_deref() must byte-\
21098             equal in length as well as in address",
21099        );
21100    }
21101
21102    #[test]
21103    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
21104        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
21105        // pin: [`WitContract::subject`] must return the `:contratos
21106        // :subject` field byte-for-byte, borrowed from the typed slot's
21107        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
21108        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
21109        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21110        // optional-scalar axis — same "the substrate-primitive accessor
21111        // must byte-equal the raw field access verbatim across every
21112        // author-declared value" discipline extended to the pub-sub arm.
21113        // Pins against a future silent detour that re-canonicalized the
21114        // subject (an accidental `.to_lowercase()` normalization that
21115        // didn't reach the peer field-access site at the dedup key, a
21116        // per-CR fully-qualified prefix rewrite the operator authors on
21117        // one consumer without the other, or an M4 typed-subject-template
21118        // `Display` re-canonicalization that silently drifted the printer
21119        // output from the source `caixa.lisp`). Four values sweep the
21120        // NATS accept-set every pub-sub author-declared subject lands on
21121        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
21122        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
21123            let c = WitContract {
21124                de: "cart".into(),
21125                para: "notifier".into(),
21126                wit: "nats:pub-sub".into(),
21127                endpoint: None,
21128                subject: Some(subject.into()),
21129                slot: None,
21130            };
21131            assert_eq!(
21132                c.subject(),
21133                Some(subject),
21134                "WitContract::subject must return :contratos :subject \
21135                 verbatim (got {:?}, expected Some({subject:?}))",
21136                c.subject(),
21137            );
21138            assert_eq!(
21139                c.subject(),
21140                c.subject.as_deref(),
21141                "WitContract::subject must byte-equal the .subject \
21142                 field's `.as_deref()` projection",
21143            );
21144        }
21145    }
21146
21147    #[test]
21148    fn wit_contract_subject_none_when_field_is_none() {
21149        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
21150        // shaped payload-carrier accessor pin: when the typed slot is
21151        // absent — the canonical shape under a non-pub-sub `:wit` world
21152        // per the [`WitContract::target`]-enforced shape ↔ target
21153        // partition ([`WitTarget::Http`] carries `:endpoint`,
21154        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
21155        // carries none) — [`WitContract::subject`] must return `None`.
21156        // Pins against a future silent detour that projected the absent
21157        // slot to a `Some("")` empty-string default (the canonical
21158        // `Option<String>` → `String` collapse footgun the sibling M2
21159        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21160        // emptiness predicates already guard on the peer M2 typed-slot
21161        // surfaces), a `Some("None")` stringified-None round-trip, or a
21162        // `Some` arm whose contents were derived from a sibling slot (an
21163        // accidental fallback to the `:endpoint` / `:slot` payload that
21164        // read the HTTP / store payload into the subject axis). Three
21165        // contracts sweep the accept-set every non-pub-sub `:wit` world
21166        // lands on — HTTP proxy, key/value store, and payload-less
21167        // capability.
21168        for (wit, endpoint, slot) in [
21169            ("wasi:http/proxy", Some("/lookup"), None),
21170            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21171            ("wasi:cli/environment", None, None),
21172        ] {
21173            let c = WitContract {
21174                de: "cart".into(),
21175                para: "downstream".into(),
21176                wit: wit.into(),
21177                endpoint: endpoint.map(str::to_string),
21178                subject: None,
21179                slot: slot.map(str::to_string),
21180            };
21181            assert!(
21182                c.subject().is_none(),
21183                "WitContract::subject must return None when the typed \
21184                 slot is absent under :wit {wit:?} (got {:?})",
21185                c.subject(),
21186            );
21187            assert_eq!(
21188                c.subject(),
21189                c.subject.as_deref(),
21190                "WitContract::subject must byte-equal the .subject \
21191                 field's `.as_deref()` projection in the absent arm",
21192            );
21193        }
21194    }
21195
21196    #[test]
21197    fn wit_contract_subject_borrows_from_subject_storage() {
21198        // The borrow-not-copy pin: [`WitContract::subject`] must return
21199        // an `Option<&str>` whose `Some` arm borrows from the typed
21200        // slot's own [`String`] storage — same-address invariant with
21201        // `c.subject.as_deref().unwrap()`. Pins against a future silent
21202        // detour that allocated a fresh `String`
21203        // (`self.subject.clone().map(...)` in the body would type-check
21204        // but silently drop the borrow, and every downstream consumer
21205        // that assumed the returned slice outlives `&self` would break
21206        // on a stale-reference use-after-free — the [`WitContract::target`]
21207        // PubSub-arm payload extraction rebinds the returned
21208        // `Option<&str>` through `.ok_or_else(...)` and threads the
21209        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
21210        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21211        // [`ContratoIdentity`] dedup key threads the returned
21212        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
21213        // from the WitContract's own storage and each would silently
21214        // misbehave if this accessor produced a detached copy). Peer of
21215        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
21216        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21217        // shaped optional-scalar axis — second extension of the
21218        // `Option<&str>` borrow-not-copy discipline onto the
21219        // per-`:contratos` payload-carrier family, this time on the
21220        // pub-sub arm.
21221        let c = WitContract {
21222            de: "cart".into(),
21223            para: "notifier".into(),
21224            wit: "nats:pub-sub".into(),
21225            endpoint: None,
21226            subject: Some("orders.paid".into()),
21227            slot: None,
21228        };
21229        let sub = c.subject().expect("Some arm");
21230        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
21231        assert_eq!(
21232            sub.as_ptr(),
21233            storage_slice.as_ptr(),
21234            "WitContract::subject must borrow from the .subject \
21235             String's backing storage — a fresh allocation here means \
21236             the accessor no longer names the substrate-primitive typed \
21237             dispatch and every downstream consumer would silently \
21238             carry a detached copy",
21239        );
21240        assert_eq!(
21241            sub.len(),
21242            storage_slice.len(),
21243            "WitContract::subject and .subject.as_deref() must byte-\
21244             equal in length as well as in address",
21245        );
21246    }
21247
21248    #[test]
21249    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
21250        // The canonical per-`:contratos` key/value-store-shaped
21251        // `:slot`-scalar pin: [`WitContract::slot`] must return the
21252        // `:contratos :slot` field byte-for-byte, borrowed from the
21253        // typed slot's own `Option<String>` storage. Peer of the
21254        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
21255        // [`WitContract::subject`] (90de675) accessor pins on the M3
21256        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21257        // optional-scalar axis — same "the substrate-primitive
21258        // accessor must byte-equal the raw field access verbatim
21259        // across every author-declared value" discipline extended to
21260        // the store arm. Pins against a future silent detour that
21261        // re-canonicalized the slot template (an accidental
21262        // `.to_lowercase()` bucket-prefix normalization that didn't
21263        // reach the peer field-access site at the dedup key, a per-CR
21264        // fully-qualified prefix rewrite the operator authors on one
21265        // consumer without the other, or an M4 typed-key-template
21266        // `Display` re-canonicalization that silently drifted the
21267        // printer output from the source `caixa.lisp`). Four values
21268        // sweep the wasi:keyvalue accept-set every store-shaped
21269        // author-declared slot lands on (flat bucket, single-param
21270        // template, multi-param template, nested-hierarchy template).
21271        for slot in [
21272            "sessions",
21273            "carts/{cart_id}",
21274            "orders/{tenant}/{order_id}",
21275            "cache/tenant-a/orders/{id}",
21276        ] {
21277            let c = WitContract {
21278                de: "cart".into(),
21279                para: "kv".into(),
21280                wit: "wasi:keyvalue/store".into(),
21281                endpoint: None,
21282                subject: None,
21283                slot: Some(slot.into()),
21284            };
21285            assert_eq!(
21286                c.slot(),
21287                Some(slot),
21288                "WitContract::slot must return :contratos :slot \
21289                 verbatim (got {:?}, expected Some({slot:?}))",
21290                c.slot(),
21291            );
21292            assert_eq!(
21293                c.slot(),
21294                c.slot.as_deref(),
21295                "WitContract::slot must byte-equal the .slot field's \
21296                 `.as_deref()` projection",
21297            );
21298        }
21299    }
21300
21301    #[test]
21302    fn wit_contract_slot_none_when_field_is_none() {
21303        // The absent-`:slot` arm of the per-`:contratos` store-shaped
21304        // payload-carrier accessor pin: when the typed slot is absent —
21305        // the canonical shape under a non-store `:wit` world per the
21306        // [`WitContract::target`]-enforced shape ↔ target partition
21307        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
21308        // carries `:subject`, [`WitTarget::Capability`] carries none) —
21309        // [`WitContract::slot`] must return `None`. Pins against a
21310        // future silent detour that projected the absent slot to a
21311        // `Some("")` empty-string default (the canonical
21312        // `Option<String>` → `String` collapse footgun the sibling M2
21313        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21314        // emptiness predicates already guard on the peer M2 typed-slot
21315        // surfaces), a `Some("None")` stringified-None round-trip, or
21316        // a `Some` arm whose contents were derived from a sibling
21317        // slot (an accidental fallback to the `:endpoint` / `:subject`
21318        // payload that read the HTTP / pub-sub payload into the store
21319        // axis). Three contracts sweep the accept-set every non-store
21320        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
21321        // payload-less capability.
21322        for (wit, endpoint, subject) in [
21323            ("wasi:http/proxy", Some("/lookup"), None),
21324            ("nats:pub-sub", None, Some("orders.paid")),
21325            ("wasi:cli/environment", None, None),
21326        ] {
21327            let c = WitContract {
21328                de: "cart".into(),
21329                para: "downstream".into(),
21330                wit: wit.into(),
21331                endpoint: endpoint.map(str::to_string),
21332                subject: subject.map(str::to_string),
21333                slot: None,
21334            };
21335            assert!(
21336                c.slot().is_none(),
21337                "WitContract::slot must return None when the typed \
21338                 slot is absent under :wit {wit:?} (got {:?})",
21339                c.slot(),
21340            );
21341            assert_eq!(
21342                c.slot(),
21343                c.slot.as_deref(),
21344                "WitContract::slot must byte-equal the .slot field's \
21345                 `.as_deref()` projection in the absent arm",
21346            );
21347        }
21348    }
21349
21350    #[test]
21351    fn wit_contract_slot_borrows_from_slot_storage() {
21352        // The borrow-not-copy pin: [`WitContract::slot`] must return
21353        // an `Option<&str>` whose `Some` arm borrows from the typed
21354        // slot's own [`String`] storage — same-address invariant with
21355        // `c.slot.as_deref().unwrap()`. Pins against a future silent
21356        // detour that allocated a fresh `String`
21357        // (`self.slot.clone().map(...)` in the body would type-check
21358        // but silently drop the borrow, and every downstream consumer
21359        // that assumed the returned slice outlives `&self` would
21360        // break on a stale-reference use-after-free — the
21361        // [`WitContract::target`] Store-arm payload extraction rebinds
21362        // the returned `Option<&str>` through `.ok_or_else(...)` and
21363        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
21364        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21365        // [`ContratoIdentity`] dedup key threads the returned
21366        // `Option<&str>` into the six-tuple's store arm — each borrow
21367        // from the WitContract's own storage and each would silently
21368        // misbehave if this accessor produced a detached copy). Peer
21369        // of the sibling per-`:contratos` [`WitContract::endpoint`]
21370        // (7020470) / [`WitContract::subject`] (90de675)
21371        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
21372        // shaped optional-scalar axis — third and final extension of
21373        // the `Option<&str>` borrow-not-copy discipline onto the
21374        // per-`:contratos` payload-carrier family, this time on the
21375        // store arm.
21376        let c = WitContract {
21377            de: "cart".into(),
21378            para: "kv".into(),
21379            wit: "wasi:keyvalue/store".into(),
21380            endpoint: None,
21381            subject: None,
21382            slot: Some("carts/{cart_id}".into()),
21383        };
21384        let slot = c.slot().expect("Some arm");
21385        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
21386        assert_eq!(
21387            slot.as_ptr(),
21388            storage_slice.as_ptr(),
21389            "WitContract::slot must borrow from the .slot String's \
21390             backing storage — a fresh allocation here means the \
21391             accessor no longer names the substrate-primitive typed \
21392             dispatch and every downstream consumer would silently \
21393             carry a detached copy",
21394        );
21395        assert_eq!(
21396            slot.len(),
21397            storage_slice.len(),
21398            "WitContract::slot and .slot.as_deref() must byte-equal \
21399             in length as well as in address",
21400        );
21401    }
21402
21403    #[test]
21404    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
21405        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
21406        // [`Membro::nome`] must return the `:membros :caixa` field
21407        // byte-for-byte, borrowed from the typed slot's own [`String`]
21408        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
21409        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21410        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21411        // slot-atom scalar-value axes — same "the substrate-primitive
21412        // accessor must byte-equal the raw field access verbatim across
21413        // every author-declared value" discipline extended to the
21414        // per-`:membros` member-identity arm. Pins against a future
21415        // silent detour that re-normalized the member identity (an
21416        // accidental `.to_lowercase()` — every `:membros :caixa` is
21417        // validated as a DNS-1123 label upstream via
21418        // [`validate_membro_caixa`], so any re-normalization is
21419        // redundant + a drift surface between the validator and the
21420        // accessor), a namespace-prefix rewrite (an accidental
21421        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
21422        // rewrite that didn't land on the peer axes), or a per-cluster
21423        // alias stamp the operator authors on one consumer without the
21424        // other. Four values sweep the accept-set the DNS-1123 gate
21425        // upstream admits (short single-word / dashed / v-suffixed
21426        // member names).
21427        for name in ["cart", "checkout", "catalog", "orders-v2"] {
21428            let m = Membro {
21429                caixa: name.into(),
21430                versao: "^0.1".into(),
21431            };
21432            assert_eq!(
21433                m.nome(),
21434                name,
21435                "Membro::nome must return :membros :caixa verbatim \
21436                 (got {:?}, expected {name:?})",
21437                m.nome(),
21438            );
21439            assert_eq!(
21440                m.nome(),
21441                m.caixa.as_str(),
21442                "Membro::nome must byte-equal the .caixa field access",
21443            );
21444        }
21445    }
21446
21447    #[test]
21448    fn membro_nome_borrows_from_caixa_storage() {
21449        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
21450        // slice that borrows from the typed slot's own [`String`]
21451        // storage — same-address invariant with `m.caixa.as_str()`. Pins
21452        // against a future silent detour that allocated a fresh `String`
21453        // (`self.caixa.clone()` in the body would type-check but
21454        // silently drop the borrow, and every downstream consumer that
21455        // assumed the returned slice outlives `&self` would break on a
21456        // stale-reference use-after-free — the `HashSet<&str>` collector
21457        // at [`AplicacaoSpec::validate`]'s `names` seed, the
21458        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
21459        // [`AplicacaoSpec::detect_sync_cycles`], the
21460        // [`crate::render::insert_first_seen`] dedup key at
21461        // [`AplicacaoSpec::validate_membros`] — each borrow from the
21462        // Membro's own storage and each would silently misbehave if
21463        // this accessor produced a detached copy). Peer of the sibling
21464        // per-`:contratos` [`WitContract::source`] /
21465        // [`WitContract::destination`] and per-`:entrada`
21466        // [`Entrada::destination`] borrow-invariant pins on the mesh-
21467        // slot-atom scalar-value axes.
21468        let m = Membro {
21469            caixa: "checkout".into(),
21470            versao: "^0.1".into(),
21471        };
21472        let name = m.nome();
21473        let caixa_slice = m.caixa.as_str();
21474        assert_eq!(
21475            name.as_ptr(),
21476            caixa_slice.as_ptr(),
21477            "Membro::nome must borrow from the .caixa String's backing \
21478             storage — a fresh allocation here means the accessor no \
21479             longer names the substrate-primitive typed dispatch and \
21480             every downstream consumer would silently carry a detached \
21481             copy",
21482        );
21483        assert_eq!(
21484            name.len(),
21485            caixa_slice.len(),
21486            "Membro::nome and .caixa.as_str() must byte-equal in length \
21487             as well as in address",
21488        );
21489    }
21490
21491    #[test]
21492    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
21493        // The canonical per-`:membros` member-`:versao`-scalar pin:
21494        // [`Membro::versao_requirement`] must return the
21495        // `:membros :versao` field byte-for-byte, borrowed from the typed
21496        // slot's own [`String`] storage. Sibling of the peer
21497        // `membro_nome_returns_caixa_byte_equal_across_permutations`
21498        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
21499        // — same "the substrate-primitive accessor must byte-equal the
21500        // raw field access verbatim across every author-declared value"
21501        // discipline extended to the per-`:membros` member-`:versao`
21502        // requirement-string arm. Pins against a future silent detour
21503        // that re-canonicalized the requirement (an accidental
21504        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
21505        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
21506        // drifted the printer output away from the source `caixa.lisp`,
21507        // an accidental whitespace trim on `"^ 0.1"` that no consumer
21508        // ever produced from the field-access side, an accidental
21509        // per-cluster lacre-projected concrete-version rewrite that
21510        // didn't land on the peer field-access sites). Five values sweep
21511        // the accept-set the shared
21512        // [`crate::render::require_valid_versao_requirement`] gate
21513        // admits (caret / tilde / exact / wildcard / bare-major).
21514        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
21515            let m = Membro {
21516                caixa: "cart".into(),
21517                versao: req.into(),
21518            };
21519            assert_eq!(
21520                m.versao_requirement(),
21521                req,
21522                "Membro::versao_requirement must return :membros :versao \
21523                 verbatim (got {:?}, expected {req:?})",
21524                m.versao_requirement(),
21525            );
21526            assert_eq!(
21527                m.versao_requirement(),
21528                m.versao.as_str(),
21529                "Membro::versao_requirement must byte-equal the .versao \
21530                 field access",
21531            );
21532        }
21533    }
21534
21535    #[test]
21536    fn membro_versao_requirement_borrows_from_versao_storage() {
21537        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
21538        // return a `&str` slice that borrows from the typed slot's own
21539        // [`String`] storage — same-address invariant with
21540        // `m.versao.as_str()`. Pins against a future silent detour that
21541        // allocated a fresh `String` (`self.versao.clone()` in the body
21542        // would type-check but silently drop the borrow, and every
21543        // downstream consumer that assumed the returned slice outlives
21544        // `&self` would break on a stale-reference use-after-free). Peer
21545        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21546        // per-`:contratos` [`WitContract::source`] /
21547        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21548        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
21549        // the mesh-slot-atom scalar-value axes.
21550        let m = Membro {
21551            caixa: "checkout".into(),
21552            versao: "^0.1".into(),
21553        };
21554        let req = m.versao_requirement();
21555        let versao_slice = m.versao.as_str();
21556        assert_eq!(
21557            req.as_ptr(),
21558            versao_slice.as_ptr(),
21559            "Membro::versao_requirement must borrow from the .versao \
21560             String's backing storage — a fresh allocation here means \
21561             the accessor no longer names the substrate-primitive typed \
21562             dispatch and every downstream consumer would silently carry \
21563             a detached copy",
21564        );
21565        assert_eq!(
21566            req.len(),
21567            versao_slice.len(),
21568            "Membro::versao_requirement and .versao.as_str() must byte-\
21569             equal in length as well as in address",
21570        );
21571    }
21572
21573    #[test]
21574    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
21575        // Sibling-pair invariant pin composing both per-`:membros`
21576        // substrate-primitive typed dispatches — [`Membro::nome`]
21577        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
21578        // `(nome(), versao_requirement())` call shape every renderer
21579        // that fans on per-member identity + version pin keys off. The
21580        // invariant, evaluated per-member:
21581        //
21582        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
21583        //
21584        // Closes the last unlifted per-`:membros` scalar axis — every
21585        // downstream consumer that reads the pair now routes through
21586        // exactly two typed dispatches on the substrate primitive, not
21587        // one typed + one open-coded field access. A future refactor
21588        // that silently split either accessor's projection (an
21589        // accidental `nome()` namespace-prefix rewrite that didn't
21590        // reach the peer, an accidental `versao_requirement()` lacre-
21591        // projected concrete-version rewrite that didn't land on the
21592        // `nome()` peer) surfaces at caixa-core build time. Peer of the
21593        // sibling per-`:entrada` `(hostname(), destination())` and
21594        // per-`:contratos` `(source(), destination())` pair invariants
21595        // on the mesh-slot-atom scalar-value axes.
21596        for (caixa, versao) in [
21597            ("cart", "^0.1"),
21598            ("checkout", "~0.1.2"),
21599            ("catalog", "0.1.0"),
21600            ("orders-v2", "*"),
21601        ] {
21602            let m = Membro {
21603                caixa: caixa.into(),
21604                versao: versao.into(),
21605            };
21606            assert_eq!(
21607                (m.nome(), m.versao_requirement()),
21608                (m.caixa.as_str(), m.versao.as_str()),
21609                "(Membro::nome, Membro::versao_requirement) must project \
21610                 (.caixa, .versao) verbatim across every author-declared \
21611                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
21612                m.nome(),
21613                m.versao_requirement(),
21614            );
21615        }
21616    }
21617
21618    #[test]
21619    fn validate_membros_empty_gate_routes_through_nome_accessor() {
21620        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
21621        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
21622        // not the raw `.caixa` field access. Structurally: setting
21623        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
21624        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
21625        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
21626        // (i.e. the empty string) — so the emptiness predicate the
21627        // refusal arm reaches under is the accessor-projected value,
21628        // not a peer field that would silently drift under a future
21629        // accessor-side rewrite.
21630        //
21631        // Pins against a future silent detour that (a) re-derived the
21632        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
21633        // instead of `self.nome().is_empty()`, silently disagreeing with
21634        // every peer consumer (the `validate_membro_caixa(m.nome())`
21635        // call one line below, the dedup-key `insert_first_seen(&mut
21636        // seen, m.nome(), …)` two lines below, the emit-side per-
21637        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
21638        // (b) accessor-side introduced a per-tenant alias arm the
21639        // caller was unaware of, silently rewriting an author-declared
21640        // `:caixa "checkout"` to `""` — the raw-field-access gate
21641        // would fail-open while the accessor-routed peer consumers
21642        // would fail-closed, splitting the diagnostic from the actual
21643        // failure surface.
21644        //
21645        // Peer of the sibling
21646        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
21647        // (c0110f1) composition pin — same "the shape-gate predicate
21648        // must route through the substrate-primitive typed dispatch"
21649        // discipline extended onto the per-`:membros` empty-`:caixa`
21650        // refusal-arm axis. Closes the last unlifted `.caixa` production-
21651        // code read site on `Membro` — after this converge every
21652        // caixa-core `.caixa` field access outside the accessor's own
21653        // body is either a test-side field-setter (in-module tests
21654        // constructing invalid-shape inputs) or a doc-comment reference.
21655        let mut s = three_member_spec();
21656        s.membros[1].caixa = String::new();
21657        assert!(
21658            s.membros[1].nome().is_empty(),
21659            "Membro::nome must byte-equal the .caixa field access — an \
21660             accessor-side detour that no longer projects the raw field \
21661             would silently split this drift-detection test from the \
21662             validate() refusal arm",
21663        );
21664        assert_eq!(
21665            s.membros[1].nome(),
21666            s.membros[1].caixa.as_str(),
21667            "Membro::nome and .caixa.as_str() must byte-equal on an \
21668             empty-`:caixa` entry — the emptiness gate keys off the \
21669             accessor by construction",
21670        );
21671        assert_eq!(
21672            s.validate().unwrap_err(),
21673            AplicacaoError::MembroCaixaEmpty,
21674            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
21675             on an entry whose accessor-projected `nome()` is empty",
21676        );
21677    }
21678
21679    #[test]
21680    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
21681        // The canonical per-`:placement` Akka-cluster-sharding
21682        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
21683        // the `:placement :shard-key` field byte-for-byte, borrowed
21684        // from the typed slot's own `Option<String>` storage. Peer of
21685        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21686        // per-`:contratos` [`WitContract::source`] /
21687        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21688        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21689        // slot-atom scalar-value axes — same "the substrate-primitive
21690        // accessor must byte-equal the raw field access verbatim across
21691        // every author-declared value" discipline extended to the
21692        // per-`:placement` Akka-cluster-sharding key extractor arm.
21693        // Pins against a future silent detour that re-normalized the
21694        // key (an accidental `.to_lowercase()` — every non-empty
21695        // `:shard-key` is validated as a printable-ASCII single-token
21696        // reference upstream via [`validate_placement_shard_key`], so
21697        // any re-normalization is redundant + a drift surface between
21698        // the validator and the accessor), a per-cluster alias rewrite
21699        // the operator authors on one consumer without the other, or an
21700        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
21701        // that didn't land on the peer field-access sites. Four values
21702        // sweep the accept-set the shape gate admits — bare identifier,
21703        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
21704        // the four canonical Akka-style entity-id extractor shapes the
21705        // future M4 cluster-sharding reconciler hashes.
21706        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
21707            let p = Placement {
21708                estrategia: PlacementStrategy::Sharded,
21709                clusters: vec!["rio".into()],
21710                affinity: None,
21711                shard_key: Some(key.into()),
21712            };
21713            assert_eq!(
21714                p.shard_key(),
21715                Some(key),
21716                "Placement::shard_key must return :placement :shard-key \
21717                 verbatim (got {:?}, expected Some({key:?}))",
21718                p.shard_key(),
21719            );
21720            assert_eq!(
21721                p.shard_key(),
21722                p.shard_key.as_deref(),
21723                "Placement::shard_key must byte-equal the .shard_key \
21724                 field's `.as_deref()` projection",
21725            );
21726        }
21727    }
21728
21729    #[test]
21730    fn placement_shard_key_none_when_field_is_none() {
21731        // The absent-`:shard-key` arm of the per-`:placement`
21732        // Akka-cluster-sharding accessor pin: when the typed slot is
21733        // absent — the canonical shape under `:estrategia Replicated` /
21734        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
21735        // enforced `shard_key.is_some() == matches!(estrategia,
21736        // Sharded)` partition — [`Placement::shard_key`] must return
21737        // `None`. Pins against a future silent detour that projected
21738        // the absent slot to a `Some("")` empty-string default (the
21739        // canonical `Option<String>` → `String` collapse footgun the
21740        // sibling M2 [`crate::LimitsSpec::is_empty`] /
21741        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
21742        // already guard on the peer M2 typed-slot surfaces), a
21743        // `Some("None")` stringified-None round-trip, or a `Some` arm
21744        // whose contents were derived from a sibling slot (an
21745        // accidental fallback to `estrategia.as_str()` that read the
21746        // strategy discriminator into the key axis). Two placements
21747        // sweep the accept-set every `validate`-passing non-`Sharded`
21748        // shape lands on — `Replicated` (Erlang/OTP distributed-app
21749        // takeover) and `SingleNode` (single-node hosting).
21750        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
21751            let p = Placement {
21752                estrategia,
21753                clusters: vec!["rio".into()],
21754                affinity: None,
21755                shard_key: None,
21756            };
21757            assert!(
21758                p.shard_key().is_none(),
21759                "Placement::shard_key must return None when the typed \
21760                 slot is absent under :estrategia {estrategia:?} (got {:?})",
21761                p.shard_key(),
21762            );
21763            assert_eq!(
21764                p.shard_key(),
21765                p.shard_key.as_deref(),
21766                "Placement::shard_key must byte-equal the .shard_key \
21767                 field's `.as_deref()` projection in the absent arm",
21768            );
21769        }
21770    }
21771
21772    #[test]
21773    fn placement_shard_key_borrows_from_shard_key_storage() {
21774        // The borrow-not-copy pin: [`Placement::shard_key`] must return
21775        // an `Option<&str>` whose `Some` arm borrows from the typed
21776        // slot's own [`String`] storage — same-address invariant with
21777        // `p.shard_key.as_deref().unwrap()`. Pins against a future
21778        // silent detour that allocated a fresh `String`
21779        // (`self.shard_key.clone().map(...)` in the body would type-
21780        // check but silently drop the borrow, and every downstream
21781        // consumer that assumed the returned slice outlives `&self`
21782        // would break on a stale-reference use-after-free — the
21783        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
21784        // gate's `Some(k)`-bound match arm reads `k: &str` under the
21785        // accessor's return type and would silently misbehave if this
21786        // accessor produced a detached copy). Peer of the sibling
21787        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
21788        // [`WitContract::source`] / [`WitContract::destination`]
21789        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
21790        // (6db982c) borrow-invariant pins on the mesh-slot-atom
21791        // scalar-value axes — first extension of the discipline onto
21792        // an `Option<String>`-shaped optional-scalar axis.
21793        let p = Placement {
21794            estrategia: PlacementStrategy::Sharded,
21795            clusters: vec!["rio".into()],
21796            affinity: None,
21797            shard_key: Some("tenantId".into()),
21798        };
21799        let key = p.shard_key().expect("Some arm");
21800        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
21801        assert_eq!(
21802            key.as_ptr(),
21803            storage_slice.as_ptr(),
21804            "Placement::shard_key must borrow from the .shard_key \
21805             String's backing storage — a fresh allocation here means \
21806             the accessor no longer names the substrate-primitive typed \
21807             dispatch and every downstream consumer would silently \
21808             carry a detached copy",
21809        );
21810        assert_eq!(
21811            key.len(),
21812            storage_slice.len(),
21813            "Placement::shard_key and .shard_key.as_deref() must byte-\
21814             equal in length as well as in address",
21815        );
21816    }
21817
21818    #[test]
21819    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
21820        // The canonical per-`:placement` M3-Adaptive-compression-hint
21821        // scalar pin: [`Placement::affinity`] must return the
21822        // `:placement :affinity` field byte-for-byte, borrowed from the
21823        // typed slot's own `Option<String>` storage. Peer of the sibling
21824        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
21825        // pin on the sibling `Option<&str>` optional-scalar axis — same
21826        // "the substrate-primitive accessor must byte-equal the raw
21827        // field access verbatim across every author-declared value"
21828        // discipline extended to the peer per-`:placement` M3-Adaptive-
21829        // compression-hint arm. Pins against a future silent detour
21830        // that re-normalized the hint (an accidental `.to_lowercase()`
21831        // — every `:affinity` is already validated as a DNS-1123 label
21832        // upstream via [`validate_placement_affinity`], so any re-
21833        // normalization is redundant + a drift surface between the
21834        // validator and the accessor), a per-cluster alias rewrite the
21835        // operator authors on one consumer without the other, or an
21836        // accidental hint-family collapse (`low-latency` → `latency`
21837        // that dropped the qualifier prefix). Four values sweep the
21838        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
21839        // canonical adaptive-compression-weight biases the future M4
21840        // placement engine reads.
21841        for hint in [
21842            "data-locality",
21843            "low-latency",
21844            "high-throughput",
21845            "cost-optimized",
21846        ] {
21847            let p = Placement {
21848                estrategia: PlacementStrategy::Replicated,
21849                clusters: vec!["rio".into()],
21850                affinity: Some(hint.into()),
21851                shard_key: None,
21852            };
21853            assert_eq!(
21854                p.affinity(),
21855                Some(hint),
21856                "Placement::affinity must return :placement :affinity \
21857                 verbatim (got {:?}, expected Some({hint:?}))",
21858                p.affinity(),
21859            );
21860            assert_eq!(
21861                p.affinity(),
21862                p.affinity.as_deref(),
21863                "Placement::affinity must byte-equal the .affinity \
21864                 field's `.as_deref()` projection",
21865            );
21866        }
21867    }
21868
21869    #[test]
21870    fn placement_affinity_none_when_field_is_none() {
21871        // The absent-`:affinity` arm of the per-`:placement`
21872        // M3-Adaptive-compression-hint accessor pin: when the typed
21873        // slot is absent — the canonical shape of an Aplicacao that
21874        // leaves the compression weighting up to the placement engine's
21875        // cluster-default arm — [`Placement::affinity`] must return
21876        // `None`. Pins against a future silent detour that projected
21877        // the absent slot to a `Some("")` empty-string default (the
21878        // canonical `Option<String>` → `String` collapse footgun the
21879        // sibling M2 [`crate::LimitsSpec::is_empty`] /
21880        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
21881        // already guard on the peer M2 typed-slot surfaces), a
21882        // `Some("None")` stringified-None round-trip, a `Some` arm
21883        // whose contents were derived from a sibling slot (an
21884        // accidental fallback to `estrategia.as_str()` that read the
21885        // strategy discriminator into the hint axis), or a
21886        // `Some("default")` implicit-default that would silently biases
21887        // the routing without the author having written one. Three
21888        // placements sweep the accept-set every `validate`-passing
21889        // `:affinity None` shape lands on — one per PlacementStrategy
21890        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
21891        // with a shard-key), since `:affinity` is orthogonal to
21892        // `:estrategia` in the typed grammar.
21893        for (estrategia, shard_key) in [
21894            (PlacementStrategy::SingleNode, None),
21895            (PlacementStrategy::Replicated, None),
21896            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
21897        ] {
21898            let p = Placement {
21899                estrategia,
21900                clusters: vec!["rio".into()],
21901                affinity: None,
21902                shard_key,
21903            };
21904            assert!(
21905                p.affinity().is_none(),
21906                "Placement::affinity must return None when the typed \
21907                 slot is absent under :estrategia {estrategia:?} (got {:?})",
21908                p.affinity(),
21909            );
21910            assert_eq!(
21911                p.affinity(),
21912                p.affinity.as_deref(),
21913                "Placement::affinity must byte-equal the .affinity \
21914                 field's `.as_deref()` projection in the absent arm",
21915            );
21916        }
21917    }
21918
21919    #[test]
21920    fn placement_affinity_borrows_from_affinity_storage() {
21921        // The borrow-not-copy pin: [`Placement::affinity`] must return
21922        // an `Option<&str>` whose `Some` arm borrows from the typed
21923        // slot's own [`String`] storage — same-address invariant with
21924        // `p.affinity.as_deref().unwrap()`. Pins against a future
21925        // silent detour that allocated a fresh `String`
21926        // (`self.affinity.clone().map(...)` in the body would type-
21927        // check but silently drop the borrow, and every downstream
21928        // consumer that assumed the returned slice outlives `&self`
21929        // would break on a stale-reference use-after-free — the
21930        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
21931        // gate reads the accessor's `&str` return through the
21932        // [`validate_placement_affinity`] `&str` parameter and would
21933        // silently misbehave if this accessor produced a detached
21934        // copy). Peer of the sibling per-`:placement`
21935        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
21936        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
21937        // extends the discipline onto the sibling per-`:placement`
21938        // M3-Adaptive-compression-hint arm.
21939        let p = Placement {
21940            estrategia: PlacementStrategy::Replicated,
21941            clusters: vec!["rio".into()],
21942            affinity: Some("data-locality".into()),
21943            shard_key: None,
21944        };
21945        let hint = p.affinity().expect("Some arm");
21946        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
21947        assert_eq!(
21948            hint.as_ptr(),
21949            storage_slice.as_ptr(),
21950            "Placement::affinity must borrow from the .affinity \
21951             String's backing storage — a fresh allocation here means \
21952             the accessor no longer names the substrate-primitive typed \
21953             dispatch and every downstream consumer would silently \
21954             carry a detached copy",
21955        );
21956        assert_eq!(
21957            hint.len(),
21958            storage_slice.len(),
21959            "Placement::affinity and .affinity.as_deref() must byte-\
21960             equal in length as well as in address",
21961        );
21962    }
21963
21964    #[test]
21965    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
21966        // The canonical per-`:placement` distribution-strategy-scalar
21967        // pin: [`Placement::estrategia`] must return the `:placement
21968        // :estrategia` field verbatim as a [`PlacementStrategy`],
21969        // `Copy`-projected from the typed slot's own `PlacementStrategy`
21970        // storage across every variant in the closed accept-set
21971        // (`SingleNode` — Erlang/OTP distributed-app takeover;
21972        // `Replicated` — active-active across every named cluster;
21973        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
21974        // against a future silent detour that re-derived the strategy
21975        // from a peer axis (an accidental fallback to
21976        // `if shard_key.is_some() { Sharded } else { Replicated }`
21977        // collapse that read the shard-key axis into the strategy
21978        // discriminator), a variant remap the operator authors on one
21979        // consumer without the other, or a stale-derive detour that
21980        // substituted [`PlacementStrategy::default`] when the field
21981        // held any explicit variant (which would silently collapse the
21982        // distinction between "author explicitly declared `:estrategia
21983        // Replicated`" and "author omitted the slot and inherited the
21984        // default" the future per-cluster override slot depends on).
21985        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
21986        // pin on the `Copy`-return `u16` scalar axis — same "the
21987        // substrate-primitive accessor must byte-equal the raw field
21988        // access verbatim across every author-declared value" discipline
21989        // extended onto the per-`:placement` distribution-strategy
21990        // `Copy`-composite-enum scalar axis.
21991        for estrategia in [
21992            PlacementStrategy::SingleNode,
21993            PlacementStrategy::Replicated,
21994            PlacementStrategy::Sharded,
21995        ] {
21996            // Route the paired `:shard-key` fixture-builder through the
21997            // typed cross-slot invariant predicate
21998            // [`PlacementStrategy::requires_shard_key`] rather than the
21999            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
22000            // arm-identity predicate — same discipline the sibling
22001            // `placement_strategy_variants_round_trip` fixture builder now
22002            // reads through.
22003            let shard_key = estrategia
22004                .requires_shard_key()
22005                .then(|| "tenantId".to_string());
22006            let p = Placement {
22007                estrategia,
22008                clusters: vec!["rio".into()],
22009                affinity: None,
22010                shard_key,
22011            };
22012            assert_eq!(
22013                p.estrategia(),
22014                estrategia,
22015                "Placement::estrategia must return :placement :estrategia \
22016                 verbatim (got {:?}, expected {estrategia:?})",
22017                p.estrategia(),
22018            );
22019            assert_eq!(
22020                p.estrategia(),
22021                p.estrategia,
22022                "Placement::estrategia accessor and .estrategia field \
22023                 access must byte-equal — the accessor is the substrate-\
22024                 primitive typed dispatch every downstream distribution-\
22025                 strategy consumer must route through",
22026            );
22027        }
22028    }
22029
22030    #[test]
22031    fn validate_placement_reads_through_lifted_estrategia_accessor() {
22032        // Three-consumer coherence pin: the
22033        // [`AplicacaoSpec::validate_placement`]
22034        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
22035        // `estrategia:` field (which reads through
22036        // [`Placement::estrategia`] to name the strategy the empty
22037        // `:clusters` list was declared against), the same method's
22038        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
22039        // reads through [`Placement::estrategia`] to fan across the
22040        // shape-gate cascades), and the non-`Sharded`-arm
22041        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
22042        // `estrategia:` field (which reads through
22043        // [`Placement::estrategia`] to name the strategy the declared-
22044        // but-inert `:shard-key` was authored under) must all key off
22045        // the lifted accessor, so any future rebrand on the typed
22046        // slot's reader shape lands at exactly one place. Pins the
22047        // three-site coherence by exercising each error surface end-
22048        // to-end and asserting the surfaced `estrategia:` field byte-
22049        // equals the accessor's return. Peer of the sibling per-
22050        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
22051        // pin on the M3 mesh-slot `Copy`-return scalar axis.
22052
22053        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
22054        // whose `estrategia:` field must byte-equal the accessor's return
22055        // for every variant in the closed accept-set.
22056        for estrategia in [
22057            PlacementStrategy::SingleNode,
22058            PlacementStrategy::Replicated,
22059            PlacementStrategy::Sharded,
22060        ] {
22061            let mut spec = three_member_spec();
22062            spec.placement.estrategia = estrategia;
22063            spec.placement.clusters = Vec::new();
22064            // Route the paired `:shard-key` spec-mutator through the typed
22065            // cross-slot invariant predicate
22066            // [`PlacementStrategy::requires_shard_key`] rather than the
22067            // [`gen_platform::IsVariant`]-derived
22068            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
22069            // same discipline the sibling
22070            // `placement_strategy_variants_round_trip` and
22071            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
22072            // fixture builders now read through.
22073            spec.placement.shard_key = estrategia
22074                .requires_shard_key()
22075                .then(|| "tenantId".to_string());
22076            let err = spec.validate().unwrap_err();
22077            match err {
22078                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
22079                    assert_eq!(
22080                        e,
22081                        spec.placement.estrategia(),
22082                        "PlacementWithoutClusters.estrategia must byte-equal \
22083                         Placement::estrategia() — the error carrier reads \
22084                         through the lifted accessor",
22085                    );
22086                }
22087                other => panic!(
22088                    "expected PlacementWithoutClusters, got {other:?} for \
22089                     estrategia={estrategia:?}"
22090                ),
22091            }
22092        }
22093
22094        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
22095        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
22096        // must byte-equal the accessor's return for both non-`Sharded`
22097        // strategies.
22098        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
22099            let mut spec = three_member_spec();
22100            spec.placement.estrategia = estrategia;
22101            spec.placement.shard_key = Some("tenantId".into());
22102            let err = spec.validate().unwrap_err();
22103            match err {
22104                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
22105                    assert_eq!(
22106                        e,
22107                        spec.placement.estrategia(),
22108                        "ShardKeyOnNonSharded.estrategia must byte-equal \
22109                         Placement::estrategia() — the non-Sharded-arm \
22110                         refusal reads through the lifted accessor",
22111                    );
22112                }
22113                other => panic!(
22114                    "expected ShardKeyOnNonSharded, got {other:?} for \
22115                     estrategia={estrategia:?}"
22116                ),
22117            }
22118        }
22119    }
22120
22121    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
22122    //
22123    // The [`Placement::clusters`] accessor lift is the second slice-return
22124    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
22125    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
22126    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
22127    // below cover (1) the accessor's byte-equal projection against the raw
22128    // field access across the empty / singleton / cohort fixtures the
22129    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
22130    // and the per-cluster validate loop fan between, and (2) the two-
22131    // consumer coherence of the paired pre-flight refusal probe and the
22132    // per-cluster validate loop routing through the accessor on both arms.
22133
22134    #[test]
22135    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
22136        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
22137        // [`Placement::clusters`] must return the `:placement :clusters`
22138        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
22139        // the same backing buffer the raw `self.clusters.as_slice()`
22140        // field access borrows from, byte-equal across every
22141        // representative fixture in the accept-set — the empty slice
22142        // (the pre-validation sentinel every
22143        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
22144        // the singleton slice (the minimal `SingleNode`-shape cohort),
22145        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
22146        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
22147        //
22148        // Pins against a future silent detour that returned
22149        // `&Vec<String>` (which would type-check but leak the storage-
22150        // side `Vec`'s grow/push/reserve surface no consumer of the
22151        // typed view reaches for), a fresh-allocated `Vec<String>` copy
22152        // (which would type-check via a coercion but silently break
22153        // every downstream caller that relied on the slice sharing the
22154        // backing buffer's identity), or an out-of-order or length-
22155        // drifted projection (which would silently split the paired
22156        // pre-flight `.is_empty()` refusal probe's input from the per-
22157        // cluster validate loop's traversal input).
22158        //
22159        // Peer of the sibling M2
22160        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22161        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22162        // `:supervisor` static-child-list axis, extended onto the M3
22163        // per-`:placement` distribution-target-list `Vec`-carry axis.
22164        let fixtures: Vec<Vec<String>> = vec![
22165            Vec::new(),
22166            vec!["rio".into()],
22167            vec!["rio".into(), "mar".into()],
22168            vec!["rio".into(), "mar".into(), "plo".into()],
22169        ];
22170        for clusters in fixtures {
22171            let p = Placement {
22172                clusters: clusters.clone(),
22173                ..Placement::default()
22174            };
22175            assert_eq!(
22176                p.clusters(),
22177                clusters.as_slice(),
22178                "Placement::clusters must return :placement :clusters \
22179                 verbatim (got {:?}, expected {:?})",
22180                p.clusters(),
22181                clusters.as_slice(),
22182            );
22183            assert_eq!(
22184                p.clusters(),
22185                p.clusters.as_slice(),
22186                "Placement::clusters accessor and .clusters.as_slice() \
22187                 field access must byte-equal — the accessor is the \
22188                 substrate-primitive typed dispatch every downstream \
22189                 cluster-pool consumer must route through",
22190            );
22191            assert_eq!(
22192                p.clusters().len(),
22193                p.clusters.len(),
22194                "Placement::clusters().len() must byte-equal \
22195                 self.clusters.len() — a length-drift would silently \
22196                 split the paired pre-flight `.is_empty()` refusal \
22197                 probe input from the per-cluster validate loop's \
22198                 traversal input",
22199            );
22200        }
22201    }
22202
22203    #[test]
22204    fn validate_placement_reads_through_lifted_clusters_accessor() {
22205        // Two-consumer coherence pin: the
22206        // [`AplicacaoSpec::validate_placement`] pre-flight
22207        // `self.placement.clusters().is_empty()` refusal probe (which
22208        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
22209        // the accessor projects the empty slice) and the per-cluster
22210        // validate loop's `for c in self.placement.clusters()`
22211        // traversal (which must reach every entry in the same order
22212        // the accessor projects, so both the per-entry value-shape
22213        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
22214        // and the duplicate-detection HashSet insert that trips
22215        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
22216        // accessor's projection) must both key off the lifted
22217        // accessor, so any future rebrand on the typed slot's reader
22218        // shape lands at exactly one place. Pins the two-site
22219        // coherence by exercising each production consumer end-to-end:
22220        // (1) the `PlacementWithoutClusters` refusal under the empty
22221        // slice, (2) the `PlacementClusterInvalid` refusal fires on
22222        // the second entry of a two-cluster cohort whose head is
22223        // valid but tail is not (which requires the loop to reach the
22224        // second entry through the accessor), and (3) the
22225        // `PlacementClusterDuplicate` refusal fires on the second
22226        // entry of a two-cluster cohort that shares a name (which
22227        // requires the loop to reach both entries — a first-entry-only
22228        // projection would silently pass since the dedup HashSet has
22229        // room for the first insert).
22230        //
22231        // Peer of the sibling M2
22232        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22233        // (bc92bce) coherence pin on the per-`:supervisor` static-
22234        // child-list axis, extended onto the M3 per-`:placement`
22235        // distribution-target-list `Vec`-carry axis.
22236
22237        // (1) Pre-flight `.is_empty()` probe: the empty slice must
22238        // trip `PlacementWithoutClusters`.
22239        let mut spec = three_member_spec();
22240        spec.placement.clusters = Vec::new();
22241        match spec.validate().unwrap_err() {
22242            AplicacaoError::PlacementWithoutClusters { .. } => {}
22243            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
22244        }
22245        assert!(
22246            spec.placement.clusters().is_empty(),
22247            "the pre-flight refusal input must be the empty slice per \
22248             the accessor's projection",
22249        );
22250
22251        // (2) Per-cluster validate loop: a two-cluster cohort with an
22252        // invalid tail entry must trip `PlacementClusterInvalid` on
22253        // the tail — the loop must reach the second entry through
22254        // the accessor.
22255        let mut spec = three_member_spec();
22256        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
22257        match spec.validate().unwrap_err() {
22258            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
22259                assert_eq!(
22260                    cluster, "BAD_CLUSTER",
22261                    "PlacementClusterInvalid.cluster must carry the \
22262                     tail entry the loop reached through the accessor",
22263                );
22264            }
22265            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
22266        }
22267        assert_eq!(
22268            spec.placement.clusters().len(),
22269            2,
22270            "the per-cluster validate loop's traversal input must be \
22271             a two-element slice per the accessor's projection",
22272        );
22273
22274        // (3) Per-cluster validate loop: a two-cluster cohort that
22275        // shares a name must trip `PlacementClusterDuplicate` on the
22276        // second entry — the loop must reach both entries through the
22277        // accessor for the dedup HashSet's second insert to collide.
22278        let mut spec = three_member_spec();
22279        spec.placement.clusters = vec!["rio".into(), "rio".into()];
22280        match spec.validate().unwrap_err() {
22281            AplicacaoError::PlacementClusterDuplicate { cluster } => {
22282                assert_eq!(
22283                    cluster, "rio",
22284                    "PlacementClusterDuplicate.cluster must carry the \
22285                     shared cluster name verbatim",
22286                );
22287            }
22288            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
22289        }
22290        assert_eq!(
22291            spec.placement.clusters().len(),
22292            2,
22293            "the per-cluster validate loop's traversal input must be \
22294             a two-element slice per the accessor's projection",
22295        );
22296    }
22297
22298    #[test]
22299    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
22300        // The canonical per-`:membros` member-list-slice-shape pin:
22301        // [`AplicacaoSpec::membros`] must return the `:membros` typed
22302        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
22303        // same backing buffer the raw `self.membros.as_slice()` field
22304        // access borrows from, byte-equal across every representative
22305        // fixture in the accept-set — the empty slice (the pre-
22306        // validation sentinel every [`AplicacaoError::NoMembros`]
22307        // refusal keys off), the singleton slice (the minimal one-
22308        // Servico Aplicacao shape), and multi-entry cohorts (the peer
22309        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
22310        // load-bearing identity of the application graph).
22311        //
22312        // Pins against a future silent detour that returned
22313        // `&Vec<Membro>` (which would type-check but leak the storage-
22314        // side `Vec`'s grow/push/reserve surface no consumer of the
22315        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
22316        // (which would type-check via a coercion but silently break
22317        // every downstream caller that relied on the slice sharing the
22318        // backing buffer's identity), or an out-of-order or length-
22319        // drifted projection (which would silently split the paired
22320        // `HashSet<&str>` name-set seed's collect input from the
22321        // pre-flight `.is_empty()` refusal probe's input from the per-
22322        // member validate loop's traversal input from the
22323        // programs.yaml emitter's per-entry fan-out loop's input from
22324        // the `feira app graph` per-member print traversal's input).
22325        //
22326        // Peer of the sibling M2
22327        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22328        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22329        // `:supervisor` static-child-list axis and the sibling M3
22330        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22331        // (a6e18d7) `&[String]` byte-equal pin on the per-
22332        // `:placement` distribution-target-list axis — extends the
22333        // slice-return-accessor byte-equal-projection discipline onto
22334        // the outermost M3 mesh-slot type's per-Aplicacao member-list
22335        // `Vec`-carry axis.
22336        let fixtures: Vec<Vec<Membro>> = vec![
22337            Vec::new(),
22338            vec![membro("catalog", "^0.1")],
22339            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22340            vec![
22341                membro("catalog", "^0.1"),
22342                membro("cart", "^0.1"),
22343                membro("payment", "^0.2"),
22344            ],
22345        ];
22346        for membros in fixtures {
22347            let s = AplicacaoSpec {
22348                membros: membros.clone(),
22349                contratos: Vec::new(),
22350                politicas: MeshPolicy::default(),
22351                placement: Placement::default(),
22352                entrada: None,
22353            };
22354            assert_eq!(
22355                s.membros(),
22356                membros.as_slice(),
22357                "AplicacaoSpec::membros must return :membros verbatim \
22358                 (got {:?}, expected {:?})",
22359                s.membros(),
22360                membros.as_slice(),
22361            );
22362            assert_eq!(
22363                s.membros(),
22364                s.membros.as_slice(),
22365                "AplicacaoSpec::membros accessor and .membros.as_slice() \
22366                 field access must byte-equal — the accessor is the \
22367                 substrate-primitive typed dispatch every downstream \
22368                 member-list consumer must route through",
22369            );
22370            assert_eq!(
22371                s.membros().len(),
22372                s.membros.len(),
22373                "AplicacaoSpec::membros().len() must byte-equal \
22374                 self.membros.len() — a length-drift would silently \
22375                 split the paired `HashSet<&str>` name-set seed's \
22376                 collect input from the pre-flight `.is_empty()` \
22377                 refusal probe input from the per-member validate \
22378                 loop's traversal input",
22379            );
22380        }
22381    }
22382
22383    #[test]
22384    fn validate_reads_through_lifted_membros_accessor() {
22385        // Three-consumer coherence pin: the
22386        // [`AplicacaoSpec::validate_membros`] pre-flight
22387        // `self.membros().is_empty()` refusal probe (which must trip
22388        // [`AplicacaoError::NoMembros`] when the accessor projects the
22389        // empty slice), the same method's per-member validate loop's
22390        // `for m in self.membros()` traversal (which must reach every
22391        // entry in the same order the accessor projects, so both the
22392        // per-entry empty-`:caixa` gate that trips
22393        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
22394        // detection `insert_first_seen` that trips
22395        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
22396        // projection), and the peer [`AplicacaoSpec::validate`]'s
22397        // `HashSet<&str>` name-set seed's
22398        // `self.membros().iter().map(Membro::nome).collect()` collect
22399        // input (which every `:contratos` `:de` / `:para` membership
22400        // lookup rejects an unknown name against) must all three key
22401        // off the lifted accessor, so any future rebrand on the typed
22402        // slot's reader shape lands at exactly one place. Pins the
22403        // three-site coherence by exercising each production consumer
22404        // end-to-end: (1) the `NoMembros` refusal under the empty
22405        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
22406        // second entry of a two-member cohort whose head is valid but
22407        // tail has an empty `:caixa` (which requires the loop to
22408        // reach the second entry through the accessor), and (3) the
22409        // `MembroDuplicate` refusal fires on the second entry of a
22410        // two-member cohort that shares a `:caixa` name (which
22411        // requires the loop to reach both entries through the
22412        // accessor for the dedup HashSet's second insert to collide).
22413        //
22414        // Peer of the sibling M2
22415        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22416        // (bc92bce) coherence pin on the per-`:supervisor` static-
22417        // child-list axis and the sibling M3
22418        // `validate_placement_reads_through_lifted_clusters_accessor`
22419        // (a6e18d7) coherence pin on the per-`:placement` distribution-
22420        // target-list axis — extends the slice-return-accessor
22421        // multi-consumer coherence discipline onto the outermost M3
22422        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
22423
22424        // (1) Pre-flight `.is_empty()` probe: the empty slice must
22425        // trip `NoMembros`.
22426        let mut spec = three_member_spec();
22427        spec.membros = Vec::new();
22428        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
22429        assert!(
22430            spec.membros().is_empty(),
22431            "the pre-flight refusal input must be the empty slice per \
22432             the accessor's projection",
22433        );
22434
22435        // (2) Per-member validate loop: a two-member cohort with an
22436        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
22437        // the tail — the loop must reach the second entry through
22438        // the accessor.
22439        let mut spec = three_member_spec();
22440        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
22441        assert_eq!(
22442            spec.validate().unwrap_err(),
22443            AplicacaoError::MembroCaixaEmpty,
22444        );
22445        assert_eq!(
22446            spec.membros().len(),
22447            2,
22448            "the per-member validate loop's traversal input must be \
22449             a two-element slice per the accessor's projection",
22450        );
22451
22452        // (3) Per-member validate loop: a two-member cohort that
22453        // shares a `:caixa` name must trip `MembroDuplicate` on the
22454        // second entry — the loop must reach both entries through the
22455        // accessor for the dedup HashSet's second insert to collide.
22456        let mut spec = three_member_spec();
22457        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
22458        match spec.validate().unwrap_err() {
22459            AplicacaoError::MembroDuplicate { caixa } => {
22460                assert_eq!(
22461                    caixa, "catalog",
22462                    "MembroDuplicate.caixa must carry the shared \
22463                     member name verbatim",
22464                );
22465            }
22466            other => panic!("expected MembroDuplicate, got {other:?}"),
22467        }
22468        assert_eq!(
22469            spec.membros().len(),
22470            2,
22471            "the per-member validate loop's traversal input must be \
22472             a two-element slice per the accessor's projection",
22473        );
22474    }
22475
22476    #[test]
22477    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
22478        // The canonical per-`:contratos` contract-list-slice-shape pin:
22479        // [`AplicacaoSpec::contratos`] must return the `:contratos`
22480        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
22481        // slice-view over the same backing buffer the raw
22482        // `self.contratos.as_slice()` field access borrows from, byte-
22483        // equal across every representative fixture in the accept-set —
22484        // the empty slice (the pre-validation "internal-only mesh" shape
22485        // an Aplicacao whose members exchange no typed edges renders
22486        // through), the singleton slice (the minimal one-edge Aplicacao
22487        // shape), and multi-entry cohorts (the peer multi-edge shapes
22488        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
22489        // of the application graph).
22490        //
22491        // Pins against a future silent detour that returned
22492        // `&Vec<WitContract>` (which would type-check but leak the
22493        // storage-side `Vec`'s grow/push/reserve surface no consumer of
22494        // the typed view reaches for), a fresh-allocated
22495        // `Vec<WitContract>` copy (which would type-check via a coercion
22496        // but silently break every downstream caller that relied on the
22497        // slice sharing the backing buffer's identity), or an out-of-
22498        // order or length-drifted projection (which would silently split
22499        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
22500        // seed's traversal input from the `detect_sync_cycles` per-edge
22501        // adjacency-list seed's traversal input from the
22502        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
22503        // BTreeMap grouping loop's traversal input from the
22504        // `feira app graph` per-contract print traversal's input).
22505        //
22506        // Peer of the immediately-adjacent sibling M3
22507        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22508        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22509        // node-list axis, the sibling M3
22510        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22511        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
22512        // distribution-target-list axis, and the sibling M2
22513        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22514        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22515        // `:supervisor` static-child-list axis — extends the slice-
22516        // return-accessor byte-equal-projection discipline onto the
22517        // outermost M3 mesh-slot type's per-Aplicacao contract-list
22518        // `Vec`-carry axis, closing the last unlifted per-
22519        // `AplicacaoSpec` `Vec`-carry axis.
22520        let fixtures: Vec<Vec<WitContract>> = vec![
22521            Vec::new(),
22522            vec![contract_http("cart", "catalog", "/products/:id")],
22523            vec![
22524                contract_http("cart", "catalog", "/products/:id"),
22525                contract_http("cart", "payment", "/charge"),
22526            ],
22527            vec![
22528                contract_http("cart", "catalog", "/products/:id"),
22529                contract_http("cart", "payment", "/charge"),
22530                contract_http("payment", "catalog", "/audit"),
22531            ],
22532        ];
22533        for contratos in fixtures {
22534            let s = AplicacaoSpec {
22535                membros: vec![
22536                    membro("catalog", "^0.1"),
22537                    membro("cart", "^0.1"),
22538                    membro("payment", "^0.2"),
22539                ],
22540                contratos: contratos.clone(),
22541                politicas: MeshPolicy::default(),
22542                placement: Placement::default(),
22543                entrada: None,
22544            };
22545            assert_eq!(
22546                s.contratos(),
22547                contratos.as_slice(),
22548                "AplicacaoSpec::contratos must return :contratos verbatim \
22549                 (got {:?}, expected {:?})",
22550                s.contratos(),
22551                contratos.as_slice(),
22552            );
22553            assert_eq!(
22554                s.contratos(),
22555                s.contratos.as_slice(),
22556                "AplicacaoSpec::contratos accessor and \
22557                 .contratos.as_slice() field access must byte-equal — \
22558                 the accessor is the substrate-primitive typed dispatch \
22559                 every downstream contract-list consumer must route \
22560                 through",
22561            );
22562            assert_eq!(
22563                s.contratos().len(),
22564                s.contratos.len(),
22565                "AplicacaoSpec::contratos().len() must byte-equal \
22566                 self.contratos.len() — a length-drift would silently \
22567                 split the paired per-edge validate-loop's traversal \
22568                 input from the sync-cycle adjacency-list seed's \
22569                 traversal input from the cilium_network_policies \
22570                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
22571                 input from the `feira app graph` per-contract print \
22572                 traversal's input",
22573            );
22574        }
22575    }
22576
22577    #[test]
22578    fn validate_reads_through_lifted_contratos_accessor() {
22579        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
22580        // per-`:contratos` validate-loop's `for c in self.contratos()`
22581        // traversal (which must reach every entry in the same order the
22582        // accessor projects, so both the per-entry
22583        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
22584        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
22585        // dedup `HashSet` insert key off the accessor's projection),
22586        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
22587        // `for c in self.contratos()` adjacency-list seed (which drives
22588        // the sync-subgraph deadlock-detection gate via
22589        // [`AplicacaoError::SyncCycle`]), and the peer
22590        // [`caixa_mesh::cilium_network_policies`]'s
22591        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
22592        // grouping loop (which drives the per-CNP fan-out) must all
22593        // three key off the lifted accessor, so any future rebrand on
22594        // the typed slot's reader shape lands at exactly one place. Pins
22595        // the three-site coherence by exercising the two caixa-core
22596        // production consumers end-to-end: (1) the empty-`:contratos`
22597        // slice must validate without a per-edge diagnostic (the
22598        // per-edge loop is a no-op under the empty projection), (2) the
22599        // `ContratoMemberMissing` refusal fires on the second entry of a
22600        // two-edge cohort whose head references a valid member but tail
22601        // references a phantom name (which requires the loop to reach
22602        // the second entry through the accessor), and (3) the
22603        // `SyncCycle` refusal fires on a self-referential two-edge
22604        // cohort through the sync-cycle detector's peer projection
22605        // (which requires the detector to iterate the accessor's
22606        // projection to add the back-edge to its adjacency list).
22607        //
22608        // Peer of the sibling M3
22609        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22610        // three-consumer coherence pin on the per-`:membros` node-list
22611        // axis and the sibling M3
22612        // `validate_placement_reads_through_lifted_clusters_accessor`
22613        // (a6e18d7) coherence pin on the per-`:placement` distribution-
22614        // target-list axis — extends the slice-return-accessor multi-
22615        // consumer coherence discipline onto the outermost M3 mesh-slot
22616        // type's per-Aplicacao contract-list `Vec`-carry axis.
22617
22618        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
22619        // and no per-edge diagnostic surfaces. Validate succeeds on
22620        // the well-formed `:membros` head.
22621        let mut spec = three_member_spec();
22622        spec.contratos = Vec::new();
22623        assert!(
22624            spec.validate().is_ok(),
22625            "empty :contratos must validate — the per-edge loop is a \
22626             no-op under the accessor's empty projection",
22627        );
22628        assert!(
22629            spec.contratos().is_empty(),
22630            "the per-edge validate loop's traversal input must be the \
22631             empty slice per the accessor's projection",
22632        );
22633
22634        // (2) Per-edge validate loop: a two-edge cohort whose tail
22635        // references a phantom `:para` member must trip
22636        // `ContratoMemberMissing` on the tail — the loop must reach
22637        // the second entry through the accessor for the membership
22638        // lookup to fail on the phantom name.
22639        let mut spec = three_member_spec();
22640        spec.contratos = vec![
22641            contract_http("cart", "catalog", "/products/:id"),
22642            contract_http("cart", "phantom", "/x"),
22643        ];
22644        let err = spec.validate().unwrap_err();
22645        assert!(
22646            matches!(
22647                err,
22648                AplicacaoError::ContratoMemberMissing { ref caixa }
22649                    if caixa == "phantom"
22650            ),
22651            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
22652        );
22653        assert_eq!(
22654            spec.contratos().len(),
22655            2,
22656            "the per-edge validate loop's traversal input must be \
22657             a two-element slice per the accessor's projection",
22658        );
22659
22660        // (3) Sync-cycle detector: a two-edge synchronous cohort
22661        // whose second edge closes the sync-subgraph back onto the
22662        // first must trip [`AplicacaoError::ContratoCycle`] — the
22663        // detector must iterate the accessor's projection to add
22664        // both edges to its adjacency list, so a length-drift on
22665        // the accessor's projection would silently disagree with
22666        // the sync-cycle detector on which edge closes the loop.
22667        // Peer projection to the `validate` per-edge loop above:
22668        // the sync-cycle detector routes through the same lifted
22669        // accessor, so a rebrand of the reader shape lands at one
22670        // place. Uses a two-edge cohort (cart → catalog → cart)
22671        // because the per-edge `ContratoSelfLoop` gate fires before
22672        // the sync-cycle detector on a single self-referential edge
22673        // (`cart → cart`) — the cycle-detector's input must be a
22674        // multi-edge cohort for its per-edge traversal input to be
22675        // observably wider than the per-edge validate loop's input.
22676        let mut spec = three_member_spec();
22677        spec.contratos = vec![
22678            contract_http("cart", "catalog", "/products/:id"),
22679            contract_http("catalog", "cart", "/callback"),
22680        ];
22681        let err = spec.validate().unwrap_err();
22682        assert!(
22683            matches!(err, AplicacaoError::ContratoCycle { .. }),
22684            "expected ContratoCycle from the sync-cycle detector on a \
22685             two-edge back-edge cohort, got {err:?}",
22686        );
22687        assert_eq!(
22688            spec.contratos().len(),
22689            2,
22690            "the sync-cycle detector's traversal input must be a \
22691             two-element slice per the accessor's projection",
22692        );
22693    }
22694
22695    #[test]
22696    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
22697        // The canonical per-`:politicas` outer-composite-reference-shape
22698        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
22699        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
22700        // the same backing storage the raw `&self.politicas` field
22701        // access borrows from, byte-equal across every representative
22702        // fixture in the accept-set — the default `MeshPolicy` (the
22703        // author-empty "no policy on any axis" shape whose
22704        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
22705        // shapes carrying one axis at a time
22706        // (`{mtls_required, timeout, retries, circuit_breaker,
22707        // rate_limit}` — the minimal five-axis fan-out over the
22708        // per-axis lifted accessor family every downstream mesh-artifact
22709        // emitter dispatches on), and the multi-axis composite (the
22710        // canonical `three_member_spec` fixture's `{timeout, retries,
22711        // mtls_required}` triple — the load-bearing shape every
22712        // Aplicacao-scoped fixture in this suite constructs).
22713        //
22714        // Pins against a future silent detour that returned a fresh-
22715        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
22716        // impl but silently break every downstream caller that relied
22717        // on the reference sharing the composite's backing identity), a
22718        // reference to an operator-resolved overlay (the future
22719        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
22720        // acknowledges — its resolution must land at exactly this
22721        // accessor body, not silently divert the raw slot away from a
22722        // second consumer), or an axis-shuffled projection (a future
22723        // detour that swapped `timeout` and `retries` through the
22724        // accessor would silently split the paired `validate_politicas`
22725        // per-axis bracket-dispatch's traversal input from the peer
22726        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
22727        // emitter's fan-out input from the peer
22728        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
22729        // overlay emitter's fan-out input).
22730        //
22731        // Peer of the sibling M3
22732        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22733        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22734        // node-list `Vec`-carry axis and the sibling M3
22735        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
22736        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
22737        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
22738        // accessor byte-equal-projection discipline onto the outermost
22739        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
22740        // reference axis, the first `&Composite`-return accessor on the
22741        // outer [`AplicacaoSpec`] type.
22742        let fixtures: Vec<MeshPolicy> = vec![
22743            MeshPolicy::default(),
22744            MeshPolicy {
22745                mtls_required: Some(true),
22746                ..MeshPolicy::default()
22747            },
22748            MeshPolicy {
22749                mtls_required: Some(false),
22750                ..MeshPolicy::default()
22751            },
22752            MeshPolicy {
22753                timeout: Some(Duration::from_secs(30)),
22754                ..MeshPolicy::default()
22755            },
22756            MeshPolicy {
22757                retries: Some(3),
22758                ..MeshPolicy::default()
22759            },
22760            MeshPolicy {
22761                circuit_breaker: Some(CircuitBreaker {
22762                    max_failures: 5,
22763                    window: Duration::from_secs(30),
22764                }),
22765                ..MeshPolicy::default()
22766            },
22767            MeshPolicy {
22768                rate_limit: Some(RateLimit {
22769                    rate: 100,
22770                    window: Duration::from_secs(1),
22771                }),
22772                ..MeshPolicy::default()
22773            },
22774            MeshPolicy {
22775                timeout: Some(Duration::from_secs(30)),
22776                retries: Some(3),
22777                mtls_required: Some(true),
22778                ..MeshPolicy::default()
22779            },
22780        ];
22781        for politicas in fixtures {
22782            let s = AplicacaoSpec {
22783                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22784                contratos: Vec::new(),
22785                politicas: politicas.clone(),
22786                placement: Placement::default(),
22787                entrada: None,
22788            };
22789            assert_eq!(
22790                *s.politicas(),
22791                politicas,
22792                "AplicacaoSpec::politicas must return :politicas verbatim \
22793                 (got {:?}, expected {:?})",
22794                s.politicas(),
22795                politicas,
22796            );
22797            assert!(
22798                std::ptr::eq(s.politicas(), &s.politicas),
22799                "AplicacaoSpec::politicas accessor and &self.politicas \
22800                 field access must borrow the same backing storage — \
22801                 the accessor is the substrate-primitive typed dispatch \
22802                 every downstream mesh-policy composite consumer must \
22803                 route through, and a reference-identity split would \
22804                 silently break every consumer that relied on the \
22805                 borrow sharing the composite's storage",
22806            );
22807            assert_eq!(
22808                s.politicas().is_empty(),
22809                s.politicas.is_empty(),
22810                "AplicacaoSpec::politicas().is_empty() must byte-equal \
22811                 self.politicas.is_empty() — an emptiness-drift would \
22812                 silently split the paired `validate_politicas` \
22813                 per-axis bracket-dispatch's seed from the peer \
22814                 caixa-mesh CNP mTLS-overlay emitter's key from the \
22815                 peer caixa-mesh HTTPRoute timeout+retry overlay \
22816                 emitter's key",
22817            );
22818        }
22819    }
22820
22821    #[test]
22822    fn validate_politicas_reads_through_lifted_politicas_accessor() {
22823        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
22824        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
22825        // followed by the per-axis fan-out `p.timeout()` /
22826        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
22827        // the lifted axis-level accessor family) must key off the
22828        // lifted outer accessor, so any future rebrand on the typed
22829        // slot's outer-composite reader shape lands at exactly one
22830        // place. Pins the multi-axis coherence by exercising each
22831        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
22832        // a `Some(Duration::ZERO)` timeout under the outer accessor's
22833        // reference projection, (2) `PolicyRetriesZero` fires on a
22834        // `Some(0)` retries under the same projection, and (3) an
22835        // empty [`MeshPolicy::default`] passes `validate_politicas` —
22836        // the outer accessor's reference-projection reaches every
22837        // per-axis branch without silently short-circuiting any.
22838        //
22839        // Peer of the sibling M3
22840        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22841        // three-consumer coherence pin on the per-`:membros` node-list
22842        // axis and the sibling M3
22843        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
22844        // three-consumer coherence pin on the per-`:contratos`
22845        // edge-list axis — extends the multi-consumer coherence
22846        // discipline onto the outermost M3 mesh-slot type's per-
22847        // Aplicacao mesh-policy composite-reference axis, the first
22848        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
22849        // type.
22850
22851        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
22852        // reference projection: a `Some(Duration::ZERO)` timeout must
22853        // trip the zero-floor gate. The bracket-dispatch's first arm
22854        // reads `p.timeout()` on the reference returned by the outer
22855        // accessor.
22856        let mut spec = three_member_spec();
22857        spec.politicas.timeout = Some(Duration::ZERO);
22858        spec.politicas.retries = None;
22859        spec.politicas.circuit_breaker = None;
22860        spec.politicas.rate_limit = None;
22861        assert_eq!(
22862            spec.validate().unwrap_err(),
22863            AplicacaoError::PolicyTimeoutZero,
22864        );
22865        assert!(
22866            std::ptr::eq(spec.politicas(), &spec.politicas),
22867            "the `validate_politicas` per-axis bracket-dispatch's \
22868             traversal input must be the same backing composite the \
22869             accessor's reference projection borrows from",
22870        );
22871
22872        // (2) `PolicyRetriesZero` refusal under the outer accessor's
22873        // reference projection: a `Some(0)` retries must trip the
22874        // zero-floor gate. The bracket-dispatch's second arm reads
22875        // `p.retries()` on the reference returned by the outer accessor.
22876        let mut spec = three_member_spec();
22877        spec.politicas.timeout = None;
22878        spec.politicas.retries = Some(0);
22879        spec.politicas.circuit_breaker = None;
22880        spec.politicas.rate_limit = None;
22881        assert_eq!(
22882            spec.validate().unwrap_err(),
22883            AplicacaoError::PolicyRetriesZero,
22884        );
22885
22886        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
22887        // — every per-axis arm short-circuits on `None`, so the outer
22888        // accessor's reference projection reaches the fall-through
22889        // `Ok(())` without any per-axis refusal firing.
22890        let mut spec = three_member_spec();
22891        spec.politicas = MeshPolicy::default();
22892        assert!(
22893            spec.validate().is_ok(),
22894            "an empty `MeshPolicy` must pass `validate_politicas` — \
22895             every per-axis arm short-circuits on `None` under the \
22896             outer accessor's reference projection",
22897        );
22898        assert!(
22899            spec.politicas().is_empty(),
22900            "the outer accessor's reference projection must be the \
22901             empty composite per the `MeshPolicy::default()` fixture",
22902        );
22903    }
22904
22905    #[test]
22906    #[allow(clippy::too_many_lines)]
22907    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
22908        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
22909        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
22910        // must both key off the lifted axis-level accessors
22911        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
22912        // the peer `:circuit-breaker` / `:rate-limit` arms already
22913        // routing through [`MeshPolicy::circuit_breaker`] /
22914        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
22915        // per axis on the substrate primitive" shape at the fan-out
22916        // (four axes, four accessors, no raw-field-access site
22917        // anywhere on the bracket-dispatch). Pins the per-axis
22918        // coherence at the accept-set boundaries the bracket carves:
22919        //   1. accessor byte-equal to raw field on every representative
22920        //      accept-set value (`None`, sub-cap, at-cap, past-cap
22921        //      sentinel) — a future accessor drift that no longer
22922        //      shipped the raw slot verbatim would surface here,
22923        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
22924        //      routed through the accessor's projection, proving the
22925        //      first arm reads through the accessor rather than a
22926        //      silent-detour peer-axis field access,
22927        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
22928        //      through the accessor's projection, proving the second
22929        //      arm reads through the accessor,
22930        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
22931        //      passes validate under the accessor projection (paired
22932        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
22933        //      sibling axis), pinning the upper-boundary accept-arm
22934        //      also routes through the accessor.
22935        //
22936        // Peer of the sibling M3
22937        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
22938        // outer-composite-reference coherence pin (which asserts the
22939        // `let p = self.politicas()` seed); extends the discipline onto
22940        // the per-axis fan-out layer that consumes the seed's
22941        // reference. Same shape as
22942        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
22943        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22944        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
22945        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
22946
22947        // (1) Accessor byte-equal to raw field on the `:timeout` axis
22948        // across the accept-set boundaries the bracket dispatch's
22949        // three-arm gate carves out
22950        // ([`crate::render::require_positive_canonical_bounded_duration`]
22951        // — zero-floor + canonical-form + upper-cap).
22952        for timeout in [
22953            None,
22954            Some(Duration::ZERO),
22955            Some(Duration::from_millis(1)),
22956            Some(POLICY_TIMEOUT_MAX),
22957        ] {
22958            let p = MeshPolicy {
22959                timeout,
22960                ..MeshPolicy::default()
22961            };
22962            assert_eq!(
22963                p.timeout(),
22964                p.timeout,
22965                "MeshPolicy::timeout accessor must byte-equal the raw \
22966                 .timeout field across every accept-set boundary the \
22967                 validate_politicas :timeout arm carves out — a drift \
22968                 here would silently split the validate bracket's arm \
22969                 from the peer caixa-mesh HTTPRoute timeout-overlay \
22970                 emitter's read",
22971            );
22972        }
22973
22974        // (2) Accessor byte-equal to raw field on the `:retries` axis
22975        // across the accept-set boundaries the bracket dispatch's
22976        // two-arm gate carves out
22977        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
22978        // + upper-cap).
22979        for retries in [
22980            None,
22981            Some(0u32),
22982            Some(1u32),
22983            Some(POLICY_RETRIES_MAX),
22984            Some(POLICY_RETRIES_MAX + 1),
22985            Some(u32::MAX),
22986        ] {
22987            let p = MeshPolicy {
22988                retries,
22989                ..MeshPolicy::default()
22990            };
22991            assert_eq!(
22992                p.retries(),
22993                p.retries,
22994                "MeshPolicy::retries accessor must byte-equal the raw \
22995                 .retries field across every accept-set boundary the \
22996                 validate_politicas :retries arm carves out — a drift \
22997                 here would silently split the validate bracket's arm \
22998                 from the peer caixa-mesh HTTPRoute retry-overlay \
22999                 emitter's read",
23000            );
23001        }
23002
23003        // (3) `PolicyTimeoutZero` fires on the accessor-projected
23004        // zero-floor boundary. A silent detour that no longer read
23005        // through `p.timeout()` (a peer-axis field read, an accidental
23006        // Option::and-then chain that collapsed the None arm to Some,
23007        // an accessor rebrand that clamped the return through the
23008        // upper cap) would fail to refuse here.
23009        let mut spec = three_member_spec();
23010        spec.politicas.timeout = Some(Duration::ZERO);
23011        spec.politicas.retries = None;
23012        spec.politicas.circuit_breaker = None;
23013        spec.politicas.rate_limit = None;
23014        assert_eq!(
23015            spec.politicas().timeout(),
23016            Some(Duration::ZERO),
23017            "the accessor projection must reflect the fixture's \
23018             `Some(Duration::ZERO)` :timeout verbatim",
23019        );
23020        assert_eq!(
23021            spec.validate().unwrap_err(),
23022            AplicacaoError::PolicyTimeoutZero,
23023            "the validate_politicas :timeout zero-floor arm must fire \
23024             through the lifted accessor's projection — a silent \
23025             detour to a peer-axis field would fail to refuse",
23026        );
23027
23028        // (4) `PolicyRetriesZero` fires on the accessor-projected
23029        // zero-floor boundary on the sibling `:retries` axis.
23030        let mut spec = three_member_spec();
23031        spec.politicas.timeout = None;
23032        spec.politicas.retries = Some(0);
23033        spec.politicas.circuit_breaker = None;
23034        spec.politicas.rate_limit = None;
23035        assert_eq!(
23036            spec.politicas().retries(),
23037            Some(0),
23038            "the accessor projection must reflect the fixture's \
23039             `Some(0)` :retries verbatim",
23040        );
23041        assert_eq!(
23042            spec.validate().unwrap_err(),
23043            AplicacaoError::PolicyRetriesZero,
23044            "the validate_politicas :retries zero-floor arm must fire \
23045             through the lifted accessor's projection — a silent \
23046             detour to a peer-axis field would fail to refuse",
23047        );
23048
23049        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
23050        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
23051        // must pass validate under the accessor projection — pins the
23052        // upper-boundary accept-arm also routes through the lifted
23053        // accessor (a drift that clamped or short-circuited at the
23054        // upper boundary would fail the whole-spec validate here).
23055        let mut spec = three_member_spec();
23056        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
23057        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
23058        spec.politicas.circuit_breaker = None;
23059        spec.politicas.rate_limit = None;
23060        assert_eq!(
23061            spec.politicas().timeout(),
23062            Some(POLICY_TIMEOUT_MAX),
23063            "the accessor projection must reflect the fixture's \
23064             at-cap :timeout verbatim",
23065        );
23066        assert_eq!(
23067            spec.politicas().retries(),
23068            Some(POLICY_RETRIES_MAX),
23069            "the accessor projection must reflect the fixture's \
23070             at-cap :retries verbatim",
23071        );
23072        assert!(
23073            spec.validate().is_ok(),
23074            "at-cap :timeout + :retries must pass validate under the \
23075             accessor projection — the upper-boundary accept-arm on \
23076             both axes routes through the lifted accessor",
23077        );
23078    }
23079
23080    #[test]
23081    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
23082        // The canonical per-`:placement` outer-composite-reference-shape
23083        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
23084        // typed `Placement` verbatim as a `&Placement` reference over the
23085        // same backing storage the raw `&self.placement` field access
23086        // borrows from, byte-equal across every representative fixture in
23087        // the accept-set — the default `Placement` (the substrate seed
23088        // shape whose [`PlacementStrategy::default`] evaluates to
23089        // `SingleNode` with an empty `:clusters` pool and both
23090        // optional-scalar axes `None`), and every canonical strategy /
23091        // cluster-pool / optional-scalar combination the
23092        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
23093        // three [`PlacementStrategy`] variants — `SingleNode`,
23094        // `Replicated`, `Sharded` — cross-projected with a non-empty
23095        // `:clusters` pool and, on the `Sharded` arm, a non-empty
23096        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
23097        // canonical `three_member_spec` `Replicated` fixture's
23098        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
23099        //
23100        // Pins against a future silent detour that returned a fresh-
23101        // cloned `Placement` copy (which would type-check via a `Clone`
23102        // impl but silently break every downstream caller that relied on
23103        // the reference sharing the composite's backing identity), a
23104        // reference to an operator-resolved overlay (the future per-
23105        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
23106        // acknowledges — its resolution must land at exactly this
23107        // accessor body, not silently divert the raw slot away from a
23108        // second consumer), or an axis-shuffled projection (a future
23109        // detour that swapped `clusters` and `affinity` through the
23110        // accessor would silently split the paired `validate_placement`
23111        // per-axis bracket-dispatch's traversal input from the peer
23112        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
23113        // programs.yaml distribution-annotation emitter's fan-out input
23114        // from the peer `feira app graph` per-Aplicacao print line's
23115        // input).
23116        //
23117        // Peer of the sibling M3
23118        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23119        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
23120        // outer mesh-policy composite-reference axis, and of the sibling
23121        // slice-return `aplicacao_spec_membros_returns_membros_slice_
23122        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
23123        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
23124        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
23125        // the outer-accessor byte-equal-projection discipline onto the
23126        // outermost M3 mesh-slot type's per-Aplicacao distribution
23127        // composite-reference axis, the second `&Composite`-return
23128        // accessor on the outer [`AplicacaoSpec`] type.
23129        let fixtures: Vec<Placement> = vec![
23130            Placement::default(),
23131            Placement {
23132                estrategia: PlacementStrategy::SingleNode,
23133                clusters: vec!["rio".into()],
23134                affinity: None,
23135                shard_key: None,
23136            },
23137            Placement {
23138                estrategia: PlacementStrategy::Replicated,
23139                clusters: vec!["rio".into(), "mar".into()],
23140                affinity: None,
23141                shard_key: None,
23142            },
23143            Placement {
23144                estrategia: PlacementStrategy::Replicated,
23145                clusters: vec!["rio".into(), "mar".into()],
23146                affinity: Some("data-locality".into()),
23147                shard_key: None,
23148            },
23149            Placement {
23150                estrategia: PlacementStrategy::Sharded,
23151                clusters: vec!["rio".into(), "mar".into()],
23152                affinity: None,
23153                shard_key: Some("tenantId".into()),
23154            },
23155            Placement {
23156                estrategia: PlacementStrategy::Sharded,
23157                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
23158                affinity: Some("low-latency".into()),
23159                shard_key: Some("metadata.tenantId".into()),
23160            },
23161        ];
23162        for placement in fixtures {
23163            let s = AplicacaoSpec {
23164                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23165                contratos: Vec::new(),
23166                politicas: MeshPolicy::default(),
23167                placement: placement.clone(),
23168                entrada: None,
23169            };
23170            assert_eq!(
23171                *s.placement(),
23172                placement,
23173                "AplicacaoSpec::placement must return :placement verbatim \
23174                 (got {:?}, expected {:?})",
23175                s.placement(),
23176                placement,
23177            );
23178            assert!(
23179                std::ptr::eq(s.placement(), &s.placement),
23180                "AplicacaoSpec::placement accessor and &self.placement \
23181                 field access must borrow the same backing storage — the \
23182                 accessor is the substrate-primitive typed dispatch every \
23183                 downstream distribution-composite consumer must route \
23184                 through, and a reference-identity split would silently \
23185                 break every consumer that relied on the borrow sharing \
23186                 the composite's storage",
23187            );
23188            assert_eq!(
23189                s.placement().estrategia(),
23190                s.placement.estrategia,
23191                "AplicacaoSpec::placement().estrategia() must byte-equal \
23192                 self.placement.estrategia — a strategy-drift would \
23193                 silently split the paired `validate_placement` \
23194                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
23195                 peer caixa-mesh programs.yaml `placement.estrategia` \
23196                 emitter's key from the peer `feira app graph` printer's \
23197                 strategy label",
23198            );
23199            assert_eq!(
23200                s.placement().clusters(),
23201                s.placement.clusters.as_slice(),
23202                "AplicacaoSpec::placement().clusters() must byte-equal \
23203                 self.placement.clusters — a cluster-pool drift would \
23204                 silently split the paired `validate_placement` \
23205                 pre-flight `.is_empty()` refusal probe's traversal from \
23206                 the peer caixa-mesh programs.yaml `placement.clusters` \
23207                 emitter's fan-out from the peer `feira app graph` \
23208                 printer's cluster list",
23209            );
23210        }
23211    }
23212
23213    #[test]
23214    fn validate_placement_reads_through_lifted_placement_accessor() {
23215        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
23216        // per-axis bracket-dispatch seed (`let p = self.placement();`,
23217        // followed by the per-axis fan-out `p.clusters()` /
23218        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
23219        // lifted axis-level accessor family) must key off the lifted
23220        // outer accessor, so any future rebrand on the typed slot's
23221        // outer-composite reader shape lands at exactly one place. Pins
23222        // the multi-axis coherence by exercising each per-axis refusal
23223        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
23224        // `:clusters` pool under the outer accessor's reference
23225        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
23226        // strategy with a `None` `:shard-key` under the same projection,
23227        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
23228        // with a `Some` `:shard-key` under the same projection, and
23229        // (4) the canonical `three_member_spec` `Replicated` fixture
23230        // passes `validate_placement` under the outer accessor's
23231        // reference projection — the accessor's reference-projection
23232        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
23233        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
23234        // without silently short-circuiting any.
23235        //
23236        // Peer of the sibling M3
23237        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23238        // (534dc21) multi-axis coherence pin on the per-`:politicas`
23239        // outer mesh-policy composite-reference axis — extends the
23240        // multi-consumer coherence discipline onto the outermost M3
23241        // mesh-slot type's per-Aplicacao distribution composite-
23242        // reference axis, the second `&Composite`-return accessor on
23243        // the outer [`AplicacaoSpec`] type.
23244
23245        // (1) `PlacementWithoutClusters` refusal under the outer
23246        // accessor's reference projection: an empty `:clusters` pool
23247        // must trip the pre-flight refusal probe. The bracket-dispatch's
23248        // first arm reads `p.clusters()` on the reference returned by
23249        // the outer accessor.
23250        let mut spec = three_member_spec();
23251        spec.placement.clusters = Vec::new();
23252        assert_eq!(
23253            spec.validate().unwrap_err(),
23254            AplicacaoError::PlacementWithoutClusters {
23255                estrategia: PlacementStrategy::Replicated,
23256            },
23257        );
23258        assert!(
23259            std::ptr::eq(spec.placement(), &spec.placement),
23260            "the `validate_placement` per-axis bracket-dispatch's \
23261             traversal input must be the same backing composite the \
23262             accessor's reference projection borrows from",
23263        );
23264
23265        // (2) `ShardedWithoutKey` refusal under the outer accessor's
23266        // reference projection: a `Sharded` strategy with a `None`
23267        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
23268        // The bracket-dispatch's third arm reads `p.estrategia()` for
23269        // the match scrutinee then `p.shard_key()` for the cascade
23270        // scrutinee, both on the reference returned by the outer
23271        // accessor.
23272        let mut spec = three_member_spec();
23273        spec.placement.estrategia = PlacementStrategy::Sharded;
23274        spec.placement.shard_key = None;
23275        assert_eq!(
23276            spec.validate().unwrap_err(),
23277            AplicacaoError::ShardedWithoutKey,
23278        );
23279
23280        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
23281        // reference projection: a non-`Sharded` strategy with a `Some`
23282        // `:shard-key` must trip the declared-but-inert refusal. The
23283        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
23284        // + `p.estrategia()` for the diagnostic on the reference
23285        // returned by the outer accessor.
23286        let mut spec = three_member_spec();
23287        spec.placement.estrategia = PlacementStrategy::Replicated;
23288        spec.placement.shard_key = Some("tenantId".into());
23289        assert_eq!(
23290            spec.validate().unwrap_err(),
23291            AplicacaoError::ShardKeyOnNonSharded {
23292                estrategia: PlacementStrategy::Replicated,
23293                shard_key: "tenantId".into(),
23294            },
23295        );
23296
23297        // (4) Canonical `three_member_spec` `Replicated` fixture passes
23298        // `validate_placement` — every per-axis arm reaches the fall-
23299        // through `Ok(())` without any per-axis refusal firing under the
23300        // outer accessor's reference projection.
23301        let spec = three_member_spec();
23302        assert!(
23303            spec.validate().is_ok(),
23304            "the canonical Replicated placement fixture must pass \
23305             `validate_placement` — every per-axis arm short-circuits on \
23306             valid input under the outer accessor's reference projection",
23307        );
23308        assert_eq!(
23309            spec.placement().estrategia(),
23310            PlacementStrategy::Replicated,
23311            "the outer accessor's reference projection must be the \
23312             canonical Replicated fixture's strategy",
23313        );
23314        assert_eq!(
23315            spec.placement().clusters(),
23316            &["rio", "mar"],
23317            "the outer accessor's reference projection must be the \
23318             canonical Replicated fixture's cluster pool",
23319        );
23320    }
23321
23322    #[test]
23323    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
23324        // The canonical per-`:entrada` outer-composite-optional-
23325        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
23326        // the `:entrada` typed `Option<Entrada>` verbatim as an
23327        // `Option<&Entrada>` reference over the same backing storage
23328        // the raw `self.entrada.as_ref()` field access borrows from,
23329        // byte-equal across every representative fixture in the
23330        // accept-set — the author-omitted `None` shape (the
23331        // "internal-only mesh" partition every downstream external-
23332        // gateway emitter treats as "emit nothing"), the minimal
23333        // singleton `:entrada` composite (host + destination + empty
23334        // paths + default port), the paths-carrying composite (the
23335        // canonical `three_member_spec` fixture's ["/api" "/health"]
23336        // path-list shape every HTTPRoute per-rule fan-out emitter
23337        // reads), and the non-default port composite (the canonical
23338        // custom-port shape the port-fallback resolver reads).
23339        //
23340        // Pins against a future silent detour that returned a fresh-
23341        // cloned `Entrada` copy (which would type-check via a `Clone`
23342        // impl but silently break every downstream caller that
23343        // relied on the reference sharing the composite's backing
23344        // identity), a reference to an operator-resolved overlay
23345        // (the future per-cluster `:entrada-overrides` slot the
23346        // MESH-COMPOSITION §V federation roadmap acknowledges — its
23347        // resolution must land at exactly this accessor body, not
23348        // silently divert the raw slot away from a second consumer),
23349        // a `None` → `Some(Entrada::default)` cluster-default
23350        // projection (which would collapse the load-bearing
23351        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
23352        // the peer `gateway_routes` early-return + `feira app graph`
23353        // internal-only-mesh partition both read), or an axis-
23354        // shuffled projection (a future detour that swapped
23355        // `host` and `para` through the accessor would silently
23356        // split the paired `validate` per-`:entrada` shape-and-
23357        // membership gate's traversal input from the peer
23358        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
23359        // fan-out input from the peer `feira app graph` external-
23360        // gateway summary line).
23361        //
23362        // Peer of the sibling M3
23363        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23364        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
23365        // `:politicas` outer mesh-policy composite-reference axis
23366        // and of the sibling M3
23367        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
23368        // (9abb8f0) `&Placement` byte-equal pin on the per-
23369        // `:placement` outer distribution-composite composite-
23370        // reference axis — extends the outer-accessor byte-equal-
23371        // projection discipline onto the last unlifted outermost M3
23372        // mesh-slot type's per-Aplicacao external-gateway composite-
23373        // reference axis, the third and final `&Composite`-return
23374        // accessor on the outer [`AplicacaoSpec`] type.
23375        let fixtures: Vec<Option<Entrada>> = vec![
23376            None,
23377            Some(Entrada {
23378                host: "checkout.quero.cloud".into(),
23379                para: "cart".into(),
23380                paths: Vec::new(),
23381                port: DEFAULT_SERVICO_PORT,
23382            }),
23383            Some(Entrada {
23384                host: "checkout.quero.cloud".into(),
23385                para: "cart".into(),
23386                paths: vec!["/api".into(), "/health".into()],
23387                port: DEFAULT_SERVICO_PORT,
23388            }),
23389            Some(Entrada {
23390                host: "checkout.quero.cloud".into(),
23391                para: "cart".into(),
23392                paths: vec!["/api".into()],
23393                port: 9443,
23394            }),
23395        ];
23396        for entrada in fixtures {
23397            let s = AplicacaoSpec {
23398                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23399                contratos: Vec::new(),
23400                politicas: MeshPolicy::default(),
23401                placement: Placement::default(),
23402                entrada: entrada.clone(),
23403            };
23404            assert_eq!(
23405                s.entrada(),
23406                entrada.as_ref(),
23407                "AplicacaoSpec::entrada must return :entrada verbatim \
23408                 (got {:?}, expected {:?})",
23409                s.entrada(),
23410                entrada.as_ref(),
23411            );
23412            match (s.entrada(), s.entrada.as_ref()) {
23413                (Some(a), Some(b)) => assert!(
23414                    std::ptr::eq(a, b),
23415                    "AplicacaoSpec::entrada accessor and \
23416                     self.entrada.as_ref() field access must borrow \
23417                     the same backing storage — the accessor is the \
23418                     substrate-primitive typed dispatch every \
23419                     downstream external-gateway composite consumer \
23420                     must route through, and a reference-identity \
23421                     split would silently break every consumer that \
23422                     relied on the borrow sharing the composite's \
23423                     storage",
23424                ),
23425                (None, None) => {}
23426                _ => panic!(
23427                    "AplicacaoSpec::entrada presence bit must byte-\
23428                     equal self.entrada.is_some() — a presence-bit \
23429                     drift would silently split the paired `validate` \
23430                     per-`:entrada` shape-and-membership gate's \
23431                     traversal head from the peer \
23432                     caixa-mesh gateway_routes early-return partition \
23433                     from the peer `feira app graph` internal-only-\
23434                     mesh partition",
23435                ),
23436            }
23437            assert_eq!(
23438                s.entrada().is_some(),
23439                s.entrada.is_some(),
23440                "AplicacaoSpec::entrada().is_some() must byte-equal \
23441                 self.entrada.is_some() — a presence-bit drift would \
23442                 silently split every downstream `Option<&Entrada>` \
23443                 consumer's partition on the internal-only-mesh arm",
23444            );
23445        }
23446    }
23447
23448    #[test]
23449    fn validate_reads_through_lifted_entrada_accessor() {
23450        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
23451        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
23452        // self.entrada() { … }`, followed by the per-axis fan-out
23453        // `validate_entrada_para(&e.para)` /
23454        // `EntradaMemberMissing` membership lookup /
23455        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
23456        // per-`e.paths` `validate_entrada_path` traversal) must key
23457        // off the lifted outer accessor, so any future rebrand on
23458        // the typed slot's outer-composite reader shape lands at
23459        // exactly one place. Pins the multi-axis coherence by
23460        // exercising each per-axis refusal end-to-end: (1) the
23461        // author-omitted `None` shape short-circuits past every
23462        // per-`:entrada` refusal (the internal-only mesh partition
23463        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
23464        // fires on a well-shaped but phantom `:para` under the outer
23465        // accessor's reference projection, and (3) the canonical
23466        // `three_member_spec` `:entrada` fixture passes `validate`
23467        // under the outer accessor's reference projection.
23468        //
23469        // Peer of the sibling M3
23470        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23471        // (534dc21) multi-axis coherence pin on the per-`:politicas`
23472        // outer mesh-policy composite-reference axis and the sibling
23473        // M3
23474        // [`validate_placement_reads_through_lifted_placement_accessor`]
23475        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
23476        // outer distribution-composite composite-reference axis —
23477        // extends the multi-consumer coherence discipline onto the
23478        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
23479        // external-gateway composite-reference axis, the third and
23480        // final `&Composite`-return accessor on the outer
23481        // [`AplicacaoSpec`] type.
23482
23483        // (1) `None` :entrada — the internal-only-mesh partition
23484        // short-circuits past every per-`:entrada` refusal. The outer
23485        // accessor's reference projection reaches the fall-through
23486        // `Ok(())` on the `None` arm without any per-axis refusal
23487        // firing.
23488        let mut spec = three_member_spec();
23489        spec.entrada = None;
23490        assert!(
23491            spec.validate().is_ok(),
23492            "an author-omitted `:entrada` must pass `validate` — the \
23493             internal-only-mesh partition short-circuits past every \
23494             per-`:entrada` refusal under the outer accessor's \
23495             reference projection",
23496        );
23497        assert!(
23498            spec.entrada().is_none(),
23499            "the outer accessor's reference projection must name the \
23500             internal-only-mesh partition per the `None` fixture",
23501        );
23502
23503        // (2) `EntradaMemberMissing` refusal under the outer accessor's
23504        // reference projection: a well-shaped but phantom `:para` must
23505        // trip the membership-lookup refusal. The gate's second arm
23506        // reads `e.para` on the reference returned by the outer
23507        // accessor.
23508        let mut spec = three_member_spec();
23509        if let Some(e) = spec.entrada.as_mut() {
23510            e.para = "phantom".into();
23511        }
23512        assert_eq!(
23513            spec.validate().unwrap_err(),
23514            AplicacaoError::EntradaMemberMissing {
23515                para: "phantom".into(),
23516            },
23517        );
23518        match (spec.entrada(), spec.entrada.as_ref()) {
23519            (Some(a), Some(b)) => assert!(
23520                std::ptr::eq(a, b),
23521                "the `validate` per-`:entrada` gate's traversal head \
23522                 must be the same backing composite the accessor's \
23523                 reference projection borrows from",
23524            ),
23525            _ => panic!("fixture must carry Some(:entrada)"),
23526        }
23527
23528        // (3) Canonical `three_member_spec` `:entrada` fixture passes
23529        // `validate` — every per-axis arm reaches the fall-through
23530        // `Ok(())` without any per-axis refusal firing under the
23531        // outer accessor's reference projection.
23532        let spec = three_member_spec();
23533        assert!(
23534            spec.validate().is_ok(),
23535            "the canonical `:entrada` fixture must pass `validate` — \
23536             every per-axis arm short-circuits on valid input under \
23537             the outer accessor's reference projection",
23538        );
23539        assert!(
23540            spec.entrada().is_some(),
23541            "the outer accessor's reference projection must be the \
23542             canonical `:entrada` fixture's composite",
23543        );
23544    }
23545
23546    #[test]
23547    fn port_for_destination_reads_through_lifted_entrada_accessor() {
23548        // Peer coherence pin: the
23549        // [`AplicacaoSpec::port_for_destination`] per-destination
23550        // L4-port fallback resolver's composite-projection seed
23551        // (`self.entrada().filter(…).map_or(…)`) must key off the
23552        // lifted outer accessor. Pins the coherence by exercising
23553        // the resolver end-to-end: (1) the `None` `:entrada` shape
23554        // falls through to `DEFAULT_SERVICO_PORT` under the outer
23555        // accessor's reference projection, (2) a non-matching
23556        // destination falls through to `DEFAULT_SERVICO_PORT` under
23557        // the outer accessor's reference projection, and (3) the
23558        // matching destination resolves to the `:entrada :port`
23559        // value under the outer accessor's reference projection.
23560        //
23561        // Peer of the sibling
23562        // [`validate_reads_through_lifted_entrada_accessor`] multi-
23563        // consumer coherence pin on the same per-`:entrada` outer-
23564        // composite axis — extends the multi-consumer coherence
23565        // discipline onto the second per-`:entrada` production
23566        // consumer, the L4-port fallback resolver.
23567
23568        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
23569        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
23570        // arm under the outer accessor's reference projection.
23571        let mut spec = three_member_spec();
23572        spec.entrada = None;
23573        assert_eq!(
23574            spec.port_for_destination("cart"),
23575            DEFAULT_SERVICO_PORT,
23576            "the port-fallback resolver must fall through to \
23577             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
23578             under the outer accessor's reference projection",
23579        );
23580
23581        // (2) Non-matching destination — the resolver's `filter(…)`
23582        // arm rejects a mismatched destination and falls through
23583        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
23584        // reference projection.
23585        let mut spec = three_member_spec();
23586        if let Some(e) = spec.entrada.as_mut() {
23587            e.para = "cart".into();
23588            e.port = 9443;
23589        }
23590        assert_eq!(
23591            spec.port_for_destination("catalog"),
23592            DEFAULT_SERVICO_PORT,
23593            "the port-fallback resolver must fall through to \
23594             DEFAULT_SERVICO_PORT on a non-matching destination \
23595             under the outer accessor's reference projection",
23596        );
23597
23598        // (3) Matching destination — the resolver's `map_or(…)` arm
23599        // returns the `:entrada :port` value under the outer
23600        // accessor's reference projection.
23601        let mut spec = three_member_spec();
23602        if let Some(e) = spec.entrada.as_mut() {
23603            e.para = "cart".into();
23604            e.port = 9443;
23605        }
23606        assert_eq!(
23607            spec.port_for_destination("cart"),
23608            9443,
23609            "the port-fallback resolver must return the \
23610             `:entrada :port` value on a matching destination \
23611             under the outer accessor's reference projection",
23612        );
23613    }
23614
23615    #[test]
23616    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
23617        // The canonical per-`:politicas` `:mtls-required` mTLS-
23618        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
23619        // must return the `:politicas :mtls-required` typed bool
23620        // verbatim as an `Option<bool>`, byte-equal to the raw field
23621        // access across every value in the three-way accept-set —
23622        // `None` (cluster default applies), `Some(true)` (mTLS
23623        // handshake enforced — the sandboxing-by-default arm the
23624        // MeshPolicy's docstring names), `Some(false)` (handshake
23625        // skipped — the explicit debug-edge opt-out).
23626        //
23627        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
23628        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
23629        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
23630        // shape — first `Option<Copy-T>`-return accessor on the M3
23631        // mesh-slot family. Pins against a future silent detour that
23632        // re-derived the toggle from a peer axis (an accidental
23633        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
23634        // whenever a breaker is set), a `None` → `Some(false)` cluster-
23635        // default projection (the canonical `Option<bool>` → `bool`
23636        // collapse footgun the surrounding `is_empty()` predicate
23637        // guards on the peer emptiness axis), or a `Some(true)` /
23638        // `Some(false)` variant swap that landed on one consumer
23639        // without the other.
23640        for required in [None, Some(true), Some(false)] {
23641            let p = MeshPolicy {
23642                mtls_required: required,
23643                ..MeshPolicy::default()
23644            };
23645            assert_eq!(
23646                p.mtls_required(),
23647                required,
23648                "MeshPolicy::mtls_required must return :politicas \
23649                 :mtls-required verbatim (got {:?}, expected {required:?})",
23650                p.mtls_required(),
23651            );
23652            assert_eq!(
23653                p.mtls_required(),
23654                p.mtls_required,
23655                "MeshPolicy::mtls_required must byte-equal the raw \
23656                 .mtls_required field access across every value in the \
23657                 three-way accept-set",
23658            );
23659        }
23660    }
23661
23662    #[test]
23663    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
23664        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
23665        // arm must key off [`MeshPolicy::mtls_required`], not the raw
23666        // `.mtls_required` field access. Structurally: toggling ONLY
23667        // the `mtls_required` slot on an otherwise-default MeshPolicy
23668        // must flip `is_empty()` from `true` (all-`None`) to `false`
23669        // (one axis carries a value); the flip must be observed for
23670        // both `Some(true)` and `Some(false)` since the emptiness
23671        // semantic reads "any axis carries a value" — not "any axis
23672        // carries a truthy value" — the same non-collapsing shape the
23673        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23674        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
23675        // peer `Option<T>`-typed slot surfaces.
23676        //
23677        // Pins against a future silent detour that re-derived the
23678        // emptiness predicate off a peer axis (an accidental
23679        // `.rate_limit.is_none()`-only chain that dropped the
23680        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
23681        // collapse to a truthy-only check (which would silently
23682        // classify `Some(false)` as empty), or an accessor-side
23683        // detour that no longer names the substrate-primitive typed
23684        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
23685        // == false` fallback in the accessor that would silently
23686        // classify both `None` and `Some(false)` as the same value).
23687        //
23688        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
23689        // (7cd2a28) accessor-composition pin on the sibling optional-
23690        // scalar axis — same "the emptiness / shape-gate predicate
23691        // must route through the substrate-primitive typed dispatch"
23692        // discipline extended onto the peer per-`:politicas` emptiness
23693        // predicate.
23694        let empty = MeshPolicy::default();
23695        assert!(
23696            empty.is_empty(),
23697            "MeshPolicy::default() must be is_empty() — every axis \
23698             defaults to None",
23699        );
23700        for required in [Some(true), Some(false)] {
23701            let p = MeshPolicy {
23702                mtls_required: required,
23703                ..MeshPolicy::default()
23704            };
23705            assert!(
23706                !p.is_empty(),
23707                "MeshPolicy::is_empty must return false when \
23708                 :mtls-required is {required:?} — the emptiness \
23709                 predicate reads \"any axis carries a value\", not \
23710                 \"any axis carries a truthy value\"",
23711            );
23712            assert_eq!(
23713                p.mtls_required().is_none(),
23714                p.is_empty(),
23715                "when :mtls-required is the only set axis, \
23716                 is_empty() must equal mtls_required().is_none() — \
23717                 the accessor and the emptiness predicate must \
23718                 route through the same substrate-primitive typed \
23719                 dispatch on the :mtls-required arm",
23720            );
23721        }
23722    }
23723
23724    #[test]
23725    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
23726        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
23727        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
23728        // accessor must return by value, not by reference. Peer of the
23729        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
23730        // borrow-invariant pin on the sibling `Option<String>` slot,
23731        // but extended onto the peer `Option<bool>` copy-invariant
23732        // shape — the accessor's returned `Option<bool>` must outlive
23733        // `&self` (multiple calls must return equal values from a
23734        // dropped-`&self` copy, since the returned Option carries no
23735        // borrow), and calling the accessor twice on the same
23736        // MeshPolicy must yield the same `Option<bool>` verbatim
23737        // (idempotent, no side effects on `&self`).
23738        //
23739        // Pins against a future silent detour that returned
23740        // `Option<&bool>` (which would type-check but silently break
23741        // every downstream caller — [`single_field_overlay`]'s first
23742        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
23743        // detached copy at the call site), an accidental
23744        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
23745        // would also type-check but return `Option<&bool>`), or a
23746        // one-arm-only accessor that reads `Some(*b)` in the Some arm
23747        // but reads a fresh Default::default() in the None arm.
23748        for required in [None, Some(true), Some(false)] {
23749            let p = MeshPolicy {
23750                mtls_required: required,
23751                ..MeshPolicy::default()
23752            };
23753            let first = p.mtls_required();
23754            let second = p.mtls_required();
23755            assert_eq!(
23756                first, second,
23757                "MeshPolicy::mtls_required must be idempotent — two \
23758                 successive calls on the same &self must return the \
23759                 same Option<bool>",
23760            );
23761            assert_eq!(
23762                first, required,
23763                "MeshPolicy::mtls_required must return :politicas \
23764                 :mtls-required verbatim by copy — got {first:?}, \
23765                 expected {required:?}",
23766            );
23767        }
23768    }
23769
23770    #[test]
23771    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
23772        // The canonical per-`:politicas` `:retries` transient-failure-
23773        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
23774        // the `:politicas :retries` typed `u32` verbatim as an
23775        // `Option<u32>`, byte-equal to the raw field access across every
23776        // representative value in the accept-set — `None` (cluster
23777        // default applies — typically "no retries beyond a single
23778        // dispatch attempt" the caixa-mesh `retry_overlay` builder
23779        // documents), `Some(1)` (the lower boundary of the
23780        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
23781        // `AplicacaoSpec::validate_politicas` gate carves out on the
23782        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
23783        // (the upper boundary the same gate carves out on the sibling
23784        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
23785        // past-the-guard sentinel that pins the accessor doesn't perform
23786        // a silent bounds-collapse at the return path).
23787        //
23788        // Sibling of the peer per-`:politicas`
23789        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
23790        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
23791        // peer per-`:politicas` `Option<u32>` shape — second
23792        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
23793        // Pins against a future silent detour that re-derived the retry
23794        // cap from a peer axis (an accidental `.circuit_breaker
23795        // .as_ref().map(|b| b.max_failures)` collapse that read the
23796        // breaker's max-failure count as a retry budget), a
23797        // `None → Some(0)` cluster-default projection (which would
23798        // silently re-introduce the `PolicyRetriesZero` refusal case at
23799        // the emit boundary), or a bounds-collapsing accessor that
23800        // clamped the return through `POLICY_RETRIES_MAX` (the
23801        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
23802        // must ship the raw slot verbatim so a validate-time gate
23803        // regression surfaces at the emit boundary rather than being
23804        // silently absorbed).
23805        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
23806            let p = MeshPolicy {
23807                retries,
23808                ..MeshPolicy::default()
23809            };
23810            assert_eq!(
23811                p.retries(),
23812                retries,
23813                "MeshPolicy::retries must return :politicas :retries \
23814                 verbatim (got {:?}, expected {retries:?})",
23815                p.retries(),
23816            );
23817            assert_eq!(
23818                p.retries(),
23819                p.retries,
23820                "MeshPolicy::retries must byte-equal the raw .retries \
23821                 field access across every value in the accept-set",
23822            );
23823        }
23824    }
23825
23826    #[test]
23827    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
23828        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
23829        // must key off [`MeshPolicy::retries`], not the raw `.retries`
23830        // field access. Structurally: toggling ONLY the `retries` slot
23831        // on an otherwise-default MeshPolicy must flip `is_empty()`
23832        // from `true` (all-`None`) to `false` (one axis carries a
23833        // value); the flip must be observed for every value in the
23834        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
23835        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
23836        // the emptiness semantic reads "any axis carries a value" —
23837        // not "any axis carries a value the validate gate accepts" —
23838        // the same non-collapsing shape the peer M2
23839        // [`crate::LimitsSpec::is_empty`] /
23840        // [`crate::BehaviorSpec::is_empty`] predicates carry.
23841        //
23842        // Pins against a future silent detour that re-derived the
23843        // emptiness predicate off a peer axis (an accidental
23844        // `.rate_limit.is_none()`-only chain that dropped the
23845        // `retries` arm entirely), a `retries == Some(_)` collapse
23846        // that key-off a validate-gate-clamped bounds check (which
23847        // would silently classify a past-the-guard `Some(u32::MAX)`
23848        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
23849        // check), or an accessor-side detour that no longer names the
23850        // substrate-primitive typed dispatch.
23851        //
23852        // Sibling of the peer per-`:politicas`
23853        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
23854        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
23855        // same "the emptiness predicate must route through the
23856        // substrate-primitive typed dispatch" discipline extended onto
23857        // the peer per-`:politicas` `Option<u32>` axis.
23858        let empty = MeshPolicy::default();
23859        assert!(
23860            empty.is_empty(),
23861            "MeshPolicy::default() must be is_empty() — every axis \
23862             defaults to None",
23863        );
23864        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
23865            let p = MeshPolicy {
23866                retries,
23867                ..MeshPolicy::default()
23868            };
23869            assert!(
23870                !p.is_empty(),
23871                "MeshPolicy::is_empty must return false when \
23872                 :retries is {retries:?} — the emptiness \
23873                 predicate reads \"any axis carries a value\", not \
23874                 \"any axis carries a value the validate gate \
23875                 accepts\"",
23876            );
23877            assert_eq!(
23878                p.retries().is_none(),
23879                p.is_empty(),
23880                "when :retries is the only set axis, is_empty() \
23881                 must equal retries().is_none() — the accessor and \
23882                 the emptiness predicate must route through the same \
23883                 substrate-primitive typed dispatch on the :retries \
23884                 arm",
23885            );
23886        }
23887    }
23888
23889    #[test]
23890    fn mesh_policy_retries_projects_option_u32_by_copy() {
23891        // The by-copy pin: [`MeshPolicy::retries`] returns
23892        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
23893        // accessor must return by value, not by reference. Sibling of
23894        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
23895        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
23896        // extended onto the sibling `Option<u32>` copy-invariant
23897        // shape — the accessor's returned `Option<u32>` must outlive
23898        // `&self` (multiple calls must return equal values from a
23899        // dropped-`&self` copy, since the returned Option carries no
23900        // borrow), and calling the accessor twice on the same
23901        // MeshPolicy must yield the same `Option<u32>` verbatim
23902        // (idempotent, no side effects on `&self`).
23903        //
23904        // Pins against a future silent detour that returned
23905        // `Option<&u32>` (which would type-check but silently break
23906        // every downstream caller — [`crate::render::single_field_overlay`]'s
23907        // first parameter is `Option<T: Clone>`, and `&u32` would
23908        // fold to a detached copy at the call site), an accidental
23909        // `Option::as_ref()` projection (`self.retries.as_ref()` would
23910        // also type-check but return `Option<&u32>`), or a one-arm-
23911        // only accessor that reads `Some(*n)` in the Some arm but
23912        // reads a fresh `Default::default()` (`0_u32`) in the None
23913        // arm.
23914        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
23915            let p = MeshPolicy {
23916                retries,
23917                ..MeshPolicy::default()
23918            };
23919            let first = p.retries();
23920            let second = p.retries();
23921            assert_eq!(
23922                first, second,
23923                "MeshPolicy::retries must be idempotent — two \
23924                 successive calls on the same &self must return the \
23925                 same Option<u32>",
23926            );
23927            assert_eq!(
23928                first, retries,
23929                "MeshPolicy::retries must return :politicas :retries \
23930                 verbatim by copy — got {first:?}, expected {retries:?}",
23931            );
23932        }
23933    }
23934
23935    #[test]
23936    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
23937        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
23938        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
23939        // return the `:politicas :timeout` typed [`Duration`] verbatim
23940        // as an `Option<Duration>`, byte-equal to the raw field access
23941        // across every representative value in the accept-set — `None`
23942        // (cluster default applies — typically the gateway class's
23943        // implementation-side per-request wall-clock cap the caixa-mesh
23944        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
23945        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
23946        // set the surrounding `AplicacaoSpec::validate_politicas` gate
23947        // carves out on the sibling `PolicyTimeoutZero` /
23948        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
23949        // (the upper boundary the same gate carves out on the sibling
23950        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
23951        // (a past-the-guard sentinel that pins the accessor doesn't
23952        // perform a silent bounds-collapse into `None` on the zero-
23953        // Duration arm — validate rejects zero but the accessor must
23954        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
23955        // past-the-guard sentinel that pins the accessor doesn't
23956        // perform a silent bounds-collapse at the return path).
23957        //
23958        // Sibling of the peer per-`:politicas`
23959        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
23960        // `Option<u32>` optional-scalar axis and the peer per-
23961        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
23962        // pin on the sibling `Option<bool>` optional-scalar axis,
23963        // extended onto the peer per-`:politicas` `Option<Duration>`
23964        // shape — third `Option<Copy-T>`-return accessor on the M3
23965        // mesh-slot family. Pins against a future silent detour that
23966        // re-derived the per-call cap from a peer axis (an accidental
23967        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
23968        // read the breaker's rolling-window duration as a per-call
23969        // deadline), a `None → Some(Duration::MAX)` cluster-default
23970        // projection (which would silently re-introduce the
23971        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
23972        // blocking" arm at the emit boundary), or a bounds-collapsing
23973        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
23974        // (the `AplicacaoSpec::validate` gate owns the bounds; the
23975        // accessor must ship the raw slot verbatim so a validate-time
23976        // gate regression surfaces at the emit boundary rather than
23977        // being silently absorbed).
23978        for timeout in [
23979            None,
23980            Some(Duration::from_millis(1)),
23981            Some(POLICY_TIMEOUT_MAX),
23982            Some(Duration::ZERO),
23983            Some(Duration::MAX),
23984        ] {
23985            let p = MeshPolicy {
23986                timeout,
23987                ..MeshPolicy::default()
23988            };
23989            assert_eq!(
23990                p.timeout(),
23991                timeout,
23992                "MeshPolicy::timeout must return :politicas :timeout \
23993                 verbatim (got {:?}, expected {timeout:?})",
23994                p.timeout(),
23995            );
23996            assert_eq!(
23997                p.timeout(),
23998                p.timeout,
23999                "MeshPolicy::timeout must byte-equal the raw .timeout \
24000                 field access across every value in the accept-set",
24001            );
24002        }
24003    }
24004
24005    #[test]
24006    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
24007        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
24008        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
24009        // field access. Structurally: toggling ONLY the `timeout` slot
24010        // on an otherwise-default MeshPolicy must flip `is_empty()`
24011        // from `true` (all-`None`) to `false` (one axis carries a
24012        // value); the flip must be observed for every value in the
24013        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24014        // gate accepts (`Some(Duration::from_millis(1))`,
24015        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
24016        // reads "any axis carries a value" — not "any axis carries a
24017        // value the validate gate accepts" — the same non-collapsing
24018        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
24019        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24020        //
24021        // Pins against a future silent detour that re-derived the
24022        // emptiness predicate off a peer axis (an accidental
24023        // `.rate_limit.is_none()`-only chain that dropped the
24024        // `timeout` arm entirely), a `timeout == Some(_)` collapse
24025        // that key-off a validate-gate-clamped bounds check (which
24026        // would silently classify a past-the-guard `Some(Duration::MAX)`
24027        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
24028        // check), or an accessor-side detour that no longer names the
24029        // substrate-primitive typed dispatch.
24030        //
24031        // Sibling of the peer per-`:politicas`
24032        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
24033        // the sibling `Option<u32>` optional-scalar axis and the peer
24034        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24035        // accessor-composition pin on the sibling `Option<bool>`
24036        // optional-scalar axis — same "the emptiness predicate must
24037        // route through the substrate-primitive typed dispatch"
24038        // discipline extended onto the peer per-`:politicas`
24039        // `Option<Duration>` axis.
24040        let empty = MeshPolicy::default();
24041        assert!(
24042            empty.is_empty(),
24043            "MeshPolicy::default() must be is_empty() — every axis \
24044             defaults to None",
24045        );
24046        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
24047            let p = MeshPolicy {
24048                timeout,
24049                ..MeshPolicy::default()
24050            };
24051            assert!(
24052                !p.is_empty(),
24053                "MeshPolicy::is_empty must return false when \
24054                 :timeout is {timeout:?} — the emptiness \
24055                 predicate reads \"any axis carries a value\", not \
24056                 \"any axis carries a value the validate gate \
24057                 accepts\"",
24058            );
24059            assert_eq!(
24060                p.timeout().is_none(),
24061                p.is_empty(),
24062                "when :timeout is the only set axis, is_empty() \
24063                 must equal timeout().is_none() — the accessor and \
24064                 the emptiness predicate must route through the same \
24065                 substrate-primitive typed dispatch on the :timeout \
24066                 arm",
24067            );
24068        }
24069    }
24070
24071    #[test]
24072    fn mesh_policy_timeout_projects_option_duration_by_copy() {
24073        // The by-copy pin: [`MeshPolicy::timeout`] returns
24074        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
24075        // and the accessor must return by value, not by reference.
24076        // Sibling of the peer per-`:politicas`
24077        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
24078        // sibling `Option<u32>` optional-scalar axis and the peer
24079        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24080        // by-copy pin on the sibling `Option<bool>` optional-scalar
24081        // axis, extended onto the peer per-`:politicas`
24082        // `Option<Duration>` copy-invariant shape — the accessor's
24083        // returned `Option<Duration>` must outlive `&self` (multiple
24084        // calls must return equal values from a dropped-`&self`
24085        // copy, since the returned Option carries no borrow), and
24086        // calling the accessor twice on the same MeshPolicy must
24087        // yield the same `Option<Duration>` verbatim (idempotent, no
24088        // side effects on `&self`).
24089        //
24090        // Pins against a future silent detour that returned
24091        // `Option<&Duration>` (which would type-check but silently
24092        // break every downstream caller — [`crate::render::single_field_overlay`]'s
24093        // first parameter is `Option<T: Clone>`, and `&Duration`
24094        // would fold to a detached copy at the call site), an
24095        // accidental `Option::as_ref()` projection
24096        // (`self.timeout.as_ref()` would also type-check but return
24097        // `Option<&Duration>`), or a one-arm-only accessor that
24098        // reads `Some(*d)` in the Some arm but reads a fresh
24099        // `Default::default()` (`Duration::ZERO`) in the None arm
24100        // (which would silently re-classify every unset `:timeout`
24101        // as the `PolicyTimeoutZero`-refused zero-Duration value at
24102        // the accessor boundary).
24103        for timeout in [
24104            None,
24105            Some(Duration::from_millis(1)),
24106            Some(POLICY_TIMEOUT_MAX),
24107            Some(Duration::ZERO),
24108            Some(Duration::MAX),
24109        ] {
24110            let p = MeshPolicy {
24111                timeout,
24112                ..MeshPolicy::default()
24113            };
24114            let first = p.timeout();
24115            let second = p.timeout();
24116            assert_eq!(
24117                first, second,
24118                "MeshPolicy::timeout must be idempotent — two \
24119                 successive calls on the same &self must return the \
24120                 same Option<Duration>",
24121            );
24122            assert_eq!(
24123                first, timeout,
24124                "MeshPolicy::timeout must return :politicas :timeout \
24125                 verbatim by copy — got {first:?}, expected {timeout:?}",
24126            );
24127        }
24128    }
24129
24130    #[test]
24131    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
24132        // The canonical per-`:politicas` `:rate-limit` Envoy-
24133        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
24134        // [`MeshPolicy::rate_limit`] must return the `:politicas
24135        // :rate-limit` typed [`RateLimit`] verbatim as an
24136        // `Option<RateLimit>`, byte-equal to the raw field access
24137        // across every representative value in the accept-set — `None`
24138        // (cluster default applies — no per-Aplicacao rate declaration,
24139        // the gateway-class per-listener default arm the future caixa-
24140        // mesh `local_rate_limit_overlay` emitter documents),
24141        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
24142        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
24143        // accept-set the surrounding
24144        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24145        // sibling `PolicyRateLimitZero` refusal, paired with the
24146        // canonical-window "1 second" arm of the three-unit
24147        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
24148        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
24149        // (the upper boundary the same gate carves out on the sibling
24150        // `PolicyRateLimitExceedsCap` refusal, paired with the
24151        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
24152        // (a past-the-guard sentinel that pins the accessor doesn't
24153        // perform a silent bounds-collapse into `None` on the
24154        // zero-rate/zero-window arm — validate rejects zero but the
24155        // accessor must ship the raw slot verbatim so a validate-time
24156        // gate regression surfaces at the emit boundary rather than
24157        // being silently absorbed), and
24158        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
24159        // (a past-the-guard sentinel that pins the accessor doesn't
24160        // perform a silent bounds-collapse at the return path).
24161        //
24162        // First `Option<Copy-composite-T>`-return accessor pin on the
24163        // M3 mesh-slot family (peer of the sibling per-`:politicas`
24164        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
24165        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
24166        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
24167        // Copy accessor pins, extended onto the peer per-`:politicas`
24168        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
24169        // and the accessor returns by value). Pins against a future
24170        // silent detour that re-derived the rate declaration from a
24171        // peer axis (an accidental
24172        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
24173        // collapse that read the breaker's trip threshold + rolling
24174        // window as a rate declaration), a `None → Some(default())`
24175        // cluster-default projection (which would silently re-
24176        // introduce a "cluster default is 0/s" arm the emit boundary
24177        // would take as "declared but inert" — the canonical
24178        // declared-but-inert footgun the sibling
24179        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
24180        // amplification-shape axis), a bounds-collapsing accessor
24181        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
24182        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
24183        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
24184        // accessor must ship the raw slot verbatim), or a
24185        // by-reference detour (`Option<&RateLimit>`) that broke every
24186        // downstream consumer keying off `Option<RateLimit>` by-copy.
24187        for rl in [
24188            None,
24189            Some(RateLimit {
24190                rate: 1,
24191                window: Duration::from_secs(1),
24192            }),
24193            Some(RateLimit {
24194                rate: POLICY_RATE_LIMIT_MAX,
24195                window: Duration::from_secs(3600),
24196            }),
24197            Some(RateLimit {
24198                rate: 0,
24199                window: Duration::ZERO,
24200            }),
24201            Some(RateLimit {
24202                rate: u32::MAX,
24203                window: Duration::MAX,
24204            }),
24205        ] {
24206            let p = MeshPolicy {
24207                rate_limit: rl,
24208                ..MeshPolicy::default()
24209            };
24210            assert_eq!(
24211                p.rate_limit(),
24212                rl,
24213                "MeshPolicy::rate_limit must return :politicas :rate-limit \
24214                 verbatim (got {:?}, expected {rl:?})",
24215                p.rate_limit(),
24216            );
24217            assert_eq!(
24218                p.rate_limit(),
24219                p.rate_limit,
24220                "MeshPolicy::rate_limit must byte-equal the raw \
24221                 .rate_limit field access across every value in the \
24222                 accept-set",
24223            );
24224        }
24225    }
24226
24227    #[test]
24228    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
24229        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
24230        // must key off [`MeshPolicy::rate_limit`], not the raw
24231        // `.rate_limit` field access. Structurally: toggling ONLY the
24232        // `rate_limit` slot on an otherwise-default MeshPolicy must
24233        // flip `is_empty()` from `true` (all-`None`) to `false` (one
24234        // axis carries a value); the flip must be observed for every
24235        // representative value in the accept-set the surrounding
24236        // [`AplicacaoSpec::validate_politicas`] gate accepts
24237        // (`Some(RateLimit { rate: 1, window: 1s })`,
24238        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
24239        // since the emptiness semantic reads "any axis carries a
24240        // value" — not "any axis carries a value the validate gate
24241        // accepts" — the same non-collapsing shape the peer M2
24242        // [`crate::LimitsSpec::is_empty`] /
24243        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24244        //
24245        // Pins against a future silent detour that re-derived the
24246        // emptiness predicate off a peer axis (an accidental
24247        // `.timeout.is_none()`-only chain that dropped the
24248        // `rate_limit` arm entirely — the last unlifted inline field
24249        // access on `is_empty` before this lift), a `rate_limit ==
24250        // Some(_)` collapse that key-off a validate-gate-clamped
24251        // bounds check (which would silently classify a past-the-
24252        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
24253        // because it fails the value-shape gate), or an accessor-
24254        // side detour that no longer names the substrate-primitive
24255        // typed dispatch.
24256        //
24257        // Fourth "the emptiness predicate must route through the
24258        // substrate-primitive typed dispatch" composition pin on the
24259        // M3 mesh-slot family — closes the last unlifted composition
24260        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24261        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24262        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24263        // 7073d0f is_empty-composition pins on the sibling primitive-
24264        // Copy axes, extended onto the peer per-`:politicas`
24265        // composite-Copy `Option<RateLimit>` axis).
24266        let empty = MeshPolicy::default();
24267        assert!(
24268            empty.is_empty(),
24269            "MeshPolicy::default() must be is_empty() — every axis \
24270             defaults to None",
24271        );
24272        for rl in [
24273            RateLimit {
24274                rate: 1,
24275                window: Duration::from_secs(1),
24276            },
24277            RateLimit {
24278                rate: POLICY_RATE_LIMIT_MAX,
24279                window: Duration::from_secs(3600),
24280            },
24281        ] {
24282            let p = MeshPolicy {
24283                rate_limit: Some(rl),
24284                ..MeshPolicy::default()
24285            };
24286            assert!(
24287                !p.is_empty(),
24288                "MeshPolicy::is_empty must return false when \
24289                 :rate-limit is {rl:?} — the emptiness predicate \
24290                 reads \"any axis carries a value\", not \"any axis \
24291                 carries a value the validate gate accepts\"",
24292            );
24293            assert_eq!(
24294                p.rate_limit().is_none(),
24295                p.is_empty(),
24296                "when :rate-limit is the only set axis, is_empty() \
24297                 must equal rate_limit().is_none() — the accessor \
24298                 and the emptiness predicate must route through the \
24299                 same substrate-primitive typed dispatch on the \
24300                 :rate-limit arm",
24301            );
24302        }
24303    }
24304
24305    #[test]
24306    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
24307        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24308        // `:rate-limit` value-shape gate must key off
24309        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
24310        // field bind. Structurally: a `MeshPolicy` whose only set
24311        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
24312        // the `PolicyRateLimitZero` refusal exactly, and the same
24313        // MeshPolicy with the rate at the canonical lower boundary
24314        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
24315        // The pair jointly pins the accessor + validate-gate
24316        // composition: any future silent detour that had the accessor
24317        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
24318        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
24319        // silently absorb the `PolicyRateLimitZero` refusal at the
24320        // accessor boundary — the composition pin catches that at
24321        // caixa-core build time.
24322        //
24323        // Sibling of the peer [`validate_politicas`]
24324        // `:mtls-required` / `:retries` / `:timeout` composition pins
24325        // on the sibling primitive-Copy optional-scalar axes — same
24326        // "the validate / shape-gate predicate must route through the
24327        // substrate-primitive typed dispatch" discipline extended
24328        // onto the peer per-`:politicas` composite-Copy
24329        // `Option<RateLimit>` axis. Second composition-with-accessor
24330        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
24331        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
24332        let mut spec = three_member_spec();
24333        spec.politicas = MeshPolicy {
24334            rate_limit: Some(RateLimit {
24335                rate: 0,
24336                window: Duration::from_secs(1),
24337            }),
24338            ..MeshPolicy::default()
24339        };
24340        assert!(
24341            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24342            "validate_politicas must reject rate == 0 with \
24343             PolicyRateLimitZero — the accessor and the validate gate \
24344             must route through the same substrate-primitive typed \
24345             dispatch on the :rate-limit zero-floor arm",
24346        );
24347        spec.politicas = MeshPolicy {
24348            rate_limit: Some(RateLimit {
24349                rate: 1,
24350                window: Duration::from_secs(1),
24351            }),
24352            ..MeshPolicy::default()
24353        };
24354        assert!(
24355            spec.validate().is_ok(),
24356            "validate_politicas must accept rate == 1 (the canonical \
24357             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
24358             set) with a canonical 1s window",
24359        );
24360    }
24361
24362    #[test]
24363    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
24364        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
24365        // `outlier_detection`-mesh consecutive-failure-ejection scalar
24366        // pin: [`MeshPolicy::circuit_breaker`] must return the
24367        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
24368        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
24369        // raw field access across every representative value in the
24370        // accept-set — `None` (cluster default applies — no
24371        // per-Aplicacao breaker declaration, the gateway-class per-
24372        // listener default arm the future caixa-mesh
24373        // `outlier_detection_overlay` emitter documents),
24374        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
24375        // (the lower boundary of the accept-set the surrounding
24376        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24377        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
24378        // refusals),
24379        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
24380        // (the upper boundary the same gate carves out on the sibling
24381        // `PolicyBreakerMaxFailuresExceedsCap` /
24382        // `PolicyBreakerWindowExceedsCap` refusals),
24383        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
24384        // (a past-the-guard sentinel that pins the accessor doesn't
24385        // perform a silent bounds-collapse into `None` on the
24386        // zero-failures/zero-window arm — validate rejects zero but
24387        // the accessor must ship the raw slot verbatim so a validate-
24388        // time gate regression surfaces at the emit boundary rather
24389        // than being silently absorbed), and
24390        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
24391        // (a past-the-guard sentinel that pins the accessor doesn't
24392        // perform a silent bounds-collapse at the return path).
24393        //
24394        // Second `Option<Copy-composite-T>`-return accessor pin on the
24395        // M3 mesh-slot family (peer of the sibling per-`:politicas`
24396        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
24397        // composite-Copy accessor pin, and of the sibling per-
24398        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
24399        // [`MeshPolicy::retries`] bdfb399 /
24400        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
24401        // accessor pins). Pins against a future silent detour that
24402        // re-derived the breaker declaration from a peer axis (an
24403        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
24404        // collapse that read the rate-limit's bucket capacity + refill
24405        // period as a breaker declaration), a `None → Some(default())`
24406        // cluster-default projection (which would silently re-
24407        // introduce the `PolicyBreakerZeroFailures` /
24408        // `PolicyBreakerZeroWindow` refusal cases at the emit
24409        // boundary), a bounds-collapsing accessor that clamped
24410        // `cb.max_failures` through
24411        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
24412        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
24413        // [`AplicacaoSpec::validate`] gate owns the bounds; the
24414        // accessor must ship the raw slot verbatim), or a
24415        // by-reference detour (`Option<&CircuitBreaker>`) that broke
24416        // every downstream consumer keying off `Option<CircuitBreaker>`
24417        // by-copy.
24418        for cb in [
24419            None,
24420            Some(CircuitBreaker {
24421                max_failures: 1,
24422                window: Duration::from_millis(1),
24423            }),
24424            Some(CircuitBreaker {
24425                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24426                window: POLICY_BREAKER_WINDOW_MAX,
24427            }),
24428            Some(CircuitBreaker {
24429                max_failures: 0,
24430                window: Duration::ZERO,
24431            }),
24432            Some(CircuitBreaker {
24433                max_failures: u32::MAX,
24434                window: Duration::MAX,
24435            }),
24436        ] {
24437            let p = MeshPolicy {
24438                circuit_breaker: cb,
24439                ..MeshPolicy::default()
24440            };
24441            assert_eq!(
24442                p.circuit_breaker(),
24443                cb,
24444                "MeshPolicy::circuit_breaker must return :politicas \
24445                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
24446                p.circuit_breaker(),
24447            );
24448            assert_eq!(
24449                p.circuit_breaker(),
24450                p.circuit_breaker,
24451                "MeshPolicy::circuit_breaker must byte-equal the raw \
24452                 .circuit_breaker field access across every value in \
24453                 the accept-set",
24454            );
24455        }
24456    }
24457
24458    #[test]
24459    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
24460        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
24461        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
24462        // `.circuit_breaker` field access. Structurally: toggling ONLY
24463        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
24464        // must flip `is_empty()` from `true` (all-`None`) to `false`
24465        // (one axis carries a value); the flip must be observed for
24466        // every representative value in the accept-set the surrounding
24467        // [`AplicacaoSpec::validate_politicas`] gate accepts
24468        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
24469        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
24470        // since the emptiness semantic reads "any axis carries a
24471        // value" — not "any axis carries a value the validate gate
24472        // accepts" — the same non-collapsing shape the peer M2
24473        // [`crate::LimitsSpec::is_empty`] /
24474        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24475        //
24476        // Pins against a future silent detour that re-derived the
24477        // emptiness predicate off a peer axis (an accidental
24478        // `.rate_limit.is_none()`-only chain that dropped the
24479        // `circuit_breaker` arm entirely — the last unlifted inline
24480        // field access on `is_empty` before this lift), a
24481        // `circuit_breaker == Some(_)` collapse that key-off a
24482        // validate-gate-clamped bounds check (which would silently
24483        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
24484        // 0, window: 0s })` as empty because it fails the value-shape
24485        // gate), or an accessor-side detour that no longer names the
24486        // substrate-primitive typed dispatch.
24487        //
24488        // Fifth "the emptiness predicate must route through the
24489        // substrate-primitive typed dispatch" composition pin on the
24490        // M3 mesh-slot family — closes the last unlifted composition
24491        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24492        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24493        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24494        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
24495        // composition pins on the sibling primitive-Copy + composite-
24496        // Copy axes, extended onto the peer per-`:politicas`
24497        // composite-Copy `Option<CircuitBreaker>` axis).
24498        let empty = MeshPolicy::default();
24499        assert!(
24500            empty.is_empty(),
24501            "MeshPolicy::default() must be is_empty() — every axis \
24502             defaults to None",
24503        );
24504        for cb in [
24505            CircuitBreaker {
24506                max_failures: 1,
24507                window: Duration::from_millis(1),
24508            },
24509            CircuitBreaker {
24510                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24511                window: POLICY_BREAKER_WINDOW_MAX,
24512            },
24513        ] {
24514            let p = MeshPolicy {
24515                circuit_breaker: Some(cb),
24516                ..MeshPolicy::default()
24517            };
24518            assert!(
24519                !p.is_empty(),
24520                "MeshPolicy::is_empty must return false when \
24521                 :circuit-breaker is {cb:?} — the emptiness predicate \
24522                 reads \"any axis carries a value\", not \"any axis \
24523                 carries a value the validate gate accepts\"",
24524            );
24525            assert_eq!(
24526                p.circuit_breaker().is_none(),
24527                p.is_empty(),
24528                "when :circuit-breaker is the only set axis, \
24529                 is_empty() must equal circuit_breaker().is_none() — \
24530                 the accessor and the emptiness predicate must route \
24531                 through the same substrate-primitive typed dispatch \
24532                 on the :circuit-breaker arm",
24533            );
24534        }
24535    }
24536
24537    #[test]
24538    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
24539        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24540        // `:circuit-breaker` value-shape gate must key off
24541        // [`MeshPolicy::circuit_breaker`], not the raw
24542        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
24543        // whose only set axis is a `Some(CircuitBreaker { max_failures:
24544        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
24545        // refusal exactly, and the same MeshPolicy with the breaker at
24546        // the canonical lower boundary
24547        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
24548        // pass validate. The pair jointly pins the accessor +
24549        // validate-gate composition: any future silent detour that had
24550        // the accessor omit the `Some(CircuitBreaker { max_failures:
24551        // 0, .. })` arm (a
24552        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
24553        // collapse) would silently absorb the
24554        // `PolicyBreakerZeroFailures` refusal at the accessor
24555        // boundary — the composition pin catches that at caixa-core
24556        // build time.
24557        //
24558        // Sibling of the peer [`validate_politicas`]
24559        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
24560        // composition pins on the sibling primitive-Copy + composite-
24561        // Copy optional-scalar axes — same "the validate / shape-gate
24562        // predicate must route through the substrate-primitive typed
24563        // dispatch" discipline extended onto the peer per-`:politicas`
24564        // composite-Copy `Option<CircuitBreaker>` axis. Second
24565        // composition-with-accessor pin on the M3 mesh-slot
24566        // `Option<CircuitBreaker>` arm alongside the
24567        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
24568        let mut spec = three_member_spec();
24569        spec.politicas = MeshPolicy {
24570            circuit_breaker: Some(CircuitBreaker {
24571                max_failures: 0,
24572                window: Duration::from_millis(1),
24573            }),
24574            ..MeshPolicy::default()
24575        };
24576        assert!(
24577            matches!(
24578                spec.validate(),
24579                Err(AplicacaoError::PolicyBreakerZeroFailures)
24580            ),
24581            "validate_politicas must reject max_failures == 0 with \
24582             PolicyBreakerZeroFailures — the accessor and the validate \
24583             gate must route through the same substrate-primitive \
24584             typed dispatch on the :circuit-breaker zero-floor arm",
24585        );
24586        spec.politicas = MeshPolicy {
24587            circuit_breaker: Some(CircuitBreaker {
24588                max_failures: 1,
24589                window: Duration::from_millis(1),
24590            }),
24591            ..MeshPolicy::default()
24592        };
24593        assert!(
24594            spec.validate().is_ok(),
24595            "validate_politicas must accept a CircuitBreaker at the \
24596             canonical lower boundary (max_failures = 1, window = \
24597             1ms) — the accessor and the validate gate must route \
24598             through the same substrate-primitive typed dispatch on \
24599             the :circuit-breaker arm",
24600        );
24601    }
24602
24603    #[test]
24604    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
24605        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
24606        // Envoy-outlier-detection trip-threshold scalar pin:
24607        // [`CircuitBreaker::max_failures`] must return the
24608        // `:politicas :circuit-breaker :max-failures` typed `u32`
24609        // verbatim, byte-equal to the raw field access across every
24610        // representative value in the accept-set — `1` (the lower
24611        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
24612        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
24613        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
24614        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
24615        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
24616        // refusal), `0` (a past-the-guard sentinel that pins the accessor
24617        // doesn't perform a silent bounds-collapse into `1` on the zero
24618        // arm — validate rejects zero but the accessor must ship the
24619        // raw slot verbatim so a validate-time gate regression surfaces
24620        // at the emit boundary rather than being silently absorbed),
24621        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
24622        // doesn't perform a silent bounds-collapse through
24623        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
24624        //
24625        // First sub-struct required-scalar accessor pin on the M3
24626        // mesh-slot family — sibling in shape to the peer per-`:membros`
24627        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
24628        // (a40b0e3) required-`String`-carry accessor pins and the peer
24629        // per-`:contratos` [`WitContract::source`] /
24630        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
24631        // accessor pins, extended onto the peer per-`CircuitBreaker`
24632        // required-`u32` scalar-value axis. Pins against a future silent
24633        // detour that re-derived the trip threshold from a peer axis (an
24634        // accidental `self.window.as_secs() as u32` collapse that read
24635        // the breaker's rolling-window duration as a failure count), a
24636        // `0 → 1` cluster-default projection (which would silently absorb
24637        // the `PolicyBreakerZeroFailures` refusal case at the accessor
24638        // boundary), or a bounds-collapsing accessor that clamped the
24639        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
24640        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24641        // must ship the raw slot verbatim).
24642        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
24643            let cb = CircuitBreaker {
24644                max_failures,
24645                window: Duration::from_secs(60),
24646            };
24647            assert_eq!(
24648                cb.max_failures(),
24649                max_failures,
24650                "CircuitBreaker::max_failures must return :politicas \
24651                 :circuit-breaker :max-failures verbatim (got {}, \
24652                 expected {max_failures})",
24653                cb.max_failures(),
24654            );
24655            assert_eq!(
24656                cb.max_failures(),
24657                cb.max_failures,
24658                "CircuitBreaker::max_failures must byte-equal the raw \
24659                 .max_failures field access across every value in the \
24660                 u32 accept-set",
24661            );
24662        }
24663    }
24664
24665    #[test]
24666    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
24667        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24668        // `:circuit-breaker :max-failures` zero-floor arm must key off
24669        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
24670        // field access. Structurally: a `CircuitBreaker { max_failures:
24671        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
24672        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
24673        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
24674        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
24675        // pass validate. The pair jointly pins the accessor +
24676        // validate-gate composition: any future silent detour that had
24677        // the accessor return a fresh `1` on the zero arm (a
24678        // `.max_failures().max(1)` collapse) would silently absorb the
24679        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
24680        // and the validate gate would accept a struct-literal
24681        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
24682        // catches that at caixa-core build time.
24683        //
24684        // Peer of the sibling per-`:politicas`
24685        // [`MeshPolicy::mtls_required`] (c0110f1) /
24686        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
24687        // (7073d0f) accessor-composition pins on the sibling optional-
24688        // scalar axes — same "the validate / shape-gate predicate must
24689        // route through the substrate-primitive typed dispatch"
24690        // discipline extended onto the peer per-`CircuitBreaker`
24691        // required-scalar composition axis.
24692        let mut spec = three_member_spec();
24693        spec.politicas = MeshPolicy {
24694            circuit_breaker: Some(CircuitBreaker {
24695                max_failures: 0,
24696                window: Duration::from_secs(60),
24697            }),
24698            ..MeshPolicy::default()
24699        };
24700        assert!(
24701            matches!(
24702                spec.validate(),
24703                Err(AplicacaoError::PolicyBreakerZeroFailures)
24704            ),
24705            "validate_politicas must reject max_failures == 0 with \
24706             PolicyBreakerZeroFailures — the accessor and the validate \
24707             gate must route through the same substrate-primitive typed \
24708             dispatch on the :max-failures zero-floor arm",
24709        );
24710        spec.politicas = MeshPolicy {
24711            circuit_breaker: Some(CircuitBreaker {
24712                max_failures: 1,
24713                window: Duration::from_secs(60),
24714            }),
24715            ..MeshPolicy::default()
24716        };
24717        assert!(
24718            spec.validate().is_ok(),
24719            "validate_politicas must accept max_failures == 1 (the \
24720             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
24721             accept-set)",
24722        );
24723    }
24724
24725    #[test]
24726    fn circuit_breaker_max_failures_projects_u32_by_copy() {
24727        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
24728        // `u32` by copy — `u32` is `Copy` and the accessor must return
24729        // by value, not by reference. Peer of the sibling
24730        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
24731        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
24732        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
24733        // optional-scalar axes, extended onto the peer
24734        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
24735        // the accessor's returned `u32` must outlive `&self` (multiple
24736        // calls must return equal values from a dropped-`&self` copy,
24737        // since the returned scalar carries no borrow), and calling
24738        // the accessor twice on the same CircuitBreaker must yield the
24739        // same `u32` verbatim (idempotent, no side effects on `&self`).
24740        //
24741        // Pins against a future silent detour that returned `&u32`
24742        // (which would type-check but silently break every downstream
24743        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
24744        // first parameter is `u32`, and `&u32` would fold to a detached
24745        // copy at the call site with a `*` deref the sibling accessors
24746        // don't need), an accidental `.max_failures.wrapping_add(0)`
24747        // detour that returned a fresh copy through an arithmetic
24748        // no-op (breaking a future `const fn` regression), or a
24749        // one-arm-only accessor that returned a saturating value on
24750        // some sentinel input (breaking the pass-through invariant the
24751        // sibling required-scalar accessors carry).
24752        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
24753            let cb = CircuitBreaker {
24754                max_failures,
24755                window: Duration::from_secs(60),
24756            };
24757            let first = cb.max_failures();
24758            let second = cb.max_failures();
24759            assert_eq!(
24760                first, second,
24761                "CircuitBreaker::max_failures must be idempotent — two \
24762                 successive calls on the same &self must return the \
24763                 same u32",
24764            );
24765            assert_eq!(
24766                first, max_failures,
24767                "CircuitBreaker::max_failures must return :politicas \
24768                 :circuit-breaker :max-failures verbatim by copy — \
24769                 got {first}, expected {max_failures}",
24770            );
24771        }
24772    }
24773
24774    #[test]
24775    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
24776        // The canonical per-`:politicas :circuit-breaker` `:window`
24777        // Envoy-outlier-detection rolling-observation-interval scalar
24778        // pin: [`CircuitBreaker::window`] must return the
24779        // `:politicas :circuit-breaker :window` typed `Duration`
24780        // verbatim, byte-equal to the raw field access across every
24781        // representative value in the accept-set — `Duration::from_millis(1)`
24782        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
24783        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
24784        // gate carves out on the sibling `PolicyBreakerZeroWindow`
24785        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
24786        // same gate carves out on the sibling
24787        // `PolicyBreakerWindowExceedsCap` refusal),
24788        // `Duration::ZERO` (a past-the-guard sentinel that pins the
24789        // accessor doesn't perform a silent bounds-collapse into
24790        // `Duration::from_millis(1)` on the zero arm — validate rejects
24791        // zero but the accessor must ship the raw slot verbatim so a
24792        // validate-time gate regression surfaces at the emit boundary
24793        // rather than being silently absorbed),
24794        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
24795        // far above the 1h cap — that pins the accessor doesn't perform
24796        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
24797        // at the return path).
24798        //
24799        // Second sub-struct required-scalar accessor pin on the M3
24800        // mesh-slot family — sibling in shape to the just-landed
24801        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
24802        // (3a74062) required-`u32` accessor pin on the peer
24803        // per-`CircuitBreaker` required-axis, extended onto the
24804        // per-sub-struct required-`Duration` axis. Pins against a
24805        // future silent detour that re-derived the observation window
24806        // from a peer axis (an accidental
24807        // `Duration::from_secs(self.max_failures as u64)` collapse that
24808        // read the breaker's trip count as an observation-interval
24809        // duration), a `Duration::ZERO → Duration::from_millis(1)`
24810        // cluster-default projection (which would silently absorb the
24811        // `PolicyBreakerZeroWindow` refusal case at the accessor
24812        // boundary), or a bounds-collapsing accessor that clamped the
24813        // return through `POLICY_BREAKER_WINDOW_MAX` (the
24814        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24815        // must ship the raw slot verbatim).
24816        for window in [
24817            Duration::from_millis(1),
24818            POLICY_BREAKER_WINDOW_MAX,
24819            Duration::ZERO,
24820            Duration::from_secs(86_400),
24821        ] {
24822            let cb = CircuitBreaker {
24823                max_failures: 5,
24824                window,
24825            };
24826            assert_eq!(
24827                cb.window(),
24828                window,
24829                "CircuitBreaker::window must return :politicas \
24830                 :circuit-breaker :window verbatim (got {:?}, \
24831                 expected {window:?})",
24832                cb.window(),
24833            );
24834            assert_eq!(
24835                cb.window(),
24836                cb.window,
24837                "CircuitBreaker::window must byte-equal the raw \
24838                 .window field access across every value in the \
24839                 Duration accept-set",
24840            );
24841        }
24842    }
24843
24844    #[test]
24845    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
24846        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24847        // `:circuit-breaker :window` zero-floor arm must key off
24848        // [`CircuitBreaker::window`], not the raw `.window` field
24849        // access. Structurally: a `CircuitBreaker { window:
24850        // Duration::ZERO, .. }` embedded in a
24851        // `:politicas :circuit-breaker` slot must surface the
24852        // `PolicyBreakerZeroWindow` refusal exactly, and a
24853        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
24854        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
24855        // accept-set) must pass validate. The pair jointly pins the
24856        // accessor + validate-gate composition: any future silent
24857        // detour that had the accessor return a fresh
24858        // `Duration::from_millis(1)` on the zero arm (a
24859        // `.window().max(Duration::from_millis(1))` collapse) would
24860        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
24861        // accessor boundary and the validate gate would accept a
24862        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
24863        // — the composition pin catches that at caixa-core build time.
24864        //
24865        // Peer of the sibling per-`CircuitBreaker`
24866        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
24867        // pin on the peer required-scalar `:max-failures` axis — same
24868        // "the validate / shape-gate predicate must route through the
24869        // substrate-primitive typed dispatch" discipline extended onto
24870        // the peer per-`CircuitBreaker` required-`Duration` composition
24871        // axis.
24872        let mut spec = three_member_spec();
24873        spec.politicas = MeshPolicy {
24874            circuit_breaker: Some(CircuitBreaker {
24875                max_failures: 5,
24876                window: Duration::ZERO,
24877            }),
24878            ..MeshPolicy::default()
24879        };
24880        assert!(
24881            matches!(
24882                spec.validate(),
24883                Err(AplicacaoError::PolicyBreakerZeroWindow)
24884            ),
24885            "validate_politicas must reject window == Duration::ZERO \
24886             with PolicyBreakerZeroWindow — the accessor and the \
24887             validate gate must route through the same substrate-\
24888             primitive typed dispatch on the :window zero-floor arm",
24889        );
24890        spec.politicas = MeshPolicy {
24891            circuit_breaker: Some(CircuitBreaker {
24892                max_failures: 5,
24893                window: Duration::from_millis(1),
24894            }),
24895            ..MeshPolicy::default()
24896        };
24897        assert!(
24898            spec.validate().is_ok(),
24899            "validate_politicas must accept window == \
24900             Duration::from_millis(1) (the lower boundary of the \
24901             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
24902        );
24903    }
24904
24905    #[test]
24906    fn circuit_breaker_window_projects_duration_by_copy() {
24907        // The by-copy pin: [`CircuitBreaker::window`] returns
24908        // `Duration` by copy — `Duration` is `Copy` and the accessor
24909        // must return by value, not by reference. Peer of the sibling
24910        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
24911        // (3a74062) by-copy pin on the peer required-scalar
24912        // `:max-failures` axis, extended onto the peer
24913        // per-`CircuitBreaker` 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        // CircuitBreaker 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        // [`crate::render::require_positive_canonical_bounded_duration`]'s
24925        // first parameter is `Duration`, and `&Duration` would fold to
24926        // a detached copy at the call site with a `*` deref the sibling
24927        // accessors don't need), an accidental `.window + Duration::ZERO`
24928        // detour that returned a fresh copy through an arithmetic
24929        // no-op (breaking a future `const fn` regression), or a
24930        // one-arm-only accessor that returned a saturating value on
24931        // some sentinel input (breaking the pass-through invariant the
24932        // sibling required-scalar accessors carry).
24933        for window in [
24934            Duration::from_millis(1),
24935            POLICY_BREAKER_WINDOW_MAX,
24936            Duration::ZERO,
24937            Duration::from_secs(86_400),
24938        ] {
24939            let cb = CircuitBreaker {
24940                max_failures: 5,
24941                window,
24942            };
24943            let first = cb.window();
24944            let second = cb.window();
24945            assert_eq!(
24946                first, second,
24947                "CircuitBreaker::window must be idempotent — two \
24948                 successive calls on the same &self must return the \
24949                 same Duration",
24950            );
24951            assert_eq!(
24952                first, window,
24953                "CircuitBreaker::window must return :politicas \
24954                 :circuit-breaker :window verbatim by copy — \
24955                 got {first:?}, expected {window:?}",
24956            );
24957        }
24958    }
24959
24960    #[test]
24961    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
24962        // Apex-identity pair-invariant pin composing both substrate-
24963        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
24964        // and [`WitContract::destination`] — at the emit-side call shape
24965        // every per-`(:de, :para)` CNP L4 port reader now takes. The
24966        // invariant, evaluated per-edge:
24967        //
24968        //   spec.port_for_destination(c.destination()) == expected_port
24969        //
24970        // where `expected_port` is `entrada.port` when
24971        // `c.destination() == entrada.destination()` and
24972        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
24973        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
24974        // pin on the per-`:entrada` axis — that pin encodes the apex
24975        // ingress L4 identity via `entrada.destination()`; this pin
24976        // encodes the per-edge L4 identity via `c.destination()`, and
24977        // both compose on the same substrate-primitive resolver so a
24978        // future refactor that silently split either accessor's apex
24979        // behavior surfaces at caixa-core build time.
24980        let mut spec = three_member_spec();
24981        if let Some(e) = spec.entrada.as_mut() {
24982            e.para = "cart".into();
24983            e.port = 8443;
24984        }
24985        let apex_contract = WitContract {
24986            de: "checkout".into(),
24987            para: "cart".into(),
24988            wit: "wasi:http/proxy".into(),
24989            endpoint: Some("/hello".into()),
24990            subject: None,
24991            slot: None,
24992        };
24993        assert_eq!(
24994            spec.port_for_destination(apex_contract.destination()),
24995            8443,
24996            "`spec.port_for_destination(c.destination())` must equal \
24997             `entrada.port` when the contract callee names the ingress \
24998             apex — the CNP per-edge L4 port and the HTTPRoute apex \
24999             backendRef port share this substrate-primitive resolver.",
25000        );
25001        let non_apex_contract = WitContract {
25002            de: "cart".into(),
25003            para: "payment".into(),
25004            wit: "wasi:http/proxy".into(),
25005            endpoint: Some("/charge".into()),
25006            subject: None,
25007            slot: None,
25008        };
25009        assert_eq!(
25010            spec.port_for_destination(non_apex_contract.destination()),
25011            DEFAULT_SERVICO_PORT,
25012            "`spec.port_for_destination(c.destination())` must fall back \
25013             to the substrate-canonical port floor when the contract \
25014             callee is not the ingress apex — the resolver's non-apex \
25015             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
25016        );
25017    }
25018
25019    #[test]
25020    fn membro_key_consts_are_lower_camel_case_shape() {
25021        // Shape-pin: every `MEMBRO_KEY_*` const must be a
25022        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25023        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25024        // leading capital, no whitespace / dots) — the canonical shape
25025        // the `#[serde(rename_all = "camelCase")]` derive produces on
25026        // [`Membro`]. A future flip to a non-camelCase attribute at
25027        // the derive surfaces both here (this test fails on the
25028        // stale-constant shape) and at
25029        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
25030        // fails on the mismatch between const and derive). Peer with
25031        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
25032        // on the sibling `SupervisorSpec` top-level axis.
25033        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25034            assert!(
25035                !key.is_empty(),
25036                "MEMBRO_KEY_* must be non-empty (got {key:?})"
25037            );
25038            let first = key.chars().next().unwrap();
25039            assert!(
25040                first.is_ascii_lowercase(),
25041                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
25042                 (got {key:?}, leads with {first:?})",
25043            );
25044            assert!(
25045                key.chars().all(|c| c.is_ascii_alphanumeric()),
25046                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
25047                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25048            );
25049        }
25050    }
25051
25052    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
25053
25054    #[test]
25055    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
25056        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
25057        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
25058        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
25059        // keys the `#[serde(rename_all = "camelCase")]` attribute on
25060        // [`WitContract`] emits for the required-triad. The three
25061        // sibling payload-arm keys already pin under
25062        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
25063        // `STORE_FIELD_NAME` — pin all six alongside so a future
25064        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25065        // verbatim-field-name flip at the derive attribute (any of which
25066        // would silently break every downstream JSON consumer that
25067        // reaches for one of the six via `Value::get(...)`) surfaces
25068        // here as a build-time test failure at `aplicacao.rs`, not as an
25069        // apply-time `.get(<stale-canonical-const>)` returning `None`
25070        // far from the derive-attr drift's commit. Peer with the sibling
25071        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25072        // pin on the M3 `:membros` per-entry axis — same discipline the
25073        // `Membro` per-entry lift established, extended here to the
25074        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
25075        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
25076        // axis on the Aplicacao surface without a lifted serde-key peer.
25077        let c = WitContract {
25078            de: "cart".into(),
25079            para: "catalog".into(),
25080            wit: "wasi:http/proxy".into(),
25081            endpoint: Some("/lookup".into()),
25082            subject: None,
25083            slot: None,
25084        };
25085        let json = serde_json::to_string(&c).unwrap();
25086        for key in [
25087            crate::CONTRATO_KEY_DE,
25088            crate::CONTRATO_KEY_PARA,
25089            crate::CONTRATO_KEY_WIT,
25090            WitTarget::HTTP_FIELD_NAME,
25091        ] {
25092            let quoted = format!("\"{key}\"");
25093            assert!(
25094                json.contains(&quoted),
25095                "serialized WitContract must carry the lifted \
25096                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
25097                 {quoted} verbatim in the JSON emission (got: {json})",
25098            );
25099        }
25100
25101        // Pin the two remaining payload-arm keys by round-tripping a
25102        // `WitContract` under each payload-shape (pub-sub, store) — the
25103        // required-triad appears on every emission but the payload arms
25104        // only surface when their `Option<String>` field is `Some`.
25105        let pubsub = WitContract {
25106            de: "cart".into(),
25107            para: "events".into(),
25108            wit: "nats:pub-sub".into(),
25109            endpoint: None,
25110            subject: Some("orders.placed".into()),
25111            slot: None,
25112        };
25113        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
25114        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
25115        assert!(
25116            pubsub_json.contains(&pubsub_quoted),
25117            "serialized pub-sub WitContract must carry the lifted \
25118             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
25119             verbatim in the JSON emission (got: {pubsub_json})",
25120        );
25121        let store = WitContract {
25122            de: "cart".into(),
25123            para: "sessions".into(),
25124            wit: "wasi:keyvalue/store".into(),
25125            endpoint: None,
25126            subject: None,
25127            slot: Some("cart/$id".into()),
25128        };
25129        let store_json = serde_json::to_string(&store).unwrap();
25130        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
25131        assert!(
25132            store_json.contains(&store_quoted),
25133            "serialized store WitContract must carry the lifted \
25134             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
25135             verbatim in the JSON emission (got: {store_json})",
25136        );
25137    }
25138
25139    #[test]
25140    fn contrato_key_consts_are_pairwise_distinct() {
25141        // Cross-axis drift-detection pin: a future collapse of the six
25142        // canonical [`WitContract`] per-entry byte-strings onto the same
25143        // value (e.g. an accidental copy-paste flip of
25144        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
25145        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
25146        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
25147        // every downstream probe on one axis onto the sibling axis's
25148        // overlay entry and pass every propagation-probe test that
25149        // expected only the stale axis's value. Peer of the sibling
25150        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
25151        // widened here to the six-way axis the `WitContract`
25152        // required-triad + `WitTarget` payload-triad jointly cover.
25153        let all = [
25154            crate::CONTRATO_KEY_DE,
25155            crate::CONTRATO_KEY_PARA,
25156            crate::CONTRATO_KEY_WIT,
25157            WitTarget::HTTP_FIELD_NAME,
25158            WitTarget::PUBSUB_FIELD_NAME,
25159            WitTarget::STORE_FIELD_NAME,
25160        ];
25161        for (i, a) in all.iter().enumerate() {
25162            for b in all.iter().skip(i + 1) {
25163                assert_ne!(
25164                    a, b,
25165                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
25166                     must be pairwise-distinct canonical byte-sequences \
25167                     — got `{a}` == `{b}`",
25168                );
25169            }
25170        }
25171    }
25172
25173    #[test]
25174    fn contrato_key_consts_are_lower_camel_case_shape() {
25175        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
25176        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
25177        // byte-sequence (no `snake_case` underscores, no `kebab-case`
25178        // hyphens, no leading colon, no `PascalCase` leading capital, no
25179        // whitespace / dots) — the canonical shape the
25180        // `#[serde(rename_all = "camelCase")]` derive produces on
25181        // [`WitContract`]. A future flip to a non-camelCase attribute at
25182        // the derive surfaces both here (this test fails on the
25183        // stale-constant shape) and at
25184        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25185        // (that test fails on the mismatch between const and derive).
25186        // Peer with `membro_key_consts_are_lower_camel_case_shape`
25187        // (ce80ca0) on the sibling `Membro` per-entry axis.
25188        for key in [
25189            crate::CONTRATO_KEY_DE,
25190            crate::CONTRATO_KEY_PARA,
25191            crate::CONTRATO_KEY_WIT,
25192            WitTarget::HTTP_FIELD_NAME,
25193            WitTarget::PUBSUB_FIELD_NAME,
25194            WitTarget::STORE_FIELD_NAME,
25195        ] {
25196            assert!(
25197                !key.is_empty(),
25198                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25199                 non-empty (got {key:?})"
25200            );
25201            let first = key.chars().next().unwrap();
25202            assert!(
25203                first.is_ascii_lowercase(),
25204                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
25205                 with an ASCII-lowercase byte (got {key:?}, leads with \
25206                 {first:?})",
25207            );
25208            assert!(
25209                key.chars().all(|c| c.is_ascii_alphanumeric()),
25210                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25211                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
25212                 whitespace (got {key:?})",
25213            );
25214        }
25215    }
25216
25217    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
25218
25219    #[test]
25220    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
25221        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
25222        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
25223        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
25224        // name the exact camelCase JSON keys the
25225        // `#[serde(rename_all = "camelCase")]` attribute on
25226        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
25227        // pin that each canonical byte-sequence appears verbatim in the
25228        // JSON — a future accidental `rename_all = "snake_case"` /
25229        // `"kebab-case"` / verbatim-field-name flip at the derive
25230        // attribute (any of which would silently break every downstream
25231        // JSON consumer that reaches for one of the four consts via
25232        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
25233        // emitter's per-Aplicacao hostname/paths/port projection, the
25234        // future `app-operator` reconciler's per-Aplicacao ingress
25235        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
25236        // materializer's admission-time cross-check) surfaces here as
25237        // a build-time test failure at `aplicacao.rs`, not as an
25238        // apply-time `.get(<stale-canonical-const>)` returning `None`
25239        // far from the derive-attr drift's commit. Peer with the
25240        // sibling
25241        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25242        // (ca463a4) and
25243        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25244        // pins on the M3 collection-slot atom axes — same discipline
25245        // both collection-slot lifts established, extended here to the
25246        // singleton `:entrada` mesh-slot atom axis, the last M3
25247        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
25248        // axis on the Aplicacao surface without a lifted serde-key
25249        // peer.
25250        let e = Entrada {
25251            host: "checkout.quero.cloud".into(),
25252            para: "cart".into(),
25253            paths: vec!["/cart".into()],
25254            port: 8080,
25255        };
25256        let json = serde_json::to_string(&e).unwrap();
25257        for key in [
25258            crate::ENTRADA_KEY_HOST,
25259            crate::ENTRADA_KEY_PARA,
25260            crate::ENTRADA_KEY_PATHS,
25261            crate::ENTRADA_KEY_PORT,
25262        ] {
25263            let quoted = format!("\"{key}\"");
25264            assert!(
25265                json.contains(&quoted),
25266                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
25267                 byte-sequence {quoted} verbatim in the JSON emission \
25268                 (got: {json})",
25269            );
25270        }
25271    }
25272
25273    #[test]
25274    fn entrada_key_consts_are_pairwise_distinct() {
25275        // Cross-axis drift-detection pin: a future collapse of the four
25276        // canonical [`Entrada`] singleton byte-strings onto the same
25277        // value (e.g. an accidental copy-paste flip of
25278        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
25279        // silently reroute every downstream probe on one axis onto the
25280        // sibling axis's overlay entry and pass every propagation-probe
25281        // test that expected only the stale axis's value — the
25282        // Gateway/HTTPRoute emitter would read the hostname string
25283        // where the destination-Servico name was expected (or vice
25284        // versa), the admission-webhook cross-check would compare the
25285        // wrong pair of values, and the resulting Gateway resource
25286        // would either be admitted with garbage or rejected at the
25287        // controller far from the rebrand commit's source. Peer of the
25288        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
25289        // tetrad (40cc4e5), the two-way distinct pin on the
25290        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
25291        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
25292        // triad (ca463a4).
25293        let all = [
25294            crate::ENTRADA_KEY_HOST,
25295            crate::ENTRADA_KEY_PARA,
25296            crate::ENTRADA_KEY_PATHS,
25297            crate::ENTRADA_KEY_PORT,
25298        ];
25299        for (i, a) in all.iter().enumerate() {
25300            for b in all.iter().skip(i + 1) {
25301                assert_ne!(
25302                    a, b,
25303                    "ENTRADA_KEY_* consts must be pairwise-distinct \
25304                     canonical byte-sequences — got `{a}` == `{b}`",
25305                );
25306            }
25307        }
25308    }
25309
25310    #[test]
25311    fn entrada_key_consts_are_lower_camel_case_shape() {
25312        // Shape-pin: every `ENTRADA_KEY_*` const must be a
25313        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25314        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25315        // leading capital, no whitespace / dots) — the canonical shape
25316        // the `#[serde(rename_all = "camelCase")]` derive produces on
25317        // [`Entrada`]. A future flip to a non-camelCase attribute at
25318        // the derive surfaces both here (this test fails on the
25319        // stale-constant shape) and at
25320        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
25321        // test fails on the mismatch between const and derive). Peer
25322        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
25323        // and `contrato_key_consts_are_lower_camel_case_shape`
25324        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
25325        // entry axes.
25326        for key in [
25327            crate::ENTRADA_KEY_HOST,
25328            crate::ENTRADA_KEY_PARA,
25329            crate::ENTRADA_KEY_PATHS,
25330            crate::ENTRADA_KEY_PORT,
25331        ] {
25332            assert!(
25333                !key.is_empty(),
25334                "ENTRADA_KEY_* must be non-empty (got {key:?})"
25335            );
25336            let first = key.chars().next().unwrap();
25337            assert!(
25338                first.is_ascii_lowercase(),
25339                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
25340                 (got {key:?}, leads with {first:?})",
25341            );
25342            assert!(
25343                key.chars().all(|c| c.is_ascii_alphanumeric()),
25344                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
25345                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25346            );
25347        }
25348    }
25349
25350    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
25351
25352    #[test]
25353    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
25354        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
25355        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
25356        // [`crate::POLITICAS_KEY_RETRIES`] /
25357        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
25358        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
25359        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
25360        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
25361        // on [`MeshPolicy`] emits. Three of the five axes
25362        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
25363        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
25364        // camelCase transforms — the derive-attribute is load-bearing
25365        // on those, unlike the sibling `Entrada` / `Membro` /
25366        // `WitContract` structs whose fields are all lowercase-single-
25367        // word and where the derive is a no-op on every axis.
25368        // Serialize a fully-populated [`MeshPolicy`] (every axis
25369        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
25370        // on none of the five slots) and pin that each canonical
25371        // byte-sequence appears verbatim in the JSON — a future
25372        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25373        // verbatim-field-name flip at the derive attribute (any of
25374        // which would silently break every downstream JSON consumer
25375        // that reaches for one of the five consts via
25376        // `Value::get(...)` — the future M4 per-edge `:politicas`
25377        // overlay projection onto Cilium `L7Rules` and Gateway API
25378        // `HTTPRoute` backend timeouts, the future
25379        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25380        // admission-time mesh-policy cross-check, the future
25381        // `feira lint` per-`:politicas` bound-check gate) surfaces here
25382        // as a build-time test failure at `aplicacao.rs`, not as an
25383        // apply-time `.get(<stale-canonical-const>)` returning `None`
25384        // far from the derive-attr drift's commit. Peer with the
25385        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
25386        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25387        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
25388        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
25389        // atom axes — same discipline every M3 sibling lift
25390        // established, extended here to the singleton `:politicas`
25391        // mesh-slot atom axis, closing the last M3 typed-struct
25392        // top-level `#[serde(rename_all = "camelCase")]` axis on the
25393        // Aplicacao surface without a lifted serde-key peer.
25394        let p = MeshPolicy {
25395            timeout: Some(Duration::from_secs(30)),
25396            retries: Some(3),
25397            circuit_breaker: Some(CircuitBreaker {
25398                max_failures: 5,
25399                window: Duration::from_secs(60),
25400            }),
25401            mtls_required: Some(true),
25402            rate_limit: Some(RateLimit {
25403                rate: 100,
25404                window: Duration::from_secs(1),
25405            }),
25406        };
25407        let json = serde_json::to_string(&p).unwrap();
25408        for key in [
25409            crate::POLITICAS_KEY_TIMEOUT,
25410            crate::POLITICAS_KEY_RETRIES,
25411            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25412            crate::POLITICAS_KEY_MTLS_REQUIRED,
25413            crate::POLITICAS_KEY_RATE_LIMIT,
25414        ] {
25415            let quoted = format!("\"{key}\"");
25416            assert!(
25417                json.contains(&quoted),
25418                "serialized MeshPolicy must carry the lifted \
25419                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
25420                 JSON emission (got: {json})",
25421            );
25422        }
25423    }
25424
25425    #[test]
25426    fn politicas_key_consts_are_pairwise_distinct() {
25427        // Cross-axis drift-detection pin: a future collapse of the five
25428        // canonical [`MeshPolicy`] singleton byte-strings onto the same
25429        // value (e.g. an accidental copy-paste flip of
25430        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
25431        // would silently reroute every downstream probe on one axis
25432        // onto the sibling axis's overlay entry and pass every
25433        // propagation-probe test that expected only the stale axis's
25434        // value — the M4 per-edge `:politicas` overlay projection would
25435        // read the retry-count string where the timeout duration was
25436        // expected (or vice versa), the CR materializer's admission
25437        // cross-check would compare the wrong pair of values, and the
25438        // resulting mesh reconciler would either bind the wrong axis
25439        // or reject the resource at reconcile far from the rebrand
25440        // commit's source. Peer of the sibling four-way distinct pin
25441        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
25442        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25443        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
25444        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25445        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25446        let all = [
25447            crate::POLITICAS_KEY_TIMEOUT,
25448            crate::POLITICAS_KEY_RETRIES,
25449            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25450            crate::POLITICAS_KEY_MTLS_REQUIRED,
25451            crate::POLITICAS_KEY_RATE_LIMIT,
25452        ];
25453        for (i, a) in all.iter().enumerate() {
25454            for b in all.iter().skip(i + 1) {
25455                assert_ne!(
25456                    a, b,
25457                    "POLITICAS_KEY_* consts must be pairwise-distinct \
25458                     canonical byte-sequences — got `{a}` == `{b}`",
25459                );
25460            }
25461        }
25462    }
25463
25464    #[test]
25465    fn politicas_key_consts_are_lower_camel_case_shape() {
25466        // Shape-pin: every `POLITICAS_KEY_*` const must be a
25467        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25468        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25469        // leading capital, no whitespace / dots) — the canonical shape
25470        // the `#[serde(rename_all = "camelCase")]` derive produces on
25471        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
25472        // at the derive surfaces both here (this test fails on the
25473        // stale-constant shape) and at
25474        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25475        // (that test fails on the mismatch between const and derive).
25476        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
25477        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25478        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25479        // (ca463a4) on the sibling M3 typed-struct axes.
25480        for key in [
25481            crate::POLITICAS_KEY_TIMEOUT,
25482            crate::POLITICAS_KEY_RETRIES,
25483            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25484            crate::POLITICAS_KEY_MTLS_REQUIRED,
25485            crate::POLITICAS_KEY_RATE_LIMIT,
25486        ] {
25487            assert!(
25488                !key.is_empty(),
25489                "POLITICAS_KEY_* must be non-empty (got {key:?})"
25490            );
25491            let first = key.chars().next().unwrap();
25492            assert!(
25493                first.is_ascii_lowercase(),
25494                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
25495                 byte (got {key:?}, leads with {first:?})",
25496            );
25497            assert!(
25498                key.chars().all(|c| c.is_ascii_alphanumeric()),
25499                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
25500                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25501            );
25502        }
25503    }
25504
25505    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
25506
25507    #[test]
25508    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
25509        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
25510        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
25511        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
25512        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25513        // [`CircuitBreaker`] emits inside the
25514        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
25515        // two axes (`max_failures` → `maxFailures`) is a non-trivial
25516        // camelCase transform — the derive-attribute is load-bearing on
25517        // that axis, unlike the sibling `window` field where the derive
25518        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
25519        // pin that each canonical byte-sequence appears verbatim in the
25520        // JSON — a future accidental `rename_all = "snake_case"` /
25521        // `"kebab-case"` / verbatim-field-name flip at the derive
25522        // attribute (any of which would silently break every downstream
25523        // JSON consumer that reaches for one of the two consts via
25524        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
25525        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
25526        // per-edge `:politicas` overlay projection onto the mesh's
25527        // per-backend consecutive-failure-counter tripping threshold, the
25528        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25529        // admission-time breaker cross-check, the future `feira lint`
25530        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
25531        // here as a build-time test failure at `aplicacao.rs`, not as an
25532        // apply-time `.get(<stale-canonical-const>)` returning `None`
25533        // far from the derive-attr drift's commit. Peer with the sibling
25534        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25535        // (b55cca7) parent-axis pin — that test pins the outer
25536        // sub-block key the derive on [`MeshPolicy`] emits, this test
25537        // pins the inner keys the derive on the payload type emits, so
25538        // the two together lock the whole [`MeshPolicy`] breaker-tuning
25539        // shape end-to-end at build time.
25540        let cb = CircuitBreaker {
25541            max_failures: 5,
25542            window: Duration::from_secs(60),
25543        };
25544        let json = serde_json::to_string(&cb).unwrap();
25545        for key in [
25546            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25547            crate::CIRCUIT_BREAKER_KEY_WINDOW,
25548        ] {
25549            let quoted = format!("\"{key}\"");
25550            assert!(
25551                json.contains(&quoted),
25552                "serialized CircuitBreaker must carry the lifted \
25553                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
25554                 in the JSON emission (got: {json})",
25555            );
25556        }
25557    }
25558
25559    #[test]
25560    fn circuit_breaker_key_consts_are_pairwise_distinct() {
25561        // Cross-axis drift-detection pin: a future collapse of the two
25562        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
25563        // same value (e.g. an accidental copy-paste flip of
25564        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
25565        // `"maxFailures"`) would silently reroute every downstream
25566        // probe on one axis onto the sibling axis's overlay entry and
25567        // pass every propagation-probe test that expected only the
25568        // stale axis's value — the M4 per-edge `:politicas` overlay
25569        // projection would read the failure-count where the window
25570        // duration was expected (or vice versa), the CR materializer's
25571        // admission cross-check would compare the wrong pair of values,
25572        // and the resulting mesh reconciler would either bind the wrong
25573        // axis or reject the resource at reconcile far from the rebrand
25574        // commit's source. Peer of the sibling five-way distinct pin on
25575        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
25576        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
25577        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
25578        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
25579        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25580        let all = [
25581            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25582            crate::CIRCUIT_BREAKER_KEY_WINDOW,
25583        ];
25584        for (i, a) in all.iter().enumerate() {
25585            for b in all.iter().skip(i + 1) {
25586                assert_ne!(
25587                    a, b,
25588                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
25589                     canonical byte-sequences — got `{a}` == `{b}`",
25590                );
25591            }
25592        }
25593    }
25594
25595    #[test]
25596    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
25597        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
25598        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25599        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25600        // leading capital, no whitespace / dots) — the canonical shape
25601        // the `#[serde(rename_all = "camelCase")]` derive produces on
25602        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
25603        // at the derive surfaces both here (this test fails on the
25604        // stale-constant shape) and at
25605        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
25606        // (that test fails on the mismatch between const and derive).
25607        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
25608        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
25609        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25610        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25611        // (ca463a4) on the sibling M3 typed-struct axes.
25612        for key in [
25613            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25614            crate::CIRCUIT_BREAKER_KEY_WINDOW,
25615        ] {
25616            assert!(
25617                !key.is_empty(),
25618                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
25619            );
25620            let first = key.chars().next().unwrap();
25621            assert!(
25622                first.is_ascii_lowercase(),
25623                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
25624                 byte (got {key:?}, leads with {first:?})",
25625            );
25626            assert!(
25627                key.chars().all(|c| c.is_ascii_alphanumeric()),
25628                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
25629                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25630            );
25631        }
25632    }
25633
25634    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
25635
25636    #[test]
25637    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
25638        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
25639        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
25640        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
25641        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
25642        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
25643        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25644        // [`Placement`] emits. One of the four axes (`shard_key` →
25645        // `shardKey`) is a non-trivial camelCase transform — the
25646        // derive-attribute is load-bearing on that axis, unlike the
25647        // sibling `estrategia` / `clusters` / `affinity` axes whose
25648        // source-side field names carry no `_` and where the derive is a
25649        // no-op. Serialize a fully-populated [`Placement`] (both
25650        // `Option`-carrying axes `Some(_)` so
25651        // `skip_serializing_if = "Option::is_none"` fires on neither of
25652        // the two optional slots) and pin that each canonical
25653        // byte-sequence appears verbatim in the JSON — a future
25654        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25655        // verbatim-field-name flip at the derive attribute (any of which
25656        // would silently break every downstream consumer that reaches
25657        // for one of the four consts via
25658        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
25659        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
25660        // aggregator's per-cluster fanout filter keying off
25661        // `placement.clusters`, the M3 shard-pool dispatch materializer
25662        // keying off `placement.shardKey`, the M3 Adaptive compression
25663        // pass weighting off `placement.affinity`, every downstream
25664        // dispatcher branching on `placement.estrategia`, the future
25665        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25666        // admission-time placement cross-check, the future `feira lint`
25667        // per-`:placement` bound-check gate) surfaces here as a
25668        // build-time test failure at `aplicacao.rs`, not as an
25669        // apply-time `.get(<stale-canonical-const>)` returning `None`
25670        // far from the derive-attr drift's commit. Peer with the sibling
25671        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25672        // (b55cca7),
25673        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
25674        // (468e959),
25675        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
25676        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25677        // (ca463a4), and
25678        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25679        // pins on the M3 collection-slot / singleton-slot atom axes —
25680        // closes the last M3 typed-struct top-level
25681        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
25682        // surface without a drift-detection pin.
25683        let p = Placement {
25684            estrategia: PlacementStrategy::Sharded,
25685            clusters: vec!["rio".into(), "mar".into()],
25686            affinity: Some("data-locality".into()),
25687            shard_key: Some("$tenantId".into()),
25688        };
25689        let json = serde_json::to_string(&p).unwrap();
25690        for key in [
25691            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25692            crate::M3_PLACEMENT_KEY_CLUSTERS,
25693            crate::M3_PLACEMENT_KEY_AFFINITY,
25694            crate::M3_PLACEMENT_KEY_SHARD_KEY,
25695        ] {
25696            let quoted = format!("\"{key}\"");
25697            assert!(
25698                json.contains(&quoted),
25699                "serialized Placement must carry the lifted \
25700                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
25701                 the JSON emission (got: {json})",
25702            );
25703        }
25704    }
25705
25706    #[test]
25707    fn m3_placement_key_consts_are_pairwise_distinct() {
25708        // Cross-axis drift-detection pin: a future collapse of the four
25709        // canonical [`Placement`] sub-block byte-strings onto the same
25710        // value (e.g. an accidental copy-paste flip of
25711        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
25712        // `"affinity"`) would silently reroute every downstream probe on
25713        // one axis onto the sibling axis's overlay entry and pass every
25714        // propagation-probe test that expected only the stale axis's
25715        // value — the M3 shard-pool dispatch materializer would read the
25716        // affinity placement-hint where the shard-selection template was
25717        // expected (or vice versa), the M3 Adaptive compression pass's
25718        // cross-check would compare the wrong pair of values, and the
25719        // resulting placement engine would either bind the wrong axis or
25720        // reject the resource at reconcile far from the rebrand commit's
25721        // source. Peer of the sibling two-way distinct pin on the
25722        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
25723        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
25724        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25725        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
25726        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25727        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25728        let all = [
25729            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25730            crate::M3_PLACEMENT_KEY_CLUSTERS,
25731            crate::M3_PLACEMENT_KEY_AFFINITY,
25732            crate::M3_PLACEMENT_KEY_SHARD_KEY,
25733        ];
25734        for (i, a) in all.iter().enumerate() {
25735            for b in all.iter().skip(i + 1) {
25736                assert_ne!(
25737                    a, b,
25738                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
25739                     canonical byte-sequences — got `{a}` == `{b}`",
25740                );
25741            }
25742        }
25743    }
25744
25745    #[test]
25746    fn m3_placement_key_consts_are_lower_camel_case_shape() {
25747        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
25748        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25749        // `kebab-case` hyphens, no leading colon, no `PascalCase`
25750        // leading capital, no whitespace / dots) — the canonical shape
25751        // the `#[serde(rename_all = "camelCase")]` derive produces on
25752        // [`Placement`]. A future flip to a non-camelCase attribute at
25753        // the derive surfaces both here (this test fails on the stale-
25754        // constant shape) and at
25755        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
25756        // (that test fails on the mismatch between const and derive).
25757        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
25758        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
25759        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
25760        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25761        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25762        // (ca463a4) on the sibling M3 typed-struct axes.
25763        for key in [
25764            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25765            crate::M3_PLACEMENT_KEY_CLUSTERS,
25766            crate::M3_PLACEMENT_KEY_AFFINITY,
25767            crate::M3_PLACEMENT_KEY_SHARD_KEY,
25768        ] {
25769            assert!(
25770                !key.is_empty(),
25771                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
25772            );
25773            let first = key.chars().next().unwrap();
25774            assert!(
25775                first.is_ascii_lowercase(),
25776                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
25777                 byte (got {key:?}, leads with {first:?})",
25778            );
25779            assert!(
25780                key.chars().all(|c| c.is_ascii_alphanumeric()),
25781                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
25782                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25783            );
25784        }
25785    }
25786
25787    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
25788    //    destination-facing L4 port resolver every per-Aplicacao renderer
25789    //    reaching for a per-destination Servico TCP port axis routes
25790    //    through. The four pin tests below fix the four-way accept-set
25791    //    the resolver must always honor: (:entrada-para-matches,
25792    //    :entrada-para-mismatches, :entrada-none-so-fallback,
25793    //    :entrada-port-non-default-honored) — drift on any arm surfaces
25794    //    at caixa-core build time rather than at cluster-apply time.
25795
25796    #[test]
25797    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
25798        // The typed `:entrada` block's `:para "cart"` matches the
25799        // queried destination, so the resolver returns the author-
25800        // declared `:port` scalar verbatim — the canonical "the
25801        // destination Servico IS the ingress apex, honor the typed
25802        // listener port" arm of the port-resolution dispatch.
25803        let mut spec = three_member_spec();
25804        if let Some(e) = spec.entrada.as_mut() {
25805            e.para = "cart".into();
25806            e.port = 9090;
25807        }
25808        assert_eq!(
25809            spec.port_for_destination("cart"),
25810            9090,
25811            "port_for_destination(entrada.para) must return entrada.port \
25812             verbatim, not the DEFAULT_SERVICO_PORT fallback"
25813        );
25814    }
25815
25816    #[test]
25817    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
25818        // The typed `:entrada` block names `:para "cart"`, but the
25819        // queried destination is `"payment"` — a Servico that
25820        // participates in the mesh graph but is not the ingress apex.
25821        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
25822        // canonical port floor, closing the "non-apex destination reads
25823        // the substrate default" arm. Same fixture the peer
25824        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
25825        // pin at caixa-mesh exercises through the CNP emit-side path;
25826        // this pin exercises the shared underlying resolver directly.
25827        let spec = three_member_spec();
25828        assert_eq!(
25829            spec.port_for_destination("payment"),
25830            DEFAULT_SERVICO_PORT,
25831            "port_for_destination(non-apex-destination) must route \
25832             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
25833        );
25834    }
25835
25836    #[test]
25837    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
25838        // Internal-only Aplicacao — no `:entrada` block declared. Every
25839        // per-destination port query falls back to the lifted
25840        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
25841        // the Aplicacao surface admits `:entrada None` (internal mesh
25842        // with no external gateway); every downstream renderer's per-
25843        // destination port axis must still resolve to a well-defined
25844        // scalar even without an ingress apex.
25845        let mut spec = three_member_spec();
25846        spec.entrada = None;
25847        assert_eq!(
25848            spec.port_for_destination("cart"),
25849            DEFAULT_SERVICO_PORT,
25850            "port_for_destination on an internal-only Aplicacao must \
25851             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
25852             every destination"
25853        );
25854        assert_eq!(
25855            spec.port_for_destination("payment"),
25856            DEFAULT_SERVICO_PORT,
25857            "port_for_destination on an internal-only Aplicacao must \
25858             fall back uniformly across every destination — the fallback \
25859             is not entrada-shape-conditional"
25860        );
25861    }
25862
25863    #[test]
25864    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
25865        // Structural pin against a hypothetical future refactor that
25866        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
25867        // the resolver (a "normalize to the default when the author's
25868        // port matches the substrate default" collapse) — that would
25869        // break renderer sites that carry meaning on the emitted port
25870        // value beyond bare equality (a future per-cluster listener-
25871        // audit that keys off the author-declared port, not the
25872        // resolved-with-fallback port). Pin that a non-default
25873        // entrada.port is returned verbatim so drift here surfaces at
25874        // caixa-core build time.
25875        let mut spec = three_member_spec();
25876        if let Some(e) = spec.entrada.as_mut() {
25877            e.para = "cart".into();
25878            e.port = 8443;
25879        }
25880        assert_ne!(
25881            8443, DEFAULT_SERVICO_PORT,
25882            "test fixture must probe a port distinct from \
25883             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
25884        );
25885        assert_eq!(
25886            spec.port_for_destination("cart"),
25887            8443,
25888            "port_for_destination(entrada.para) must return entrada.port \
25889             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
25890        );
25891    }
25892
25893    #[test]
25894    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
25895        // Apex-identity pair-invariant pin composing both substrate-
25896        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
25897        // and [`Entrada::destination`] — at the emit-side call shape
25898        // every per-Aplicacao renderer's ingress-apex L4 port reader
25899        // now takes. The invariant:
25900        //
25901        //   spec.port_for_destination(entrada.destination()) == entrada.port
25902        //
25903        // holds by construction under today's single-destination
25904        // `:entrada` slot (`destination()` returns `entrada.para`, and
25905        // the resolver's apex arm matches `para == destination` and
25906        // returns `entrada.port`), and every downstream consumer that
25907        // composes the two accessors at the ingress apex — the
25908        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
25909        // `backendRefs[0].port` emit-site path, the peer future M4 CR
25910        // materializer's admission-webhook that promotes the scalar to
25911        // a per-CR override overlay, every future per-Aplicacao snapshot
25912        // renderer's apex-facing L4 port reader — reaches through the
25913        // same composition. Pin the identity across four permutations
25914        // (`:para` × `:port` including a non-default port to exercise
25915        // the honor-verbatim arm and a non-cart `:para` to exercise
25916        // destination-agnostic identity) so a future refactor that
25917        // silently split either accessor's apex behavior surfaces at
25918        // caixa-core build time — a subtle `destination()` renaming
25919        // that returned `entrada.host.as_str()` instead of
25920        // `entrada.para.as_str()` would blow this pin loudly, closing
25921        // the last quiet failure mode the two lifts admit in composition.
25922        //
25923        // Peer discipline with the sibling caixa-mesh cross-crate pin
25924        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
25925        // on the two-renderer pair-invariant axis; this pin encodes the
25926        // same two-consumer coherence rule at the substrate-primitive
25927        // level so the invariant survives even if every renderer is
25928        // deleted.
25929        for (para, port) in [
25930            ("cart", DEFAULT_SERVICO_PORT),
25931            ("cart", 8443u16),
25932            ("payment", 9090u16),
25933            ("catalog", 443u16),
25934        ] {
25935            let mut spec = three_member_spec();
25936            if let Some(e) = spec.entrada.as_mut() {
25937                e.para = para.into();
25938                e.port = port;
25939            }
25940            let expected_port = spec
25941                .entrada()
25942                .expect("three_member_spec carries a typed `:entrada` block")
25943                .port();
25944            let composed_port = {
25945                let entrada = spec.entrada().expect("entrada present");
25946                spec.port_for_destination(entrada.destination())
25947            };
25948            assert_eq!(
25949                composed_port, expected_port,
25950                "`spec.port_for_destination(entrada.destination())` must \
25951                 equal `entrada.port` under today's single-destination \
25952                 `:entrada` slot — this is the apex-identity contract \
25953                 every downstream ingress-apex L4 port reader relies on. \
25954                 Input :entrada :para: {para:?}, :entrada :port: {port}"
25955            );
25956        }
25957    }
25958
25959    #[test]
25960    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
25961        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
25962        // per-`:entrada` apex-arm membership probe must key off
25963        // [`Entrada::destination`], not the raw `.para` field access.
25964        // Structurally: setting ONLY the `:entrada :para` field to a
25965        // fresh non-cart destination on an otherwise-well-formed
25966        // Aplicacao must (1) leave `e.destination()` byte-equal to
25967        // `e.para.as_str()` (the accessor is byte-projective by
25968        // definition), and (2) cause the resolver's apex arm to fire
25969        // and return `entrada.port` at exactly that new destination
25970        // while every other destination string falls through to
25971        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
25972        // membership check. Pins against a future silent detour that
25973        // (a) re-derived the apex-arm membership probe off
25974        // `e.para == destination` in `port_for_destination` instead of
25975        // `e.destination() == destination`, silently disagreeing with
25976        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
25977        // consumers (`entrada.destination()` at
25978        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
25979        // caixa-mesh/src/lib.rs:2739) that already reach through the
25980        // accessor, (b) accessor-side introduced a per-tenant alias
25981        // arm the caller was unaware of, silently rewriting an
25982        // author-declared `:para "cart"` value to a canary-aliased
25983        // form — the raw-field-access resolver would fall through to
25984        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
25985        // while the peer emit-site consumers landed on the aliased
25986        // destination, splitting the ingress-apex L4 port at
25987        // cluster-apply time.
25988        //
25989        // Peer of the sibling
25990        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
25991        // (d0de220) composition pin on the per-`:membros` refusal-arm
25992        // axis — same "the shape-gate predicate must route through the
25993        // substrate-primitive typed dispatch" discipline extended onto
25994        // the per-`:entrada` apex-arm membership-probe axis. Closes
25995        // the last unlifted `.para` production-code read site on
25996        // `Entrada` in `caixa-core` — after this converge every
25997        // `caixa-core` `.para` field access outside the accessor's own
25998        // body and outside the `WitContract` per-`:contratos` sibling
25999        // axis is either a test-side field-setter or a doc-comment
26000        // reference.
26001        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
26002            let mut spec = three_member_spec();
26003            if let Some(e) = spec.entrada.as_mut() {
26004                e.para = para.into();
26005                e.port = port;
26006            }
26007            let e = spec
26008                .entrada
26009                .as_ref()
26010                .expect("three_member_spec carries a typed `:entrada` block");
26011            assert_eq!(
26012                e.destination(),
26013                e.para.as_str(),
26014                "Entrada::destination must byte-equal the .para field \
26015                 access — an accessor-side detour that no longer \
26016                 projects the raw field would silently split this \
26017                 drift-detection test from the port_for_destination \
26018                 apex-arm membership probe",
26019            );
26020            assert_eq!(
26021                spec.port_for_destination(para),
26022                port,
26023                "port_for_destination must key off the accessor-projected \
26024                 destination and return `entrada.port` on the apex arm — \
26025                 input :entrada :para: {para:?}, :entrada :port: {port}",
26026            );
26027            assert_eq!(
26028                spec.port_for_destination("ghost-destination-never-a-member"),
26029                DEFAULT_SERVICO_PORT,
26030                "port_for_destination must fall through to \
26031                 DEFAULT_SERVICO_PORT on a non-matching destination \
26032                 under the accessor-projected membership check — input \
26033                 :entrada :para: {para:?}, :entrada :port: {port}",
26034            );
26035        }
26036    }
26037
26038    #[test]
26039    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
26040        // The canonical per-`:politicas :rate-limit` `:rate`
26041        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
26042        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
26043        // typed `u32` verbatim, byte-equal to the raw field access
26044        // across every representative value in the accept-set — `1` (the
26045        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
26046        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
26047        // carves out on the sibling `PolicyRateLimitZero` refusal),
26048        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
26049        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
26050        // `0` (a past-the-guard sentinel that pins the accessor doesn't
26051        // perform a silent bounds-collapse into `1` on the zero arm —
26052        // validate rejects zero but the accessor must ship the raw slot
26053        // verbatim so a validate-time gate regression surfaces at the
26054        // emit boundary rather than being silently absorbed), `u32::MAX`
26055        // (a past-the-guard sentinel that pins the accessor doesn't
26056        // perform a silent bounds-collapse through
26057        // `POLICY_RATE_LIMIT_MAX` at the return path).
26058        //
26059        // First sub-struct required-scalar accessor pin on the
26060        // `RateLimit` axis — sibling in shape to the peer
26061        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
26062        // required-`u32` accessor pin on the peer per-sub-struct
26063        // required-axis. Pins against a future silent detour that
26064        // re-derived the token capacity from a peer axis (an accidental
26065        // `self.window.as_secs() as u32` collapse that read the
26066        // rate-limit window duration as a token count), a `0 → 1`
26067        // cluster-default projection (which would silently absorb the
26068        // `PolicyRateLimitZero` refusal case at the accessor boundary),
26069        // or a bounds-collapsing accessor that clamped the return
26070        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
26071        // gate owns the bounds; the accessor must ship the raw slot
26072        // verbatim).
26073        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26074            let rl = RateLimit {
26075                rate,
26076                window: Duration::from_secs(1),
26077            };
26078            assert_eq!(
26079                rl.rate(),
26080                rate,
26081                "RateLimit::rate must return :politicas :rate-limit :rate \
26082                 verbatim (got {}, expected {rate})",
26083                rl.rate(),
26084            );
26085            assert_eq!(
26086                rl.rate(),
26087                rl.rate,
26088                "RateLimit::rate must byte-equal the raw .rate field \
26089                 access across every value in the u32 accept-set",
26090            );
26091        }
26092    }
26093
26094    #[test]
26095    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
26096        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26097        // `:rate-limit :rate` zero-floor arm must key off
26098        // [`RateLimit::rate`], not the raw `.rate` field access.
26099        // Structurally: a `RateLimit { rate: 0, window:
26100        // Duration::from_secs(1) }` embedded in a `:politicas
26101        // :rate-limit` slot must surface the `PolicyRateLimitZero`
26102        // refusal exactly, and a `RateLimit { rate: 1, window:
26103        // Duration::from_secs(1) }` (the lower boundary of the
26104        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
26105        // The pair jointly pins the accessor + validate-gate composition:
26106        // any future silent detour that had the accessor return a fresh
26107        // `1` on the zero arm (a `.rate().max(1)` collapse) would
26108        // silently absorb the `PolicyRateLimitZero` refusal at the
26109        // accessor boundary and the validate gate would accept a
26110        // struct-literal `RateLimit { rate: 0, .. }` — the composition
26111        // pin catches that at caixa-core build time.
26112        //
26113        // Peer of the sibling per-`CircuitBreaker`
26114        // [`CircuitBreaker::max_failures`] (3a74062) /
26115        // [`CircuitBreaker::window`] (373957f) accessor-composition
26116        // pins on the peer required-scalar axes — same "the validate /
26117        // shape-gate predicate must route through the substrate-primitive
26118        // typed dispatch" discipline extended onto the peer
26119        // per-`RateLimit` required-`u32` composition axis.
26120        let mut spec = three_member_spec();
26121        spec.politicas = MeshPolicy {
26122            rate_limit: Some(RateLimit {
26123                rate: 0,
26124                window: Duration::from_secs(1),
26125            }),
26126            ..MeshPolicy::default()
26127        };
26128        assert!(
26129            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26130            "validate_politicas must reject rate == 0 with \
26131             PolicyRateLimitZero — the accessor and the validate gate \
26132             must route through the same substrate-primitive typed \
26133             dispatch on the :rate zero-floor arm",
26134        );
26135        spec.politicas = MeshPolicy {
26136            rate_limit: Some(RateLimit {
26137                rate: 1,
26138                window: Duration::from_secs(1),
26139            }),
26140            ..MeshPolicy::default()
26141        };
26142        assert!(
26143            spec.validate().is_ok(),
26144            "validate_politicas must accept rate == 1 (the lower \
26145             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
26146        );
26147    }
26148
26149    #[test]
26150    fn rate_limit_rate_projects_u32_by_copy() {
26151        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
26152        // `u32` is `Copy` and the accessor must return by value, not by
26153        // reference. Peer of the sibling per-`CircuitBreaker`
26154        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
26155        // peer required-scalar `:max-failures` axis, extended onto the
26156        // peer per-`RateLimit` required-`u32` copy-invariant shape —
26157        // the accessor's returned `u32` must outlive `&self` (multiple
26158        // calls must return equal values from a dropped-`&self` copy,
26159        // since the returned scalar carries no borrow), and calling the
26160        // accessor twice on the same RateLimit must yield the same
26161        // `u32` verbatim (idempotent, no side effects on `&self`).
26162        //
26163        // Pins against a future silent detour that returned `&u32`
26164        // (which would type-check but silently break every downstream
26165        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26166        // first parameter is `u32`, and `&u32` would fold to a detached
26167        // copy at the call site with a `*` deref the sibling accessors
26168        // don't need), an accidental `.rate.wrapping_add(0)` detour that
26169        // returned a fresh copy through an arithmetic no-op (breaking a
26170        // future `const fn` regression), or a one-arm-only accessor
26171        // that returned a saturating value on some sentinel input
26172        // (breaking the pass-through invariant the sibling required-
26173        // scalar accessors carry).
26174        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26175            let rl = RateLimit {
26176                rate,
26177                window: Duration::from_secs(1),
26178            };
26179            let first = rl.rate();
26180            let second = rl.rate();
26181            assert_eq!(
26182                first, second,
26183                "RateLimit::rate must be idempotent — two successive \
26184                 calls on the same &self must return the same u32",
26185            );
26186            assert_eq!(
26187                first, rate,
26188                "RateLimit::rate must return :politicas :rate-limit :rate \
26189                 verbatim by copy — got {first}, expected {rate}",
26190            );
26191        }
26192    }
26193
26194    #[test]
26195    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
26196        // The canonical per-`:politicas :rate-limit` `:window`
26197        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
26198        // pin: [`RateLimit::window`] must return the
26199        // `:politicas :rate-limit :window` typed `Duration` verbatim,
26200        // byte-equal to the raw field access across every
26201        // representative value in the accept-set — `Duration::from_secs(1)`
26202        // (the `"s"` canonical window, the lower row of
26203        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
26204        // [`AplicacaoSpec::validate_politicas`] gate accepts via
26205        // [`is_canonical_rate_limit_window`]),
26206        // `Duration::from_secs(60)` (the `"m"` canonical window, the
26207        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
26208        // window, the upper row), `Duration::ZERO` (a past-the-guard
26209        // sentinel that pins the accessor doesn't perform a silent
26210        // bounds-collapse into `Duration::from_secs(1)` on the zero
26211        // arm — validate rejects an off-set window through
26212        // `PolicyRateLimitWindowNotCanonical` but the accessor must
26213        // ship the raw slot verbatim so a validate-time gate
26214        // regression surfaces at the emit boundary rather than being
26215        // silently absorbed), `Duration::from_millis(500)` (a
26216        // sub-canonical past-the-guard sentinel that pins the accessor
26217        // doesn't silently normalize a non-canonical fractional
26218        // magnitude onto the nearest canonical row).
26219        //
26220        // Second sub-struct required-scalar accessor pin on the
26221        // `RateLimit` axis — sibling in shape to the just-landed
26222        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
26223        // accessor pin on the peer per-sub-struct required-axis,
26224        // extended onto the per-`RateLimit` required-`Duration` axis.
26225        // Pins against a future silent detour that re-derived the
26226        // refill period from a peer axis (an accidental
26227        // `Duration::from_secs(self.rate as u64)` collapse that read
26228        // the rate-limit token capacity as a refill-interval
26229        // duration), a `Duration::ZERO → Duration::from_secs(1)`
26230        // canonical-default projection (which would silently absorb
26231        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
26232        // accessor boundary), or a canonical-set-collapsing accessor
26233        // that clamped the return through [`rate_limit_window_unit`]
26234        // (the `AplicacaoSpec::validate` gate owns the canonical-set
26235        // membership; the accessor must ship the raw slot verbatim).
26236        for window in [
26237            Duration::from_secs(1),
26238            Duration::from_secs(60),
26239            Duration::from_secs(3600),
26240            Duration::ZERO,
26241            Duration::from_millis(500),
26242        ] {
26243            let rl = RateLimit { rate: 100, window };
26244            assert_eq!(
26245                rl.window(),
26246                window,
26247                "RateLimit::window must return :politicas :rate-limit :window \
26248                 verbatim (got {:?}, expected {window:?})",
26249                rl.window(),
26250            );
26251            assert_eq!(
26252                rl.window(),
26253                rl.window,
26254                "RateLimit::window must byte-equal the raw .window field \
26255                 access across every value in the Duration accept-set",
26256            );
26257        }
26258    }
26259
26260    #[test]
26261    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
26262        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26263        // `:rate-limit :window` canonical-set arm must key off
26264        // [`RateLimit::window`], not the raw `.window` field access.
26265        // Structurally: a `RateLimit { window: Duration::from_millis(500),
26266        // .. }` embedded in a `:politicas :rate-limit` slot must
26267        // surface the `PolicyRateLimitWindowNotCanonical` refusal
26268        // exactly (with the sub-canonical `Duration::from_millis(500)`
26269        // magnitude carried through verbatim), and a `RateLimit
26270        // { window: Duration::from_secs(1), .. }` (the lower row of
26271        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
26272        // The pair jointly pins the accessor + validate-gate
26273        // composition: any future silent detour that had the accessor
26274        // normalize the off-set window to the nearest canonical row
26275        // (a `.window().max(Duration::from_secs(1))` collapse, or a
26276        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
26277        // collapse) would silently absorb the
26278        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
26279        // boundary — including a drift in the error's `window` payload
26280        // (the emit-side diagnostic reader keys off the offending
26281        // magnitude verbatim, so a normalization at the accessor
26282        // boundary would silently pin the wrong magnitude in the
26283        // refusal). The composition pin catches that at caixa-core
26284        // build time.
26285        //
26286        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
26287        // (7f81a60) accessor-composition pin on the peer required-
26288        // scalar `:rate` axis — same "the validate / shape-gate
26289        // predicate must route through the substrate-primitive typed
26290        // dispatch, and the error payload must project through the
26291        // same accessor" discipline extended onto the peer
26292        // per-`RateLimit` required-`Duration` composition axis.
26293        let mut spec = three_member_spec();
26294        spec.politicas = MeshPolicy {
26295            rate_limit: Some(RateLimit {
26296                rate: 100,
26297                window: Duration::from_millis(500),
26298            }),
26299            ..MeshPolicy::default()
26300        };
26301        match spec.validate() {
26302            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
26303                assert_eq!(
26304                    window,
26305                    Duration::from_millis(500),
26306                    "PolicyRateLimitWindowNotCanonical must carry the \
26307                     offending :window magnitude verbatim through the \
26308                     accessor — got {window:?}, expected 500ms",
26309                );
26310            }
26311            other => panic!(
26312                "validate_politicas must reject non-canonical :window \
26313                 with PolicyRateLimitWindowNotCanonical — the accessor \
26314                 and the validate gate must route through the same \
26315                 substrate-primitive typed dispatch on the :window \
26316                 canonical-set arm; got {other:?}",
26317            ),
26318        }
26319        spec.politicas = MeshPolicy {
26320            rate_limit: Some(RateLimit {
26321                rate: 100,
26322                window: Duration::from_secs(1),
26323            }),
26324            ..MeshPolicy::default()
26325        };
26326        assert!(
26327            spec.validate().is_ok(),
26328            "validate_politicas must accept window == Duration::from_secs(1) \
26329             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
26330        );
26331    }
26332
26333    #[test]
26334    fn rate_limit_window_projects_duration_by_copy() {
26335        // The by-copy pin: [`RateLimit::window`] returns `Duration`
26336        // by copy — `Duration` is `Copy` and the accessor must return
26337        // by value, not by reference. Peer of the sibling per-`RateLimit`
26338        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
26339        // required-scalar `:rate` axis, extended onto the peer
26340        // per-`RateLimit` required-`Duration` copy-invariant shape —
26341        // the accessor's returned `Duration` must outlive `&self`
26342        // (multiple calls must return equal values from a
26343        // dropped-`&self` copy, since the returned scalar carries no
26344        // borrow), and calling the accessor twice on the same
26345        // RateLimit must yield the same `Duration` verbatim
26346        // (idempotent, no side effects on `&self`).
26347        //
26348        // Pins against a future silent detour that returned
26349        // `&Duration` (which would type-check but silently break every
26350        // downstream `Duration`-by-value consumer —
26351        // [`is_canonical_rate_limit_window`]'s first parameter is
26352        // `Duration`, and `&Duration` would fold to a detached copy at
26353        // the call site with a `*` deref the sibling accessors don't
26354        // need), an accidental `.window + Duration::ZERO` detour that
26355        // returned a fresh copy through an arithmetic no-op (breaking
26356        // a future `const fn` regression), or a one-arm-only accessor
26357        // that returned a canonical fallback on some sentinel input
26358        // (breaking the pass-through invariant the sibling required-
26359        // scalar accessors carry).
26360        for window in [
26361            Duration::from_secs(1),
26362            Duration::from_secs(60),
26363            Duration::from_secs(3600),
26364            Duration::ZERO,
26365            Duration::from_millis(500),
26366        ] {
26367            let rl = RateLimit { rate: 100, window };
26368            let first = rl.window();
26369            let second = rl.window();
26370            assert_eq!(
26371                first, second,
26372                "RateLimit::window must be idempotent — two successive \
26373                 calls on the same &self must return the same Duration",
26374            );
26375            assert_eq!(
26376                first, window,
26377                "RateLimit::window must return :politicas :rate-limit :window \
26378                 verbatim by copy — got {first:?}, expected {window:?}",
26379            );
26380        }
26381    }
26382
26383    #[test]
26384    fn placement_estrategia_default_pins_m3_canonical_value() {
26385        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
26386        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
26387        // active-active-across-every-named-cluster arm, the closest
26388        // canonical M3 production reference the substrate carries and
26389        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
26390        // for every un-`:placement`-declared Aplicacao. Pinning the arm
26391        // here surfaces a future rebrand of the M3-canonical
26392        // distribution default (a widening to `Sharded` once the
26393        // substrate discovers hash-keyed distribution as the more
26394        // common production shape, a tightening to `SingleNode` for
26395        // stateful Erlang/OTP distributed-app-takeover semantics
26396        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
26397        // operator pins through a future `:placement-overrides` slot)
26398        // as a deliberate test edit, not a silent contract migration.
26399        // Peer of the sibling M2 per-supervisor value pins
26400        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
26401        // /
26402        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
26403        // extended onto the M3 mesh-primitive-defining `:placement
26404        // :estrategia` axis.
26405        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
26406    }
26407
26408    #[test]
26409    fn placement_strategy_default_routes_through_lifted_default() {
26410        // Composition pin: the [`Default for PlacementStrategy`] impl's
26411        // return arm must route through the substrate-canonical
26412        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
26413        // a raw `Self::Replicated` arm. Prior to the lift the impl
26414        // carried an inline `Self::Replicated` arm with no compile-time
26415        // link back to the shared M3-canonical `Replicated` arm the
26416        // paired [`Default for Placement`] impl's struct-literal
26417        // `estrategia` field, the serde-side `#[serde(default)]` on
26418        // [`Placement::estrategia`] that resolves an author-omitted
26419        // wire-form `:placement :estrategia` scalar through the impl,
26420        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
26421        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
26422        // routes through [`Placement::default`] which routes through the
26423        // strategy default) all key off — so a future rebrand of the
26424        // M3-canonical distribution default would have had to be threaded
26425        // through the `Default` impl and the three peer routes in
26426        // lockstep or the four consumers would silently split. Byte-
26427        // parity against the lifted constant closes the split. Peer of
26428        // the sibling
26429        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
26430        // /
26431        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
26432        // composition pins on the M2 per-supervisor axes.
26433        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
26434    }
26435
26436    #[test]
26437    fn placement_default_estrategia_routes_through_lifted_default() {
26438        // Composition pin: the [`Default for Placement`] impl's
26439        // struct-literal `estrategia` field must route through the
26440        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
26441        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
26442        // impl that the sibling
26443        // `placement_strategy_default_routes_through_lifted_default` pin
26444        // already routes onto the constant). Structurally: every
26445        // `Placement::default()` call must yield an `estrategia` field
26446        // byte-equal to the lifted constant so the two paired defaults —
26447        // the [`Default for PlacementStrategy`] impl arm and the
26448        // struct-literal default arm here — cannot silently split on any
26449        // future M3-canonical distribution-default rebrand. Peer of the
26450        // sibling M2
26451        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
26452        // byte-parity pin on the [`Default for SupervisorSpec`]
26453        // struct-literal `estrategia` field extended onto the M3
26454        // mesh-primitive-defining slot family.
26455        assert_eq!(
26456            Placement::default().estrategia,
26457            PLACEMENT_ESTRATEGIA_DEFAULT,
26458        );
26459    }
26460
26461    #[test]
26462    fn placement_serde_default_estrategia_routes_through_lifted_default() {
26463        // Composition pin: the serde-side `#[serde(default)]` on
26464        // [`Placement::estrategia`] — the wire-format author-omitted
26465        // `:placement :estrategia` arm — must resolve onto the substrate-
26466        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
26467        // (via the [`Default for PlacementStrategy`] impl the sibling
26468        // `placement_strategy_default_routes_through_lifted_default` pin
26469        // already routes onto the constant). Structurally: a `Placement`
26470        // deserialized from a payload that omits the `estrategia` key
26471        // must yield an `estrategia` field byte-equal to the lifted
26472        // constant, so the wire-format author-omitted arm and the
26473        // [`PlacementStrategy::default`] impl arm cannot silently split
26474        // on any future M3-canonical distribution-default rebrand. Peer
26475        // of the sibling M2
26476        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
26477        // byte-parity pin on the wire-format author-omitted `:children
26478        // :restart` scalar extended onto the M3 mesh-primitive-defining
26479        // slot family.
26480        let omitted: Placement = serde_json::from_str("{}")
26481            .expect("Placement must deserialize with the estrategia key omitted");
26482        assert_eq!(
26483            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
26484            "an author-omitted :placement :estrategia slot must degrade onto \
26485             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
26486             {:?}, expected {:?})",
26487            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
26488        );
26489    }
26490}