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///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    matches!(WitShape::classify(wit), WitShape::Http)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    matches!(WitShape::classify(wit), WitShape::PubSub)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    matches!(WitShape::classify(wit), WitShape::Store)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    matches!(WitShape::classify(wit), WitShape::Capability)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361/// Closed 4-arm typed classification of a raw `:contratos :wit` value's
362/// WIT-shape membership — the single-dispatch typed source of truth for
363/// the four-arm partition the free-function classifier family
364/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
365/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) opens on the
366/// raw `&str` axis. Every peer free predicate now routes through
367/// [`Self::classify`] via a `matches!` arm-check, so the raw `&str →
368/// WIT-shape-arm` dispatch lives at one substrate primitive rather than
369/// four open-coded prefix probes plus a triplet negation.
370///
371/// # Compounding
372///
373/// The free predicates fan out to four independent bodies, three of
374/// which read one [`WIT_*_SHAPE_PREFIXES`] const each and one of which
375/// re-negates the trio. A future fifth WIT-shape arm (a hypothetical
376/// `wasi:sockets/*` / `tcp:*` transport-layer shape, an `oci:*`
377/// capability-import carrier, per the sibling [`wit_shape_matches`]
378/// docstring's trajectory bullet) previously required:
379///   1. one new [`WIT_*_SHAPE_PREFIXES`] const,
380///   2. one new `wit_shape_is_<name>` free predicate,
381///   3. an edit to [`wit_shape_is_capability`]'s negation to add the
382///      new arm — which a future author can silently forget, at which
383///      point every downstream capability-shape reader would
384///      misclassify the new arm as capability without a compile-time
385///      signal.
386///
387/// After this lift the third step becomes a compiler-checked
388/// exhaustiveness error: adding a fifth [`WitShape`] variant without
389/// growing [`Self::classify`]'s `match` fails at caixa-core build time
390/// (unhandled arm), and the sibling accessors ([`Self::as_str`], the
391/// [`std::fmt::Display`] and [`AsRef<str>`] impls, the
392/// [`gen_platform::IsVariant`]-derived per-arm predicates) refuse to
393/// compile until the new arm carries a body. The free predicate for
394/// the new arm is then a thin one-line `matches!` on the classifier's
395/// result, and [`wit_shape_is_capability`]'s definition stays a
396/// zero-line delta.
397///
398/// # Peers
399///
400/// Peer of the closed-set typed enums the caixa surface already
401/// carries on adjacent axes:
402/// - [`crate::CaixaKind`] on the top-level `:kind` axis
403/// - [`crate::dialeto::CaixaDialeto`] on the dialect-classification axis
404/// - [`PlacementStrategy`] on the `:placement :estrategia` axis
405/// - [`RateLimitUnit`] on the `:politicas :rate-limit :window` axis
406/// - [`crate::supervisor::RestartStrategy`] /
407///   [`crate::supervisor::RestartPolicy`] on the supervisor-strategy
408///   axes
409///
410/// Distinct from [`WitTarget`] on the same overall `:contratos` slot:
411/// [`WitTarget`] is the *post-validation* payload-carrying view (each
412/// arm carries the payload field its shape requires — an endpoint, a
413/// subject, a slot); [`WitShape`] is the *pre-validation* raw-`&str`
414/// classification (four unit arms — a witness of "which arm would the
415/// downstream validate consume this as?" without materializing the
416/// payload). Both surfaces carry an [`gen_platform::IsVariant`]-derived
417/// arm-predicate family and a `Capability` arm, so any downstream
418/// consumer that pairs a raw `&str` shape witness with a validated
419/// [`WitTarget`] view reads through matched per-arm predicates on both
420/// sides.
421///
422/// # Not a validator
423///
424/// Purely syntactic classification on the raw `:contratos :wit` prefix
425/// set — unlike [`WitContract::target`], which additionally rejects
426/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
427/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
428/// payload-shape mismatches. An empty or structurally malformed `wit`
429/// string classifies here as [`Self::Capability`] (the prefix set
430/// matches nothing), and the surrounding validate-side gate cascade is
431/// where the [`AplicacaoError::EmptyWit`] /
432/// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
433/// enum is the classifier, not the validator.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant)]
435pub enum WitShape {
436    /// HTTP-shaped WIT world — the raw `:contratos :wit` value starts
437    /// with any prefix in [`WIT_HTTP_SHAPE_PREFIXES`] (`wasi:http/`,
438    /// `http:`). Peer of [`WitTarget::Http`] on the paired
439    /// post-validation payload-carrying view.
440    Http,
441    /// Pub-sub-shaped WIT world — the raw `:contratos :wit` value
442    /// starts with any prefix in [`WIT_PUBSUB_SHAPE_PREFIXES`]
443    /// (`nats:`, `kafka:`). Peer of [`WitTarget::PubSub`] on the paired
444    /// post-validation payload-carrying view.
445    ///
446    /// The `IsVariant` derive would auto-name the predicate
447    /// `is_pub_sub` (`discriminant_to_snake("PubSub") == "pub_sub"`);
448    /// the explicit `#[is_variant(name = "pubsub")]` override keeps the
449    /// emitted method name byte-identical to the sibling
450    /// [`WitTarget::is_pubsub`] and [`WitContract::is_pubsub`]
451    /// predicates so all three arm-discriminator axes — raw-`&str`,
452    /// post-validation payload view, and pre-projection `WitContract`
453    /// surface — reach every downstream consumer through the same
454    /// `is_pubsub()` name.
455    #[is_variant(name = "pubsub")]
456    PubSub,
457    /// Key/value-store-shaped WIT world — the raw `:contratos :wit`
458    /// value starts with any prefix in [`WIT_STORE_SHAPE_PREFIXES`]
459    /// (`wasi:keyvalue/`, `kv:`). Peer of [`WitTarget::Store`] on the
460    /// paired post-validation payload-carrying view.
461    Store,
462    /// Payload-less capability edge — none of the three payload-arm
463    /// prefix sets match. Peer of [`WitTarget::Capability`] on the
464    /// paired post-validation view; the fallback arm that catches
465    /// everything the payload-arm probes miss, including the empty
466    /// string and every structurally-malformed `:wit` value the
467    /// surrounding [`WitContract::target`] validator rejects
468    /// downstream.
469    Capability,
470}
471
472impl WitShape {
473    /// Exhaustive iteration surface for every consumer that walks the
474    /// closed four-arm [`WitShape`] partition — a future
475    /// `feira app graph --by-wit-shape` histogram column, the future M4
476    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
477    /// admission-webhook rejection body naming the accepted-shape set,
478    /// any future round-trip fuzz harness that sweeps every arm's
479    /// canonical accept-set. A future variant addition (a hypothetical
480    /// `wasi:sockets/*` transport-layer shape, an `oci:*`
481    /// capability-import carrier per the sibling [`wit_shape_matches`]
482    /// docstring's trajectory bullet) extends this slice as one edit
483    /// and every consumer picks up the new entry through the shared
484    /// iteration; the compiler-checked exhaustiveness on the sibling
485    /// method `match` arms ([`Self::classify`] / [`Self::as_str`]) is
486    /// the build-time guarantee that no arm forgets to grow.
487    ///
488    /// Peer of the sibling closed-set typed enums'
489    /// [`crate::CaixaKind::ALL`] /
490    /// [`crate::dialeto::CaixaDialeto::ALL`] /
491    /// [`PlacementStrategy::ALL`] / [`RateLimitUnit::ALL`] /
492    /// [`crate::supervisor::RestartStrategy::ALL`] /
493    /// [`crate::supervisor::RestartPolicy::ALL`] /
494    /// [`crate::dep::DepList::ALL`] exhaustive-iteration surfaces —
495    /// the next closed-set typed enum on the caixa surface to converge
496    /// onto the same one-canonical-arm-list-per-enum discipline, and
497    /// the first WIT-shape-classification axis (as distinct from an
498    /// OTP-shape M2 slot or an M3 mesh slot) to reach it. Order matches
499    /// variant declaration order verbatim (`Http` → `PubSub` → `Store`
500    /// → `Capability`) so the slice is the canonical ordering every
501    /// listing / rendering consumer defers to, and matches the arm
502    /// preference [`Self::classify`] dispatches on.
503    pub const ALL: &'static [Self] = &[Self::Http, Self::PubSub, Self::Store, Self::Capability];
504
505    /// Classify a raw `:contratos :wit` value into its closed four-arm
506    /// WIT-shape partition — the single canonical dispatch every free
507    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
508    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] predicate
509    /// routes through via a `matches!` arm-check, and the single
510    /// canonical dispatch every future consumer that needs the full
511    /// four-arm answer (rather than a per-arm boolean) reaches for.
512    ///
513    /// Arm preference is `Http` → `PubSub` → `Store` → `Capability`,
514    /// matching the declaration order pinned in [`Self::ALL`]. Under
515    /// the disjointness pins immediately above the impl block
516    /// (`const _: () = assert!(!wit_shape_is_http("nats:events"))` and
517    /// peers), the preference order is unobservable — no `:wit` value
518    /// satisfies more than one payload-arm prefix set. If a future
519    /// prefix-set edit accidentally overlaps two arms (e.g. a `kv:`
520    /// prefix accidentally re-emitted under
521    /// [`WIT_HTTP_SHAPE_PREFIXES`]), the sibling `const _: () =
522    /// assert!(!wit_shape_is_http("kv:cache"))` pin trips at
523    /// caixa-core build time before the preference-order behavior
524    /// becomes observable at any consumer site.
525    ///
526    /// # Const-eval posture
527    ///
528    /// Declared `pub const fn` — routes through the peer `pub const
529    /// fn` [`wit_shape_matches`] combinator on each of the three
530    /// payload-arm prefix-set probes, so every substrate-side
531    /// `const`-context WIT-shape-arm-classifier consumer (any future
532    /// M4 admission-webhook `const fn` per-`:contratos :wit`
533    /// arm-resolver over a raw `&str`, any future `const fn`
534    /// per-`:contratos`-edge WIT-registry prefix-set overlay resolver
535    /// that fans on the classified arm at compile time) reaches
536    /// through the same typed dispatch on the substrate primitive at
537    /// const-eval time as at runtime. Pinned load-bearing by the
538    /// [`tests::wit_shape_classify_is_const_fn`] test's `const fn`
539    /// wrapper — any future accidental downgrade to non-`const` fails
540    /// with E0015 at the wrapper call site at caixa-core build time,
541    /// strictly stronger than a runtime `assert!`.
542    #[must_use]
543    pub const fn classify(wit: &str) -> Self {
544        if wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES) {
545            Self::Http
546        } else if wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES) {
547            Self::PubSub
548        } else if wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES) {
549            Self::Store
550        } else {
551            Self::Capability
552        }
553    }
554
555    /// Canonical short kebab byte-string every consumer that formats a
556    /// [`WitShape`] as census-facing text lands on — returns
557    /// `"http"` / `"pubsub"` / `"store"` / `"capability"`, the same
558    /// byte-strings the [`std::fmt::Display`] and [`AsRef<str>`] impls
559    /// route through and every future histogram-column /
560    /// audit-report / admission-rejection-body reader reads.
561    ///
562    /// Peer of the sibling closed-set typed enums'
563    /// [`crate::CaixaKind::as_str`] /
564    /// [`crate::dialeto::CaixaDialeto::as_str`] /
565    /// [`PlacementStrategy::as_str`] /
566    /// [`RateLimitUnit::as_suffix`] /
567    /// [`crate::supervisor::RestartStrategy::as_str`] /
568    /// [`crate::supervisor::RestartPolicy::as_str`] canonical-projection
569    /// accessors on the sibling closed-set typed-enum discriminator
570    /// axes.
571    #[must_use]
572    pub const fn as_str(self) -> &'static str {
573        match self {
574            Self::Http => "http",
575            Self::PubSub => "pubsub",
576            Self::Store => "store",
577            Self::Capability => "capability",
578        }
579    }
580
581    /// Reverse projection on the [`WitShape`] closed-set enum's
582    /// canonical-projection axis — parses a `"http"` / `"pubsub"` /
583    /// `"store"` / `"capability"` census-label byte-string back to the
584    /// typed enum, or returns [`None`] when `s` lies outside the four-
585    /// arm accept-set [`Self::as_str`] emits. The single `&str → Self`
586    /// projection every future re-entry point on the [`WitShape`]
587    /// census-label axis dispatches through (a future
588    /// `feira app graph --by-wit-shape=<http|pubsub|store|capability>`
589    /// CLI arg-parse that binds the wire byte-string into the typed
590    /// enum before dispatching to the per-arm histogram column, a
591    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
592    /// rejection body re-parsing a prior emission's per-arm audit-column
593    /// tag back to the typed enum for accepted-shape policy classification,
594    /// a `tracing::field::Value::Str`-arm structured-log re-loader binding
595    /// a prior [`std::fmt::Display`]-formatted [`WitShape`] output back to the
596    /// typed enum for cross-run shape-flavor histogram diff) would have
597    /// had to re-inline a four-arm `match s` cascade that expressed no
598    /// compile-time link back to the substrate primitive.
599    ///
600    /// Distinct axis from the peer [`Self::classify`] total classifier,
601    /// which takes the *raw* `:contratos :wit` identifier (`"wasi:http/proxy"`,
602    /// `"nats:events"`, `"wasi:keyvalue/store"`, everything else) and
603    /// returns the arm the payload-arm prefix-set dispatch resolves to —
604    /// a total function on the WIT-identifier axis. [`Self::from_wire`]
605    /// takes the *census-label* byte-string (`"http"` / `"pubsub"` /
606    /// `"store"` / `"capability"`, the paired output of [`Self::as_str`])
607    /// and returns the arm — a partial function on the closed four-string
608    /// census-label axis. The two axes carry different accept-sets by
609    /// design, not drift: [`Self::classify`] accepts every `&str` and
610    /// falls through to [`Self::Capability`] on the empty and every
611    /// structurally-malformed input; [`Self::from_wire`] accepts exactly
612    /// the four census labels [`Self::as_str`] emits and rejects
613    /// everything else (including every raw WIT identifier [`Self::classify`]
614    /// would classify — so a caller who accidentally routes a raw
615    /// `:contratos :wit` value through [`Self::from_wire`] instead of
616    /// [`Self::classify`] observes [`None`] rather than a plausibly-wrong
617    /// arm silently). The paired axis discipline mirrors the sibling
618    /// [`crate::CaixaKind::as_str`] / [`crate::CaixaKind::from_wire`]
619    /// pair on the top-level `:kind` axis.
620    ///
621    /// Same closed-set-reverse-projection discipline the sibling
622    /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
623    /// [`crate::dialeto::CaixaDialeto::from_wire`] (d0e65ea) /
624    /// [`crate::supervisor::RestartStrategy::from_wire`] (4eec29c) /
625    /// [`crate::supervisor::RestartPolicy::from_wire`] (dd32ccf) /
626    /// [`PlacementStrategy::from_wire`] (18c7342) /
627    /// [`crate::dep::DepList::from_wire`] (45ee563) /
628    /// [`crate::render::PathShapeViolation::from_wire`] (aebd9c6) /
629    /// `caixa_arch::invariants::InvariantKind::from_wire` (b9e4e61) /
630    /// `caixa_arch::report::ArchVerdict::from_wire` (6afe564) /
631    /// `caixa_lint::diagnostic::Severity::from_wire` (5afff0e) /
632    /// `caixa_lint::diagnostic::FixSafety::from_wire` (bd505a1) /
633    /// `caixa_theme::style::Semantic::from_wire` (e7bca7b) /
634    /// `caixa_provedor::ferrite::FerriteRuntime::from_wire` (1e4cc81)
635    /// typed enums carry on the peer wire-side `str → Self` axes —
636    /// extends the substrate-wide `(as_str, from_wire)` round-trip
637    /// family onto the first `:contratos :wit` raw-classification
638    /// axis to converge on the reverse-projection discipline, matching
639    /// the same two-way `str ↔ Self` round-trip every sibling closed-
640    /// set enum already carries. Method-named `from_wire` (not
641    /// `from_str`) to match the peer shapes verbatim and side-step a
642    /// `clippy::should_implement_trait` lint that a plain `from_str`
643    /// name would otherwise trigger without paired [`std::str::FromStr`]
644    /// impl scaffolding this axis does not carry today. Returns
645    /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
646    /// shapes: the caller picks the diagnostic form appropriate for its
647    /// use site (a future `feira app graph --by-wit-shape` CLI arg-parse
648    /// renders its own per-verb error message; a future admission-webhook
649    /// rejection body wraps the [`None`] outcome with the accepted-set
650    /// enumeration `WitShape::ALL.iter().map(WitShape::as_str)` for
651    /// operator diagnostics).
652    ///
653    /// Pinned load-bearing at the substrate-primitive level by
654    /// [`tests::wit_shape_from_wire_accepts_every_as_str_output`]
655    /// (round-trip witness against the peer [`Self::as_str`] axis) and
656    /// [`tests::wit_shape_from_wire_rejects_unknown_byte_strings`]
657    /// (rejection witness against silent accept-set widening,
658    /// including the raw `:contratos :wit` identifiers [`Self::classify`]
659    /// consumes on the sibling axis — so a caller who confuses the two
660    /// axes trips the pin at caixa-core build time rather than at a
661    /// downstream consumer's silent misclassification).
662    #[must_use]
663    pub fn from_wire(s: &str) -> Option<Self> {
664        match s {
665            "http" => Some(Self::Http),
666            "pubsub" => Some(Self::PubSub),
667            "store" => Some(Self::Store),
668            "capability" => Some(Self::Capability),
669            _ => None,
670        }
671    }
672}
673
674/// Route [`std::fmt::Display`] through [`WitShape::as_str`], so every
675/// consumer that formats a [`WitShape`] as user-facing text (future
676/// histogram column headers on `feira app graph --by-wit-shape`,
677/// future admission-webhook rejection bodies enumerating the accepted
678/// shape set, future audit-report per-arm column headers) lands on the
679/// same `"http"` / `"pubsub"` / `"store"` / `"capability"` byte-string
680/// the paired [`AsRef<str>`] impl also routes through. Same
681/// canonical-projection discipline the sibling
682/// [`std::fmt::Display for crate::CaixaKind`] /
683/// [`std::fmt::Display for crate::dialeto::CaixaDialeto`] /
684/// [`std::fmt::Display for PlacementStrategy`] /
685/// [`std::fmt::Display for RateLimitUnit`] impls carry — every text
686/// projection on this closed-set typed enum's dispatch surface reaches
687/// through one accessor.
688impl std::fmt::Display for WitShape {
689    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
690        f.write_str(self.as_str())
691    }
692}
693
694/// Route [`AsRef<str>`] through [`WitShape::as_str`], so every
695/// consumer that borrows a [`WitShape`] as `&str` (a future
696/// `HashMap<&str, _>` keyed lookup, a `&str`-bounded generic that
697/// takes a shape tag) lands on the same byte-string the sibling
698/// [`std::fmt::Display`] impl routes through. Peer of the sibling
699/// closed-set typed enums' [`AsRef<str>`] impls carrying the same
700/// discipline.
701impl AsRef<str> for WitShape {
702    fn as_ref(&self) -> &str {
703        self.as_str()
704    }
705}
706
707/// Standard-library trait-idiomatic reverse projection on the
708/// [`WitShape`] closed-set typed enum. Routes byte-for-byte through the
709/// paired substrate-primitive [`WitShape::from_wire`] `Option<Self>`
710/// accessor so `s.try_into::<WitShape>()` /
711/// `WitShape::try_from(&s)` reaches the same four-arm `"http"` /
712/// `"pubsub"` / `"store"` / `"capability"` census-label accept-set the
713/// sibling method-named resolver dispatches through and the sibling
714/// [`WitShape::as_str`] emits.
715///
716/// `type Error = ()` — matches the sibling [`WitShape::from_wire`]'s
717/// `Option<Self>` return-shape's deliberate deferral of error typing:
718/// the caller picks the diagnostic form appropriate for its use site (a
719/// future `feira app graph --by-wit-shape <arm>` CLI arg-parse composes
720/// its own per-verb "unknown wit-shape: <arg> — accepted: {…}" message
721/// enumerating [`WitShape::ALL`], a future M4
722/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook wraps
723/// `Err(())` with a per-CR structured refusal body enumerating the
724/// four-arm census set, a `Result::map_err` at the call site lifts the
725/// unit-error to a per-verb error type). Same shape the sibling
726/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
727/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
728/// (5b828ed), and [`crate::supervisor::RestartPolicy`] (6fdd0d9)
729/// `TryFrom<&str>` impls carry.
730///
731/// Chosen over [`std::str::FromStr`] to sidestep both
732/// `clippy::should_implement_trait` on the method-named
733/// [`WitShape::from_wire`] and the two-axis discipline the paired
734/// [`WitShape::classify`] total function keeps on the *raw* WIT
735/// identifier axis — the sibling
736/// `wit_shape_from_wire_and_classify_partition_the_axis` pin makes this
737/// two-axis split load-bearing, and a `FromStr` impl on the census-label
738/// axis would obscure which of the two axes a plain
739/// `s.parse::<WitShape>()` reaches. `TryFrom<&str>` keeps the trait-
740/// idiomatic reverse projection anchored to the same census-label axis
741/// [`WitShape::from_wire`] resolves through, leaving the raw
742/// [`WitShape::classify`] axis untouched.
743///
744/// The paired [`WitShape::from_wire`] resolver's accept-set is shared by
745/// construction, so any future arm addition (a hypothetical
746/// `wasi:sockets/*` transport-layer shape or `oci:*` capability-import
747/// carrier the sibling [`wit_shape_matches`] docstring names as a
748/// trajectory item) grows the trait-idiomatic axis by construction —
749/// one caixa-core edit on [`WitShape::from_wire`] extends both the
750/// method-named reverse projection every existing consumer keys off and
751/// the trait-idiomatic reverse projection this impl exposes, without a
752/// coordinated rewrite across every future `TryFrom<&str>`-bound
753/// consumer's arm-set.
754///
755/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
756/// projection family ([`crate::CaixaKind`] via 3c83606,
757/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
758/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
759/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9) onto the second
760/// M3-mesh-primitive-defining slot enum on the caixa surface — the
761/// `:contratos :wit` census-label closed set the caixa-mesh renderer
762/// keys off end-to-end for per-edge programs.yaml fan-out.
763///
764/// Pinned load-bearing by
765/// [`tests::wit_shape_try_from_str_routes_through_from_wire_accessor`]
766/// (byte-parity pin against [`WitShape::from_wire`] across the four-arm
767/// accept-set),
768/// [`tests::wit_shape_try_from_str_rejects_unknown_byte_strings`]
769/// (rejection witness against silent accept-set widening), and
770/// [`tests::wit_shape_try_from_str_and_from_wire_partition_the_accept_set`]
771/// (cross-axis partition pin locking trait and method-named projections
772/// to the same `Option<Self>` output on every input).
773impl TryFrom<&str> for WitShape {
774    type Error = ();
775
776    fn try_from(s: &str) -> Result<Self, Self::Error> {
777        Self::from_wire(s).ok_or(())
778    }
779}
780
781/// Standard-library trait-idiomatic forward projection on the
782/// [`WitShape`] closed-set typed enum. Routes byte-for-byte through the
783/// paired substrate-primitive [`WitShape::as_str`] `pub const fn`
784/// accessor so `<&'static str>::from(shape)` / `shape.into::<&'static
785/// str>()` reaches the same four-arm `"http"` / `"pubsub"` / `"store"`
786/// / `"capability"` census-label emit-set the sibling method-named
787/// accessor dispatches through and the sibling
788/// [`std::fmt::Display for WitShape`] / [`AsRef<str> for WitShape`]
789/// impls also route through.
790///
791/// Extends the substrate-wide closed-set-enum trait-idiomatic
792/// forward-projection family
793/// ([`crate::supervisor::RestartStrategy`] via 523157d,
794/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
795/// [`crate::CaixaKind`] via edb827b,
796/// [`crate::CaixaDialeto`] via c189a6f,
797/// [`PlacementStrategy`] via afa3562) onto the second
798/// M3-mesh-primitive-defining slot enum on the caixa surface — the
799/// `:contratos :wit` census-label closed set the caixa-mesh renderer
800/// keys off end-to-end for per-edge programs.yaml fan-out. Pairs with
801/// the sibling [`TryFrom<&str> for WitShape`] impl (5472902) to close
802/// the two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
803/// axis pair, mirroring the pre-existing method-named
804/// [`WitShape::as_str`] + [`WitShape::from_wire`] pair on the
805/// substrate-primitive axis pair.
806///
807/// The paired [`WitShape::as_str`] accessor's four-arm emit-set is the
808/// single source of truth — every future arm addition (a hypothetical
809/// `wasi:sockets/*` transport-layer shape or `oci:*` capability-import
810/// carrier the sibling [`wit_shape_matches`] docstring's trajectory
811/// bullet names) grows the trait-idiomatic forward axis by
812/// construction: one caixa-core edit on [`WitShape::as_str`] extends
813/// every one of the sibling forward-projection paths
814/// ([`std::fmt::Display`], [`AsRef<str>`], [`WitShape::as_str`]
815/// itself, and this [`From<Self> for &'static str`]) without a
816/// coordinated rewrite across every future `Into<&'static str>`-bound
817/// consumer's arm-set.
818///
819/// Pinned load-bearing by
820/// [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
821/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
822/// emit-set, plus a `const`-context materialization witness for the
823/// `&'static str` lifetime promise routed through the paired
824/// [`WitShape::as_str`] `pub const fn` accessor, plus a paired
825/// `.into()` shape assertion covering the blanket-derived
826/// `Into<&'static str>` shape) and
827/// [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
828/// (partition pin asserting `<&'static str as From<WitShape>>::from`
829/// and [`WitShape::as_str`] agree on every arm, plus a two-way direct
830/// round-trip witness through the paired trait-idiomatic
831/// [`TryFrom<&str>`] axis that closes the two-way `Self ↔ &'static
832/// str` round-trip on the trait-idiomatic axis pair — the emit-side
833/// [`WitShape::as_str`] and the parse-side [`WitShape::from_wire`]
834/// dispatch on the same four inline census-label byte-strings by
835/// construction, so round-tripping composes the two trait impls
836/// directly).
837impl From<WitShape> for &'static str {
838    fn from(shape: WitShape) -> &'static str {
839        shape.as_str()
840    }
841}
842
843/// Trait-idiomatic *forward* projection on [`WitShape`] from a *borrowed*
844/// input onto the `&'static str` axis — the borrowed-input companion to
845/// the paired owned-input [`From<WitShape> for &'static str`] impl
846/// immediately above. Routes byte-for-byte through the same substrate-
847/// primitive [`WitShape::as_str`] `pub const fn` accessor so every
848/// consumer that binds a `&WitShape` through the standard-library
849/// `.into()` / [`From<&Self> for &'static str`] axis (a
850/// `WitShape::ALL.iter().map(<&'static str>::from).collect::<Vec<_>>()`
851/// per-arm accept-set materializer — whose iterator over
852/// `&'static [WitShape]` yields `&WitShape`, not `WitShape`, so the
853/// owned-input [`From<WitShape>`] axis alone forces every call site through
854/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
855/// rather than the direct trait-idiomatic projection; a future generic
856/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column over
857/// the substrate-wide closed-set typed-enum family that walks the
858/// `iter().map(Into::into)` shape verbatim; the future M4
859/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection body
860/// that composes the accepted-`:contratos :wit` census-label enumeration
861/// from an iterated `WitShape::ALL.iter().map(|s| s.into())` pipe rather
862/// than a per-arm `match s { … }` cascade; a future
863/// `HashMap::<&'static str, WitShape>::from_iter(
864///   WitShape::ALL.iter().map(|s| (s.into(), *s)))`-style per-shape
865/// reverse-lookup table the sibling [`TryFrom<&str>`] impl cannot compose
866/// without this borrowed-input axis in place) reaches the same four-arm
867/// `"http"` / `"pubsub"` / `"store"` / `"capability"` census-label
868/// emit-set the paired owned-input [`From<WitShape> for &'static str`],
869/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
870/// [`WitShape::as_str`] surfaces already return.
871///
872/// Seventh peer on the substrate-wide trait-idiomatic *borrowed-input*
873/// forward-projection family opened on [`crate::dep::DepList`]
874/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
875/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
876/// [`crate::supervisor::RestartStrategy`] (e941836) and
877/// [`crate::supervisor::RestartPolicy`] (842c7f3), and the first M3
878/// mesh-primitive slot enum [`PlacementStrategy`] (4d941d8). Rust's
879/// `From` trait does not auto-derive the `From<&Self>` sibling from a
880/// `From<Self>` impl (the blanket `impl<T, U> From<&T> for U where T:
881/// Copy, U: From<T>` does not exist in `core`), so every closed-set
882/// typed enum that carries the owned-input axis but not the borrowed-
883/// input axis forces every borrowed-input call site through a
884/// `.copied()` / `<&'static str>::from(*shape)` / `shape.as_str()`
885/// detour whose type bounds have no compile-time link to the substrate
886/// primitive. [`WitShape`] is the *second* M3-mesh-primitive-defining
887/// closed-set typed enum to converge onto this borrowed-input campaign
888/// — the [`PlacementStrategy`] first-mover (4d941d8) opened the M3-slot
889/// arm, and [`WitShape`]'s `:contratos :wit` census-label axis (the
890/// caixa-mesh renderer's per-edge programs.yaml fan-out key) closes the
891/// next M3 slot ahead of the sibling [`RateLimitUnit`] `:politicas
892/// :rate-limit` canonical-suffix axis whose owned-input forward-
893/// projection axis (7fdfbf4) awaits the paired borrowed-input closure.
894///
895/// Same three-path convergence discipline as the paired owned-input
896/// impl (this borrowed-input axis, the paired owned-input
897/// [`From<WitShape> for &'static str`], and [`WitShape::as_str`] all
898/// route through the same four-arm inline census-label byte-strings), so
899/// a future variant rename or per-arm serde-attribute drift reaches
900/// every one of the six sibling forward-projection paths
901/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
902/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
903/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
904/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core edit.
905///
906/// The [`WitShape::as_str`] emit and [`WitShape::from_wire`] parse share
907/// the same census-label vocabulary by construction — the same four
908/// inline census-label byte-strings dispatch on both halves — so the
909/// borrowed-input forward axis and the reverse axis compose directly
910/// without the intermediate wire-vocab hop the peer [`crate::CaixaKind`]
911/// axis pair requires. The round-trip witness pin below locks this
912/// direct composition on the M3 slot enum's trait-idiomatic axis pair.
913///
914/// Pinned load-bearing by
915/// [`tests::wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor`]
916/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
917/// emit-set via a borrowed input, plus a `const`-context materialization
918/// witness for the `&'static str` lifetime promise, plus a blanket
919/// `.into()` shape) and
920/// [`tests::wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
921/// (cross-axis partition pin against the paired owned-input
922/// [`From<WitShape> for &'static str`] impl, plus a
923/// `.iter().map(Into::into)` pipe witness over [`WitShape::ALL`], plus a
924/// direct round-trip witness through [`TryFrom<&str>`] that closes the
925/// two-way `&Self → &'static str → Self` round-trip on the M3 slot
926/// enum's trait-idiomatic axis pair without the wire-vocab intermediate
927/// the peer [`crate::CaixaKind`] axis pair requires).
928impl From<&WitShape> for &'static str {
929    fn from(shape: &WitShape) -> &'static str {
930        shape.as_str()
931    }
932}
933
934impl WitContract {
935    /// Substrate-canonical per-`:contratos` caller-Servico scalar
936    /// accessor every consumer that reads the edge's source endpoint
937    /// keys off — returns the author-declared `:contratos :de`
938    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
939    /// own [`String`] storage.
940    ///
941    /// The `:contratos :de` slot names the caller-side member Servico
942    /// on a typed inter-Servico edge (validated by
943    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
944    /// Aplicacao declares — a stray `:de` that doesn't name a member is
945    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
946    /// caller-attachment miss at cluster-apply time). Peer of the
947    /// sibling [`WitContract::destination`] accessor on the same
948    /// per-`:contratos` entry — the pair `( source(), destination() )`
949    /// jointly names the typed edge every renderer that fans on the
950    /// caller-callee identity keys off (the
951    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
952    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
953    /// map, the per-edge dedup key, the per-edge membership-lookup
954    /// diagnostic).
955    ///
956    /// Prior to this lift the `.de` byte-string was accessed inline at
957    /// four caixa-core sites (the two validate-side membership lookups
958    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
959    /// tuple's caller-arm at
960    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
961    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
962    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
963    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
964    /// — five open-coded `.de.as_str()` field-accesses that expressed
965    /// no compile-time link back to the typed slot. A future extension
966    /// of the `:contratos :de` axis to a richer author surface (a
967    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
968    /// canary flow, a per-cluster caller-alias table the operator pins
969    /// through a future `:placement`-scoped slot, the M4
970    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
971    /// admission-webhook that promotes the scalar to a caller-set
972    /// projection) would have had to be threaded through every
973    /// open-coded copy in lockstep or one consumer would silently
974    /// disagree with the peers on which caller Servico a given edge
975    /// resolves to. Lifting the resolution rule to a typed method on
976    /// the substrate primitive means every downstream caller-facing
977    /// consumer reaches for one typed dispatch — the resolver's
978    /// accept-set migrates as a unit on any future axis addition.
979    ///
980    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
981    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
982    /// axis — same "one typed dispatch on the substrate primitive,
983    /// thin projections at each consumer" discipline extended onto the
984    /// per-`:contratos` caller-Servico byte-string axis.
985    ///
986    /// Declared `pub const fn` — the body composes exclusively through
987    /// the `pub const fn` [`String::as_str`] projection (const-stable
988    /// since Rust 1.87, well within the workspace MSRV), so every
989    /// downstream `const`-context consumer of the per-`:contratos`
990    /// caller-Servico byte-string reaches through the same substrate-
991    /// primitive dispatch at const-eval time as at runtime. Peer of
992    /// the sibling `pub const fn` [`Self::destination`] /
993    /// [`Self::world_ref`] scalar accessors on the same
994    /// per-`:contratos` byte-string trio (the family closure the
995    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
996    /// locks load-bearing), and mirror on the method-surface of the
997    /// sibling free-function [`wit_shape_matches`] +
998    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
999    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
1000    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
1001    /// dispatch family.
1002    #[must_use]
1003    pub const fn source(&self) -> &str {
1004        self.de.as_str()
1005    }
1006
1007    /// Substrate-canonical per-`:contratos` callee-Servico scalar
1008    /// accessor every consumer that reads the edge's destination
1009    /// endpoint keys off — returns the author-declared
1010    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
1011    /// from the typed slot's own [`String`] storage.
1012    ///
1013    /// The `:contratos :para` slot names the callee-side member Servico
1014    /// on a typed inter-Servico edge (validated by
1015    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
1016    /// Aplicacao declares — a stray `:para` that doesn't name a member
1017    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
1018    /// callee-attachment miss at cluster-apply time). Callee-side twin
1019    /// of the sibling [`WitContract::source`] accessor — the pair
1020    /// jointly names the typed edge every renderer that fans on the
1021    /// caller-callee identity keys off, and this accessor is also the
1022    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
1023    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
1024    /// composes with `destination()` at every emit site that projects a
1025    /// per-edge destination Servico's L4 listener port.
1026    ///
1027    /// Prior to this lift the `.para` byte-string was accessed inline
1028    /// at five sites — four caixa-core (the validate-side membership
1029    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
1030    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
1031    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
1032    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
1033    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
1034    /// — with no compile-time link back to the typed slot. A future
1035    /// extension of the `:contratos :para` axis to a richer author
1036    /// surface (a multi-callee weighted-fan-out overlay for canary /
1037    /// blue-green routing on typed edges, a per-cluster callee-alias
1038    /// table the operator pins through a future `:placement`-scoped
1039    /// slot, the M4 CR materializer's per-CR admission-webhook that
1040    /// promotes the scalar to a callee-set projection) would have had
1041    /// to be threaded through every open-coded copy in lockstep or one
1042    /// consumer would silently disagree on which callee Servico a given
1043    /// edge resolves to (a per-CNP `endpointSelector` that names a
1044    /// different destination than its L4 port resolver reads for, a
1045    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
1046    /// as distinct while the adjacency map collapses them, or vice
1047    /// versa). Lifting to a typed method on the substrate primitive
1048    /// means every downstream callee-facing consumer reaches for one
1049    /// typed dispatch.
1050    ///
1051    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
1052    /// (6db982c) accessor — both name the "destination-Servico
1053    /// byte-string" concept on their respective mesh-slot atoms (per-
1054    /// ingress apex vs. per-typed-edge callee), and both extend the
1055    /// substrate-primitive-owns-the-resolver discipline onto the
1056    /// per-slot destination-Servico scalar axis. Composes with
1057    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
1058    /// emit-side per-edge L4 port reader — the composition
1059    /// `spec.port_for_destination(c.destination())` pins the CNP per-
1060    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
1061    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
1062    /// `spec.port_for_destination(entrada.destination())`.
1063    ///
1064    /// Declared `pub const fn` — sibling in `const`-eval posture to the
1065    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
1066    /// per-`:contratos` byte-string scalar accessors, all three
1067    /// projecting through the `pub const fn` [`String::as_str`]
1068    /// (const-stable since Rust 1.87). See [`Self::source`] for the
1069    /// family-closure rationale.
1070    #[must_use]
1071    pub const fn destination(&self) -> &str {
1072        self.para.as_str()
1073    }
1074
1075    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
1076    /// accessor every consumer that reads the edge's WIT world
1077    /// discriminator keys off — returns the author-declared
1078    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
1079    /// the typed slot's own [`String`] storage.
1080    ///
1081    /// The `:contratos :wit` slot names the WIT world the typed edge
1082    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
1083    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
1084    /// be a well-shaped WIT world reference via
1085    /// [`crate::render::is_wit_world_ref`] and by
1086    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
1087    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
1088    /// [`WitContract::source`] / [`WitContract::destination`] accessors
1089    /// on the same per-`:contratos` entry — the triple
1090    /// `( source(), destination(), world_ref() )` jointly names the
1091    /// typed edge every renderer that fans on the caller-callee-shape
1092    /// identity keys off (the per-edge dedup key at
1093    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
1094    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
1095    /// [`caixa_mesh::cilium_network_policies`], the
1096    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
1097    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
1098    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
1099    ///
1100    /// Prior to this lift the `.wit` byte-string was accessed inline at
1101    /// five sites — three caixa-core (the `WitContract::is_*` shape-
1102    /// dispatch predicates' `&self.wit` arg, the validate-side empty
1103    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
1104    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
1105    /// printer's `{}` format-slot at `c.wit`) — five open-coded
1106    /// `.wit` field-accesses that expressed no compile-time link back to
1107    /// the typed slot. A future extension of the `:contratos :wit` axis
1108    /// to a richer author surface (an M4 promotion from `String` to a
1109    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
1110    /// lisp per this struct's own `:wit` field docstring, a per-cluster
1111    /// WIT-alias table the operator pins through a future
1112    /// `:placement`-scoped slot, a canonicalization pass that lowercases
1113    /// `wasi:*` prefixes) would have had to be threaded through every
1114    /// open-coded copy in lockstep or one consumer would silently
1115    /// disagree with the peers on which WIT shape a given edge resolves
1116    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
1117    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
1118    /// empty-check that missed a whitespace-only string a peer accessor
1119    /// stripped, or vice versa). Lifting to a typed method on the
1120    /// substrate primitive means every downstream WIT-shape-facing
1121    /// consumer reaches for one typed dispatch — the resolver's
1122    /// accept-set migrates as a unit on any future axis addition.
1123    ///
1124    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
1125    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
1126    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
1127    /// 6db982c), per-`:membros` [`Membro::nome`] /
1128    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
1129    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
1130    /// on the substrate primitive, thin projections at each consumer"
1131    /// discipline extended onto the last unlifted per-`:contratos`
1132    /// scalar (the WIT-world-reference arm).
1133    ///
1134    /// [fag]: caixa-feira/src/cmd/app.rs
1135    ///
1136    /// Declared `pub const fn` — sibling in `const`-eval posture to the
1137    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
1138    /// per-`:contratos` byte-string scalar accessors on the trio, and
1139    /// the load-bearing enabler for the paired `pub const fn`
1140    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1141    /// [`Self::is_capability`] WIT-shape-predicate family (each
1142    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
1143    /// the `const`-eval posture by construction once this accessor
1144    /// carries it). See [`Self::source`] for the family-closure
1145    /// rationale and the paired
1146    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1147    /// for the load-bearing witness.
1148    #[must_use]
1149    pub const fn world_ref(&self) -> &str {
1150        self.wit.as_str()
1151    }
1152
1153    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
1154    /// payload-target scalar accessor every consumer that reads the
1155    /// edge's L7 HTTP request path payload keys off — returns the
1156    /// author-declared `:contratos :endpoint` byte-string verbatim as
1157    /// an `Option<&str>`, borrowed from the typed slot's own
1158    /// `Option<String>` storage; `None` when the slot is absent (the
1159    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
1160    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
1161    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1162    /// [`WitTarget::Capability`] edge carries none of the three).
1163    ///
1164    /// The `:contratos :endpoint` slot carries the HTTP request path
1165    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
1166    /// — same shape required of `:entrada :paths`, gated by the shared
1167    /// [`crate::render::is_gateway_api_http_path`] predicate) that
1168    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
1169    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
1170    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
1171    /// downstream consumer that reads the payload keys off this scalar
1172    /// (the [`WitContract::target`] Http-arm payload extraction that
1173    /// materializes [`WitTarget::Http { endpoint }`] under the paired
1174    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
1175    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1176    /// key's endpoint arm that pins the payload as part of the six-tuple
1177    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
1178    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
1179    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1180    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
1181    /// emission path that lands the payload verbatim as a Cilium L7
1182    /// `path:` rule).
1183    ///
1184    /// Prior to this lift the `.endpoint` field was accessed inline at
1185    /// two production sites in `caixa-core/src/aplicacao.rs` — the
1186    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
1187    /// self.endpoint.as_deref();` binding at the top of the method, and
1188    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1189    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
1190    /// field-accesses that expressed no compile-time link back to the
1191    /// typed slot. A future extension of the `:contratos :endpoint`
1192    /// axis to a richer author surface (an M4 promotion from
1193    /// `Option<String>` to a typed HTTP path-template enum once the
1194    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
1195    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
1196    /// alias table the operator pins through a future `:placement`-
1197    /// scoped slot, a canonicalization pass that percent-encodes non-
1198    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
1199    /// materializer applies per-tenant) would have had to be threaded
1200    /// through both open-coded copies in lockstep or the two consumers
1201    /// would silently disagree on which HTTP path a given edge resolves
1202    /// to — the [`WitContract::target`] payload-extraction reading
1203    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
1204    /// the operator-resolved `"/tenant-a/lookup"` would silently split
1205    /// the [`WitTarget::Http`]-arm rendered payload from the actual
1206    /// dedup-key uniqueness axis, a two-consumer split at the validator
1207    /// far from the source `caixa.lisp` with no field naming the
1208    /// payload-drift root cause. Lifting the resolution rule to a typed
1209    /// method on the substrate primitive means every downstream
1210    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
1211    /// L7-payload surface reaches for exactly one typed dispatch — the
1212    /// resolver's accept-set migrates as a unit on any future axis
1213    /// addition.
1214    ///
1215    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
1216    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
1217    /// accessors on the M3 mesh-slot family — same "one typed dispatch
1218    /// on the substrate primitive, thin projections at each consumer"
1219    /// discipline extended onto the per-`:contratos` HTTP-shaped
1220    /// payload-carrier `Option<String>` optional-scalar axis. First
1221    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
1222    /// atom — opens the "optional per-slot payload-carrier scalar"
1223    /// projection pattern the sibling per-`:contratos` `:subject` /
1224    /// `:slot` future lifts fold on, matching the closed
1225    /// per-`:contratos` scalar-value accessor family
1226    /// ([`WitContract::source`] / [`WitContract::destination`] /
1227    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
1228    /// scalar `String` axes. Named `endpoint()` to match the storage
1229    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
1230    /// author-facing label const; the accessor's identity name maps
1231    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1232    /// docstring already carries.
1233    #[must_use]
1234    pub const fn endpoint(&self) -> Option<&str> {
1235        match &self.endpoint {
1236            Some(s) => Some(s.as_str()),
1237            None => None,
1238        }
1239    }
1240
1241    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
1242    /// payload-target scalar accessor every consumer that reads the
1243    /// edge's NATS / Kafka publish subject payload keys off — returns
1244    /// the author-declared `:contratos :subject` byte-string verbatim
1245    /// as an `Option<&str>`, borrowed from the typed slot's own
1246    /// `Option<String>` storage; `None` when the slot is absent (the
1247    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
1248    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
1249    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1250    /// [`WitTarget::Capability`] edge carries none of the three).
1251    ///
1252    /// The `:contratos :subject` slot carries the NATS / Kafka publish
1253    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
1254    /// per-edge target selector — `orders.paid`, `events.>`, whatever
1255    /// subject namespace the author names on the pub-sub edge) that
1256    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
1257    /// arm's `subject: &'a str` payload when the edge's `:wit` world
1258    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
1259    /// downstream consumer that reads the payload keys off this scalar
1260    /// (the [`WitContract::target`] PubSub-arm payload extraction that
1261    /// materializes [`WitTarget::PubSub { subject }`] under the paired
1262    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
1263    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1264    /// key's subject arm that pins the payload as part of the six-tuple
1265    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
1266    /// future M4 per-edge WIT registry resolver's pub-sub-arm
1267    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1268    /// materializer's per-edge NATS admission webhook, the future
1269    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1270    /// as a NATS subject the operator pins per-CR).
1271    ///
1272    /// Prior to this lift the `.subject` field was accessed inline at
1273    /// two production sites in `caixa-core/src/aplicacao.rs` — the
1274    /// [`WitContract::target`] payload-shape dispatch's `let subject =
1275    /// self.subject.as_deref();` binding at the top of the method, and
1276    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1277    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
1278    /// field-accesses that expressed no compile-time link back to the
1279    /// typed slot. A future extension of the `:contratos :subject` axis
1280    /// to a richer author surface (an M4 promotion from `Option<String>`
1281    /// to a typed NATS-subject-template enum once the WIT registry
1282    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
1283    /// struct's own `:wit` field docstring, a per-cluster subject-alias
1284    /// table the operator pins through a future `:placement`-scoped
1285    /// slot, a canonicalization pass that lowercases / dedupes wildcard
1286    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
1287    /// applies per-tenant) would have had to be threaded through both
1288    /// open-coded copies in lockstep or the two consumers would silently
1289    /// disagree on which NATS subject a given edge resolves to — the
1290    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
1291    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
1292    /// resolved `"tenant-a.orders.paid"` would silently split the
1293    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
1294    /// key uniqueness axis, a two-consumer split at the validator far
1295    /// from the source `caixa.lisp` with no field naming the payload-
1296    /// drift root cause. Lifting the resolution rule to a typed method
1297    /// on the substrate primitive means every downstream pub-sub-payload-
1298    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
1299    /// surface reaches for exactly one typed dispatch — the resolver's
1300    /// accept-set migrates as a unit on any future axis addition.
1301    ///
1302    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1303    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
1304    /// carrier axis — second `Option<&str>`-return accessor on the
1305    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
1306    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
1307    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
1308    /// key/value-store arm as the last unlifted per-`:contratos`
1309    /// `Option<String>` axis. Named `subject()` to match the storage
1310    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
1311    /// author-facing label const; the accessor's identity name maps
1312    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1313    /// docstring already carries.
1314    #[must_use]
1315    pub const fn subject(&self) -> Option<&str> {
1316        match &self.subject {
1317            Some(s) => Some(s.as_str()),
1318            None => None,
1319        }
1320    }
1321
1322    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
1323    /// shaped payload-target scalar accessor every consumer that reads
1324    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
1325    /// off — returns the author-declared `:contratos :slot` byte-string
1326    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
1327    /// own `Option<String>` storage; `None` when the slot is absent
1328    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
1329    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
1330    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
1331    /// [`WitTarget::Capability`] edge carries none of the three).
1332    ///
1333    /// The `:contratos :slot` slot carries the key/value store
1334    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
1335    /// arm's per-edge target selector — `carts/{cart_id}`,
1336    /// `sessions/{tenant}/{sid}`, whatever key-template the author
1337    /// names on the store edge) that [`WitContract::target`] projects
1338    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
1339    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
1340    /// accept-set. Every downstream consumer that reads the payload
1341    /// keys off this scalar (the [`WitContract::target`] Store-arm
1342    /// payload extraction that materializes [`WitTarget::Store { slot }`]
1343    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
1344    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1345    /// key's store arm that pins the payload as part of the six-tuple
1346    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
1347    /// the future M4 per-edge WIT registry resolver's store-arm
1348    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1349    /// materializer's per-edge key/value admission webhook, the future
1350    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1351    /// as a key-template the operator pins per-CR).
1352    ///
1353    /// Prior to this lift the `.slot` field was accessed inline at two
1354    /// production sites in `caixa-core/src/aplicacao.rs` — the
1355    /// [`WitContract::target`] payload-shape dispatch's `let slot =
1356    /// self.slot.as_deref();` binding at the top of the method, and
1357    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1358    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
1359    /// field-accesses that expressed no compile-time link back to the
1360    /// typed slot. A future extension of the `:contratos :slot` axis
1361    /// to a richer author surface (an M4 promotion from `Option<String>`
1362    /// to a typed key-template enum once the WIT registry stabilizes
1363    /// key-template parameter shapes in tatara-lisp per this struct's
1364    /// own `:wit` field docstring, a per-cluster slot-alias table the
1365    /// operator pins through a future `:placement`-scoped slot, a
1366    /// canonicalization pass that lowercases the bucket prefix, a
1367    /// per-CR fully-qualified rewrite the M4 CR materializer applies
1368    /// per-tenant) would have had to be threaded through both
1369    /// open-coded copies in lockstep or the two consumers would
1370    /// silently disagree on which key-template a given edge resolves
1371    /// to — the [`WitContract::target`] payload-extraction reading
1372    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
1373    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
1374    /// would silently split the [`WitTarget::Store`]-arm rendered
1375    /// payload from the actual dedup-key uniqueness axis, a
1376    /// two-consumer split at the validator far from the source
1377    /// `caixa.lisp` with no field naming the payload-drift root cause.
1378    /// Lifting the resolution rule to a typed method on the substrate
1379    /// primitive means every downstream store-payload-facing consumer
1380    /// of the Aplicacao's per-`:contratos` payload surface reaches for
1381    /// exactly one typed dispatch — the resolver's accept-set migrates
1382    /// as a unit on any future axis addition.
1383    ///
1384    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1385    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
1386    /// accessors on the M3 mesh-slot payload-carrier axis — third and
1387    /// final `Option<&str>`-return accessor on the per-`:contratos`
1388    /// mesh-slot atom, closes the last unlifted per-`:contratos`
1389    /// `Option<String>` axis and completes the "optional per-slot
1390    /// payload-carrier scalar" projection pattern the peer HTTP /
1391    /// pub-sub arms established across the three payload-shape
1392    /// dispatch arms. Named `slot()` to match the storage field's
1393    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
1394    /// author-facing label const; the accessor's identity name maps
1395    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1396    /// docstring already carries.
1397    #[must_use]
1398    pub const fn slot(&self) -> Option<&str> {
1399        match &self.slot {
1400            Some(s) => Some(s.as_str()),
1401            None => None,
1402        }
1403    }
1404
1405    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
1406    /// caller-callee-pair accessor every consumer that constructs an
1407    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
1408    /// caller-callee pair keys off — returns the author-declared
1409    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
1410    /// owned `(String, String)` tuple, projected through the lifted
1411    /// [`WitContract::source`] / [`WitContract::destination`] scalar
1412    /// accessors so any future rebrand on the caller-arm / callee-arm
1413    /// projection axis (an M4 per-cluster caller-alias table the
1414    /// operator pins through a future `:placement`-scoped slot, a
1415    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
1416    /// a per-`:membros` alias overlay from the future `:membros
1417    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1418    /// acknowledges) reaches every diagnostic-construction site by
1419    /// construction.
1420    ///
1421    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
1422    /// owned form" primitive every per-`:contratos` diagnostic variant on
1423    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
1424    /// nine variants [`AplicacaoError::EmptyWit`],
1425    /// [`AplicacaoError::ContratoEndpointEmpty`],
1426    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
1427    /// [`AplicacaoError::ContratoEndpointInvalid`],
1428    /// [`AplicacaoError::ContratoSubjectEmpty`],
1429    /// [`AplicacaoError::ContratoSubjectInvalid`],
1430    /// [`AplicacaoError::ContratoSlotEmpty`],
1431    /// [`AplicacaoError::ContratoSlotInvalid`], and
1432    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
1433    /// para: String` field pair the constructor site reads verbatim off
1434    /// the [`WitContract`] the diagnostic points at, so a diagnostic
1435    /// whose `de:` and `para:` labels silently drift off the source
1436    /// caller/callee — a per-cluster caller-alias rewrite that landed on
1437    /// one variant's inline `de: c.de.clone()` field access but not on
1438    /// its sibling variant's, an accidental swap of the `de:` and `para:`
1439    /// arms in a copy-paste of the constructor block — would emit a
1440    /// build-time error whose "which caixa is at fault" question the
1441    /// operator answers wrongly, far from the source `caixa.lisp`.
1442    ///
1443    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
1444    /// pair was inlined at seven [`WitContract::target`] error-
1445    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
1446    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
1447    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
1448    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
1449    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
1450    /// the [`AplicacaoError::ContratoSlotEmpty`] /
1451    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
1452    /// two [`AplicacaoSpec::validate`] error-construction sites (the
1453    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
1454    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
1455    /// insert-first-seen closure) — nine open-coded `.de.clone() +
1456    /// .para.clone()` pairs that expressed no compile-time contract that
1457    /// the caller-arm and callee-arm arms of the same diagnostic
1458    /// construction reach for the same [`WitContract`] instance or that
1459    /// the `de:` and `para:` label pair binds to the fields the author
1460    /// declared. Any future rebrand on the axis — an M4 per-cluster
1461    /// caller/callee-alias rewrite the operator pins through a future
1462    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1463    /// per-CR fully-qualified namespace prefix the M4
1464    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1465    /// per-tenant, a canonicalization pass that lowercases the caller +
1466    /// callee identifiers post-parse — would have had to be threaded
1467    /// through every open-coded copy in lockstep or one variant's
1468    /// diagnostic would silently name a different caller/callee pair
1469    /// than its peer, silently degrading the "which caixa is at fault"
1470    /// self-locating signal every operator-facing typed diagnostic
1471    /// exists to carry. Lifting the pair to a typed method on the
1472    /// substrate primitive means every downstream diagnostic-construction
1473    /// site reaches for exactly one typed dispatch — the resolver's
1474    /// projection migrates as a unit on any future axis addition.
1475    ///
1476    /// Peer of the sibling per-`:contratos` scalar accessor family
1477    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
1478    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
1479    /// scalar-value axes — first composite-projection accessor on the
1480    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
1481    /// form `.clone()` field-accesses that pair the sibling
1482    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
1483    /// one typed dispatch. Named `edge_pair()` to reflect the identity
1484    /// name of the projected tuple (the typed-edge caller-callee pair,
1485    /// distinct from the sibling triple-projection
1486    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
1487    /// closure in [`WitContract::target`] + the paired
1488    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
1489    /// site's `(de, para, wit)` triple onto one typed dispatch).
1490    #[must_use]
1491    pub fn edge_pair(&self) -> (String, String) {
1492        (self.source().to_string(), self.destination().to_string())
1493    }
1494
1495    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
1496    /// :wit)` triple every per-edge diagnostic constructor that names
1497    /// all three axes threads verbatim into its `de:` / `para:` /
1498    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
1499    /// / missing-target / invalid-wit / capability-with-payload arms
1500    /// (eight sites all shape `let (de, para, wit) = edge();
1501    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
1502    /// accessor landed) and the sibling
1503    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
1504    /// constructor (which paired `edge_pair()` for the `(de, para)`
1505    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
1506    /// typed-dispatch + raw-field-access shape the sibling accessor
1507    /// family already flagged as a drift risk). Nine total call sites
1508    /// collapse onto this helper.
1509    ///
1510    /// Lifted with the same one-source-of-truth discipline
1511    /// [`WitContract::edge_pair`] carries on the paired
1512    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
1513    /// arms compose through the lifted [`WitContract::source`] /
1514    /// [`WitContract::destination`] / [`WitContract::world_ref`]
1515    /// scalar accessors byte-for-byte (pinned by the paired
1516    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
1517    /// composition-pin), so any future rebrand on the per-`:contratos`
1518    /// caller / callee / world-ref axis (an M4 per-cluster
1519    /// caller/callee-alias rewrite the operator pins through a future
1520    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1521    /// per-CR fully-qualified namespace prefix the M4
1522    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1523    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
1524    /// on `source()` / `destination()`, a per-CR canonicalization pass
1525    /// that lowercases the WIT world ref post-parse) migrates as a
1526    /// single caixa-core edit rather than a coordinated rewrite of
1527    /// nine open-coded triple-constructors.
1528    ///
1529    /// Peer of the sibling per-`:contratos` composite-projection
1530    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
1531    /// composite-value axes — closes the last unlifted owned-form
1532    /// composite-tuple axis on the per-`:contratos` diagnostic-
1533    /// construction surface. Named `edge_triple()` to reflect the
1534    /// identity name of the projected tuple (the typed-edge
1535    /// caller-callee-wit triple, sibling to the caller-callee-only
1536    /// pair `edge_pair()` returns).
1537    #[must_use]
1538    pub fn edge_triple(&self) -> (String, String, String) {
1539        (
1540            self.source().to_string(),
1541            self.destination().to_string(),
1542            self.world_ref().to_string(),
1543        )
1544    }
1545
1546    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
1547    /// dedups typed edges keys off — routes through the lifted
1548    /// [`WitContract::source`] / [`WitContract::destination`] /
1549    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
1550    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
1551    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
1552    /// type alias's six axes migrate as a unit on any future axis
1553    /// addition (adding a seventh field to [`WitContract`] is one
1554    /// [`ContratoIdentity`] alias edit + one accessor addition + one
1555    /// arm here, not a coordinated rewrite of every open-coded
1556    /// six-tuple builder that dedups on the identity axis).
1557    ///
1558    /// Sibling of [`WitContract::edge_pair`] /
1559    /// [`WitContract::edge_triple`] on the composite-projection axis:
1560    /// the pair projects the caller-callee axes, the triple extends it
1561    /// with the world-ref, this method extends it with the three
1562    /// payload-carrier axes. Every projection returns the same six
1563    /// scalar accessors' outputs; the three methods differ only in
1564    /// which arms they surface.
1565    ///
1566    /// Declared `pub const fn` — every callee is itself `pub const fn`
1567    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
1568    /// project through `pub const fn` [`String::as_str`], const-stable
1569    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
1570    /// [`Self::slot`] project through the same `String::as_str` under a
1571    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
1572    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1573    /// closed the const-eval surface on) and tuple construction from
1574    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1575    /// itself trivially const. The `ContratoIdentity<'_>` alias
1576    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1577    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1578    /// no heap allocation, no non-const call folded through the tuple's
1579    /// construction. Sibling in `const`-eval posture to the peer
1580    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1581    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1582    /// composite-projection family the sibling
1583    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1584    /// already anchors — this extends the same `const`-eval-surface
1585    /// posture onto the peer six-arm composite-projection axis where
1586    /// the projection surfaces the full identity tuple rather than a
1587    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1588    /// bearing by
1589    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1590    /// (a future accidental downgrade fires E0015 at the wrapper at
1591    /// caixa-core build time).
1592    #[must_use]
1593    pub const fn identity(&self) -> ContratoIdentity<'_> {
1594        (
1595            self.source(),
1596            self.destination(),
1597            self.world_ref(),
1598            self.endpoint(),
1599            self.subject(),
1600            self.slot(),
1601        )
1602    }
1603
1604    /// True when this contract targets an HTTP-shaped WIT world.
1605    ///
1606    /// Declared `pub const fn` — routes through the paired `pub const
1607    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1608    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1609    /// (d46420c). Sibling in `const`-eval posture to the peer
1610    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1611    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1612    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1613    /// the same `const`-eval-surface posture as the free-function
1614    /// classifier family it composes through. Pinned load-bearing by
1615    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1616    /// test (a future accidental downgrade to non-`const` fires E0015
1617    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1618    /// build time).
1619    #[must_use]
1620    pub const fn is_http(&self) -> bool {
1621        wit_shape_is_http(self.world_ref())
1622    }
1623
1624    /// True when this contract targets a pub-sub-shaped WIT world.
1625    ///
1626    /// Declared `pub const fn` — sibling in `const`-eval posture to
1627    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1628    /// [`Self::is_capability`] WIT-shape-predicate family. See
1629    /// [`Self::is_http`] for the family-closure rationale.
1630    #[must_use]
1631    pub const fn is_pubsub(&self) -> bool {
1632        wit_shape_is_pubsub(self.world_ref())
1633    }
1634
1635    /// True when this contract targets a key/value-shaped WIT world.
1636    ///
1637    /// Declared `pub const fn` — sibling in `const`-eval posture to
1638    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1639    /// [`Self::is_capability`] WIT-shape-predicate family. See
1640    /// [`Self::is_http`] for the family-closure rationale.
1641    #[must_use]
1642    pub const fn is_store(&self) -> bool {
1643        wit_shape_is_store(self.world_ref())
1644    }
1645
1646    /// True when this contract targets *none* of the three known payload-
1647    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1648    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1649    /// open on the [`WitContract`] surface. Returns the exact-inverse
1650    /// disjunction of the peer trio — `true` when none of the three
1651    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1652    /// author-declared WIT world is a pure typed capability edge with no
1653    /// payload selector (the shape [`WitContract::target`] projects onto
1654    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1655    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1656    ///
1657    /// The `:contratos :wit` shape-space is closed at four arms
1658    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1659    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1660    /// everything else on the payload-less capability arm), and every
1661    /// downstream consumer that must filter contratos by shape-class
1662    /// keys off the four sibling predicates (the [`WitContract::target`]
1663    /// dispatch's implicit `else` after the three payload-shape arm
1664    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1665    /// every future substrate-side capability-shape-only emitter — the
1666    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1667    /// future `feira app graph --capability` per-Aplicacao capability-
1668    /// column filter, the future per-cluster capability-scope reconciler
1669    /// that skips L4/L7 emission for payload-less edges since Cilium
1670    /// can't introspect WASI capability calls, the future
1671    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1672    /// shape shape-count histogram). Every such consumer reaches for one
1673    /// typed dispatch on the substrate primitive so the "which arm
1674    /// carries the capability-only shape?" answer lives at one caixa-core
1675    /// edit rather than open-coded across per-consumer
1676    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1677    /// negations, each of which would silently drop a future fourth
1678    /// payload-arm addition without a compile-time signal at the
1679    /// consumer site.
1680    ///
1681    /// Prior to this lift the "not one of the three known payload
1682    /// shapes" classification sat inline at [`WitContract::target`]'s
1683    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1684    /// [`WitTarget::Capability`] admission arm after the three `if
1685    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1686    /// { … }` guards) with no named accessor for downstream consumers
1687    /// to reach through. A future substrate-side capability-only
1688    /// filter or a future capability-scope reconciler would have had to
1689    /// re-inline the same triplet negation at every emit site with no
1690    /// compile-time link back to the sibling trio, and a future arm
1691    /// addition (a hypothetical fourth payload-shape prefix set — a
1692    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1693    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1694    /// trajectory bullet) would land the new predicate on the payload-
1695    /// carrying trio and silently misclassify the new shape as
1696    /// capability at every triplet-negation consumer site, propagating
1697    /// the drift far from the caixa-core prefix-set commit.
1698    ///
1699    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1700    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1701    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1702    /// axis, mirroring the paired post-projection [`WitTarget`]
1703    /// `gen_platform::IsVariant`-derived 4-way predicate set
1704    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1705    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1706    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1707    /// arm-set). The two typed axes — pre-projection on the raw
1708    /// `:contratos :wit` string, post-projection on the validated typed
1709    /// view — now carry a matched 4-arm predicate discipline: every
1710    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1711    /// predicate on the [`WitContract`] surface, and any future
1712    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1713    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1714    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1715    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1716    /// pre-projection axis through a matching peer prefix-set + peer
1717    /// predicate lift by construction — the compile-time exhaustiveness
1718    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1719    /// the post-projection accessor family stays in sync, and the sibling
1720    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1721    /// partition-witness pin locks the pre-projection classification in
1722    /// load-bearing so a peer prefix-set addition that widened one arm's
1723    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1724    /// surfaces as a test failure at caixa-core build time rather than a
1725    /// silent per-consumer split at renderer emit time.
1726    ///
1727    /// Composes byte-for-byte through the lifted peer trio
1728    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1729    /// any future rebrand of any prefix-set const flows through this
1730    /// method by construction without a coordinated per-consumer rewrite
1731    /// (pinned by the sibling
1732    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1733    /// composition-witness).
1734    ///
1735    /// Note: purely syntactic classification on the `:wit` prefix-set —
1736    /// unlike [`Self::target`], which additionally rejects value-shape-
1737    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1738    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1739    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1740    /// structurally malformed returns `true` from `is_capability()` (the
1741    /// prefix set matches nothing), and the surrounding
1742    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1743    /// is where the [`AplicacaoError::EmptyWit`] /
1744    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1745    /// predicate is the classifier, not the validator.
1746    ///
1747    /// Declared `pub const fn` — closes the WIT-shape-predicate
1748    /// family's `const`-eval-surface pass at the fourth (payload-less)
1749    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1750    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1751    /// See [`Self::is_http`] for the family-closure rationale.
1752    #[must_use]
1753    pub const fn is_capability(&self) -> bool {
1754        wit_shape_is_capability(self.world_ref())
1755    }
1756
1757    /// True when this contract's caller equals its callee — a
1758    /// structurally degenerate typed edge that no `:contratos` entry can
1759    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1760    /// Servico B" is an *inter*-Servico contract between two distinct
1761    /// graph nodes). A Servico contracting with itself resolves to an
1762    /// in-process call the wasm-engine never routes through the mesh at
1763    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1764    /// per-edge policy can express the intended shape — the pub-sub
1765    /// path silently rendered a self-allow rule that is a no-op (intra-
1766    /// pod traffic bypasses the mesh entirely), and the synchronous
1767    /// paths surfaced as a misleading `ContratoCycle` whose path was
1768    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1769    /// deadlock. Every downstream consumer that must reject the shape
1770    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1771    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1772    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1773    /// axis, every future adjacency-graph builder that must skip self-
1774    /// edges rather than fold them into an incidental cycle) now keys
1775    /// off exactly one typed dispatch on the substrate primitive, so
1776    /// any future rebrand on the axis (an M4-typed-caller enum whose
1777    /// identity comparison rule the accessor could route through, an
1778    /// operator-side per-cluster caller/callee-alias table the
1779    /// materializer resolves per-CR before the equality probe, a
1780    /// promotion of the pointwise `==` to a set-membership check once
1781    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1782    /// so a per-replica self-edge is rejected under the same predicate)
1783    /// migrates as a single caixa-core edit rather than a coordinated
1784    /// rewrite of every downstream self-edge consumer. Composes
1785    /// byte-for-byte through the lifted [`Self::source`] /
1786    /// [`Self::destination`] scalar accessors — the accessor pair every
1787    /// per-`:contratos` scalar-value axis already routes through — so
1788    /// any future rebrand of the underlying `:de` / `:para` storage
1789    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1790    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1791    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1792    /// same one body without a coordinated per-consumer rewrite.
1793    ///
1794    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1795    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1796    /// on the `:wit` world-ref axis — extended onto the per-edge
1797    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1798    /// partition the WIT-shape-space; `is_self_loop` partitions the
1799    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1800    /// the graph-theoretic identity of the shape (a loop from a graph
1801    /// node to itself, distinct from the sibling multi-node
1802    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1803    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1804    /// variant already carrying the term.
1805    ///
1806    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1807    /// shape-predicate on the substrate's `const`-eval surface. The peer
1808    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1809    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1810    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1811    /// posture on the WIT-world-ref classifier axis; this lift extends it
1812    /// onto the peer caller-callee identity-space predicate. The body
1813    /// projects the `:de` / `:para` `String` storage through the sibling
1814    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1815    /// accessors, then compares the resulting `&str` byte-slices under a
1816    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1817    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1818    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1819    /// — every operation `const`-eval-callable on stable Rust, no
1820    /// iterator methods, no `PartialEq for str` trait dispatch (which
1821    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1822    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1823    /// loop verbatim on the paired-slice-equality shape. Every downstream
1824    /// substrate-side `const`-context consumer of the per-`:contratos`
1825    /// self-edge partition (a future `const _: () = assert!(…)` module-
1826    /// scope invariant pin over a per-fixture typed [`WitContract`] once
1827    /// the type's carriers admit `const`-context construction, a future
1828    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1829    /// composer that fans on the identity-space partition at compile
1830    /// time) reaches through the same typed dispatch on the substrate
1831    /// primitive at const-eval time as at runtime. Pinned by
1832    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1833    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1834    /// future accidental downgrade to non-`const` trips at caixa-core
1835    /// build time with E0015 (`cannot call non-const method`), strictly
1836    /// stronger than a runtime `assert!`.
1837    #[must_use]
1838    pub const fn is_self_loop(&self) -> bool {
1839        // Compose through the paired `pub const fn` [`Self::source`] /
1840        // [`Self::destination`] scalar accessors so any future rebrand of
1841        // the underlying `:de` / `:para` storage (a lift from `String` to
1842        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1843        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1844        // inline-buffer swap) flows through the same one body without a
1845        // coordinated per-consumer rewrite. Peer of the sibling
1846        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1847        // [`Self::is_capability`] shape-predicate family — each of which
1848        // composes through the paired [`Self::world_ref`] scalar accessor
1849        // onto the peer `pub const fn` [`wit_shape_is_http`] /
1850        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1851        // [`wit_shape_is_capability`] free-function classifier — the same
1852        // "typed dispatch composes with typed dispatch, not raw field
1853        // access" discipline extended onto the caller-callee identity-
1854        // space partition. Pinned by
1855        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1856        // above.
1857        let a = self.source().as_bytes();
1858        let b = self.destination().as_bytes();
1859        if a.len() != b.len() {
1860            return false;
1861        }
1862        // Manual byte-level equality loop — mirrors the peer
1863        // [`wit_shape_matches`] combinator's manual `starts_with` loop
1864        // verbatim on the paired-slice-equality shape. `PartialEq for
1865        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1866        // trait dispatch it routes through is not `const`), so a naive
1867        // `self.source() == self.destination()` body would trip on
1868        // `const`-eval-callability; the byte-slice loop dispatches
1869        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1870        // const-stable slice indexing (since Rust 1.79) — every
1871        // operation `const`-eval-callable on stable.
1872        let mut i = 0;
1873        while i < a.len() {
1874            if a[i] != b[i] {
1875                return false;
1876            }
1877            i += 1;
1878        }
1879        true
1880    }
1881
1882    /// Reject a `:contratos` entry whose `:de` or `:para` names a
1883    /// caixa the `:membros` graph does not contain — the substrate-
1884    /// primitive per-edge graph-membership gate every consumer of the
1885    /// typed inter-Servico edge's endpoint-resolution axis reaches
1886    /// through one dispatch.
1887    ///
1888    /// A `:contratos` entry is a typed directed edge between two
1889    /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
1890    /// address graph nodes, so a reference to a node the graph does
1891    /// not contain is a build error"). Both endpoints must resolve
1892    /// against the same [`AplicacaoSpec::membro_names`] oracle: the
1893    /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
1894    /// framing does not distinguish `:de` from `:para` (both arms
1895    /// carry the offending `caixa` name verbatim without a
1896    /// slot-discriminator field, unlike the sibling per-arm shape
1897    /// gate [`validate_contrato_caixa`] whose paired
1898    /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
1899    /// variants each carry a `slot: &'static str` tag). So the two
1900    /// arms are byte-identical modulo the accessor projection they
1901    /// key off, and folding them into one per-edge dispatch preserves
1902    /// every existing diagnostic-fired output byte-for-byte while
1903    /// closing the last inline duplication the substrate-primitive
1904    /// per-edge gate family carried inside
1905    /// [`AplicacaoSpec::validate_contratos`].
1906    ///
1907    /// Routes through the paired [`Self::source`] / [`Self::destination`]
1908    /// scalar accessors so every future rebrand of the underlying
1909    /// `:de` / `:para` storage (a lift from `String` to a typed
1910    /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
1911    /// the M4 CR materializer authors, a per-cluster caller-alias
1912    /// table the operator pins through a future `:placement`-scoped
1913    /// slot, an M4 promotion from `String` to a typed edge-endpoint
1914    /// enum) flows through the same body without a coordinated
1915    /// per-consumer rewrite. Peer of the sibling per-edge substrate
1916    /// primitives already lifted on the same `impl WitContract`
1917    /// surface ([`Self::is_self_loop`] on the identity-space arm,
1918    /// [`Self::target`] on the payload-shape ↔ target-consistency
1919    /// arm, [`Self::identity`] on the dedup-key arm) — this run
1920    /// extends the shape to the last per-edge axis
1921    /// [`AplicacaoSpec::validate_contratos`] carried as an inline
1922    /// twin-arm cascade.
1923    ///
1924    /// Every future consumer that wants to re-check *one* edge's
1925    /// graph-membership reaches through one call: the M4
1926    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1927    /// admission-webhook re-checking `:contratos` after a
1928    /// per-`(:de, :para)` edge patch without re-walking the whole
1929    /// `:contratos` list, the per-`:contratos`-edge `:politicas`
1930    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
1931    /// resolves an effective per-edge [`MeshPolicy`] and must
1932    /// re-check the edge's endpoints against the same membership
1933    /// oracle before it can key a per-edge override off the endpoint
1934    /// tuple. Pre-lift each such consumer was structurally forced to
1935    /// either re-inline the twin `if !names.contains(...)` cascade
1936    /// (the duplication the PRIME DIRECTIVE names as a bug) or call
1937    /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
1938    /// walk to re-check one edge. Post-lift each reaches the axis
1939    /// through one dispatch on the substrate primitive.
1940    ///
1941    /// `:de` runs before `:para` per the canonical edge-direction
1942    /// order the sibling per-arm shape gate
1943    /// [`validate_contrato_caixa`] arm ordering, the self-loop
1944    /// diagnostic string, and every peer arm ordering in
1945    /// [`AplicacaoSpec::validate_contratos`] already use — a
1946    /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
1947    /// phantom `:para`, preserving byte-equal ordering with the
1948    /// pre-lift inline cascade.
1949    fn require_endpoints_in(
1950        &self,
1951        names: &std::collections::HashSet<&str>,
1952    ) -> Result<(), AplicacaoError> {
1953        if !names.contains(self.source()) {
1954            return Err(AplicacaoError::contrato_member_missing(self.source()));
1955        }
1956        if !names.contains(self.destination()) {
1957            return Err(AplicacaoError::contrato_member_missing(self.destination()));
1958        }
1959        Ok(())
1960    }
1961
1962    /// Typed view of the contract's payload target. Enforces that the
1963    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1964    /// fields agree, and that each carried value is itself
1965    /// value-shape valid:
1966    ///
1967    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1968    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1969    ///     `PathPrefix` invariant — same shape required of `:entrada
1970    ///     :paths`)
1971    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1972    ///     non-empty (NATS / Kafka publish without a subject is a
1973    ///     no-op subscribe, never the author's intent)
1974    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1975    ///     non-empty (an empty slot template addresses the bucket
1976    ///     root, defeating the per-key isolation the slot exists for)
1977    ///   - Anything else ⇒ none of the three; the contract is a pure
1978    ///     typed capability edge with no payload selector.
1979    ///
1980    /// Translates the Apollo Federation discipline ("conflicts are
1981    /// errors at compile time, not warnings at runtime";
1982    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1983    /// a contract whose WIT shape disagrees with its target field, or
1984    /// whose target field carries a value-shape-invalid string, is a
1985    /// build error — not a silent renderer drop. The returned
1986    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1987    /// non-empty (and absolute, for `Http`); every downstream consumer
1988    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1989    /// the M4 per-edge policy resolver) can rely on that without
1990    /// re-checking.
1991    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1992        // Route the HTTP-shaped payload-target extraction through the
1993        // lifted [`WitContract::endpoint`] accessor rather than the raw
1994        // `self.endpoint.as_deref()` field access — the two production
1995        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1996        // payload-carrier scalar (this method's Http-arm payload
1997        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1998        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1999        // off exactly one typed dispatch on the substrate primitive, so
2000        // any future rebrand on the axis (an M4 per-cluster endpoint-
2001        // alias rewrite, a per-CR fully-qualified path prefix the M4
2002        // materializer applies per-tenant, an M4 promotion from
2003        // `Option<String>` to a typed HTTP path-template enum) migrates
2004        // as a single caixa-core edit rather than a coordinated rewrite
2005        // of the two call sites — peer of the sibling M3 per-`:placement`
2006        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
2007        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
2008        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
2009        let endpoint = self.endpoint();
2010        let subject = self.subject();
2011        // Route the store-arm payload-carrier scalar through the
2012        // lifted [`WitContract::slot`] accessor rather than the raw
2013        // `self.slot.as_deref()` field access — the two production
2014        // consumers of the per-`:contratos :slot` key/value-store-
2015        // shaped payload-carrier scalar (this method's Store-arm
2016        // payload extraction, the [`AplicacaoSpec::validate`]
2017        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
2018        // arm) now key off exactly one typed dispatch on the substrate
2019        // primitive. Closes the last unlifted per-`:contratos`
2020        // `Option<String>` axis, completing the payload-carrier
2021        // accessor family peer of the sibling per-`:contratos`
2022        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
2023        // (90de675) lifts across the HTTP / pub-sub arms.
2024        let slot = self.slot();
2025        // Route the local `(de, para, wit)` triple-projection closure
2026        // through the lifted [`WitContract::edge_triple`] typed accessor
2027        // rather than re-inlining `(self.de.clone(), self.para.clone(),
2028        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
2029        // triple-carrying diagnostic constructors below (wrong-target /
2030        // missing-target on all three payload arms + capability-with-
2031        // payload + invalid-wit) now key off exactly one typed dispatch
2032        // on the substrate-primitive composite projection, sibling to
2033        // the peer [`WitContract::edge_pair`]-routed
2034        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
2035        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
2036        // diagnostic constructors on the same per-`:contratos`
2037        // diagnostic-construction surface.
2038        let edge = || self.edge_triple();
2039
2040        // The `:wit` value drives every downstream dispatch — the
2041        // is_http/is_pubsub/is_store prefix matchers below, the
2042        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
2043        // exclusion. Until this gate landed `target()` accepted any
2044        // non-empty string and silently demoted unrecognized shapes to
2045        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
2046        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
2047        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
2048        // package, the paste-from-binary footgun a multi-line blob
2049        // accidentally landing in the slot, the un-percent-encoded
2050        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
2051        // routing, got L4-only" footgun. Empty is still pre-checked at
2052        // the [`AplicacaoSpec::validate`] call site via the narrower
2053        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
2054        // validate layer); the value-shape gate here picks up the
2055        // structurally-invalid non-empty cases the empty check misses,
2056        // and remains correct under direct `target()` calls outside
2057        // validate (the predicate's defensive empty arm returns a
2058        // parser-shaped reason rather than silently falling through to
2059        // the Capability arm). Same trajectory as c4213a4 (WitContract
2060        // endpoint/subject/slot value-shape gates lifted into
2061        // `target()`) on the peer payload axes.
2062        //
2063        // Routed through the lifted [`WitContract::world_ref`] accessor
2064        // rather than the raw `&self.wit` field access — the two
2065        // production consumers of the per-`:contratos :wit` world-ref
2066        // byte-string on the value-shape axis (this method's invalid-
2067        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
2068        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
2069        // [`WitContract::identity`]) now key off exactly one typed
2070        // dispatch on the substrate primitive, so any future rebrand on
2071        // the axis (an M4 promotion from `String` to a typed WIT
2072        // world-ref enum once the WIT registry stabilizes in
2073        // tatara-lisp, a per-CR canonicalization pass that lowercases
2074        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
2075        // inline-buffer swap on the storage arm) migrates as a single
2076        // caixa-core edit rather than a coordinated rewrite of the two
2077        // call sites — sibling of the peer [`WitContract::endpoint`] /
2078        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
2079        // routed payload-carrier extractions above on the same
2080        // [`WitContract::target`] body, completing the per-`:contratos`
2081        // scalar-accessor-routing pass at the last unlifted raw-field-
2082        // access site inside `impl WitContract`. Same "typed dispatch
2083        // composes with typed dispatch, not with raw field access"
2084        // discipline the sibling [`WitContract::edge_pair`] /
2085        // [`WitContract::edge_triple`] / [`WitContract::identity`]
2086        // composite-projection accessors and the
2087        // [`WitContract::is_self_loop`] identity-space predicate
2088        // already route through. Pinned by
2089        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
2090        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
2091            return Err(AplicacaoError::contrato_wit_invalid(
2092                self.edge_pair(),
2093                self.world_ref(),
2094                reason,
2095            ));
2096        }
2097
2098        if self.is_http() {
2099            if subject.is_some() || slot.is_some() {
2100                return Err(AplicacaoError::contrato_wrong_target(
2101                    edge(),
2102                    WitTarget::HTTP_FIELD_NAME,
2103                ));
2104            }
2105            let ep = endpoint.ok_or_else(|| {
2106                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
2107            })?;
2108            if ep.is_empty() {
2109                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
2110            }
2111            if !ep.starts_with('/') {
2112                return Err(AplicacaoError::contrato_endpoint_not_absolute(
2113                    self.edge_pair(),
2114                    ep,
2115                ));
2116            }
2117            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
2118            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
2119            // API v1 HTTPPathMatch.value admission grammar with the
2120            // sibling `:entrada :paths` axis. Until this gate landed
2121            // `target()` only refused the empty string + the missing-
2122            // leading-`/` form; a structurally invalid endpoint
2123            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
2124            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
2125            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
2126            // path-traversal segment, the >1024-byte slug) silently
2127            // passed validate and the failure surfaced at apply time
2128            // as a Cilium policy rejection / silent traffic drop, far
2129            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
2130            // grammar `:entrada :paths` already gates (55410e4), now
2131            // shared with `:contratos :endpoint` through the lifted
2132            // `crate::render::is_gateway_api_http_path` predicate.
2133            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
2134                return Err(AplicacaoError::contrato_endpoint_invalid(
2135                    self.edge_pair(),
2136                    ep,
2137                    reason,
2138                ));
2139            }
2140            return Ok(WitTarget::Http { endpoint: ep });
2141        }
2142        if self.is_pubsub() {
2143            if endpoint.is_some() || slot.is_some() {
2144                return Err(AplicacaoError::contrato_wrong_target(
2145                    edge(),
2146                    WitTarget::PUBSUB_FIELD_NAME,
2147                ));
2148            }
2149            let s = subject.ok_or_else(|| {
2150                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
2151            })?;
2152            if s.is_empty() {
2153                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
2154            }
2155            // The `:subject` lands at runtime as the NATS subject the
2156            // producer publishes to and the consumer subscribes from.
2157            // Until this gate landed `target()` only refused the
2158            // empty string; a structurally invalid subject
2159            // (`"foo..bar"` — empty token between separators,
2160            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
2161            // server's subject parser rejects, `"foo bar"` —
2162            // un-percent-encoded whitespace, `"foo.café"` —
2163            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
2164            // empty leading/trailing tokens, the >256-byte
2165            // paste-from-binary slug) silently passed validate and
2166            // the failure surfaced at runtime as a NATS server-side
2167            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
2168            // a silent message drop, far from the source caixa.lisp.
2169            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
2170            // trajectory `:contratos :endpoint` (4f0390b) and
2171            // `:contratos :wit` (6226bf4) already gate, now shared
2172            // with `:contratos :subject` through the lifted
2173            // `crate::render::is_nats_subject` predicate.
2174            if let Err(reason) = crate::render::is_nats_subject(s) {
2175                return Err(AplicacaoError::contrato_subject_invalid(
2176                    self.edge_pair(),
2177                    s,
2178                    reason,
2179                ));
2180            }
2181            return Ok(WitTarget::PubSub { subject: s });
2182        }
2183        if self.is_store() {
2184            if endpoint.is_some() || subject.is_some() {
2185                return Err(AplicacaoError::contrato_wrong_target(
2186                    edge(),
2187                    WitTarget::STORE_FIELD_NAME,
2188                ));
2189            }
2190            let sl = slot.ok_or_else(|| {
2191                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
2192            })?;
2193            if sl.is_empty() {
2194                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
2195            }
2196            // Value-shape gate on the third (and last) typed payload
2197            // axis the `WitContract::target` dispatch carries — the
2198            // peer of [`crate::render::is_gateway_api_http_path`] for
2199            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
2200            // for `:subject` (63e18a0). Until this gate landed
2201            // `target()` only refused the empty string; a structurally
2202            // invalid slot (`"check out/$order"` — un-percent-encoded
2203            // whitespace whose runtime behavior varies unpredictably
2204            // across kv backends, `"checkout/\x01order"` — control
2205            // character that Redis admits but corrupts on next read
2206            // and DynamoDB rejects outright, `"chéckout/$order"` —
2207            // un-percent-encoded non-ASCII byte each backend re-encodes
2208            // differently, `"checkout\n/$order"` — embedded newline,
2209            // the 513-byte paste-from-binary slug) silently passed
2210            // validate and surfaced at runtime as a per-backend kv
2211            // write rejection (DynamoDB / etcd) or as a silent
2212            // next-read corruption (Redis-via-RESP3), far from the
2213            // source caixa.lisp with no field naming which `:contratos`
2214            // edge carried the typo. The lifted predicate makes the
2215            // kv-backend intersection-floor a substrate-level
2216            // invariant at validate time, not a runtime "this passed
2217            // validate but the kv backend rejected on first write"
2218            // surprise — closes the typed payload-axis value-shape
2219            // trajectory across all three legs of the four
2220            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
2221            // that caixa-mesh + the future kv emitters land in.
2222            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
2223                return Err(AplicacaoError::contrato_slot_invalid(
2224                    self.edge_pair(),
2225                    sl,
2226                    reason,
2227                ));
2228            }
2229            return Ok(WitTarget::Store { slot: sl });
2230        }
2231
2232        // Unrecognized WIT world — must not carry any payload target.
2233        if endpoint.is_some() || subject.is_some() || slot.is_some() {
2234            return Err(AplicacaoError::contrato_wrong_target(
2235                edge(),
2236                WitTarget::CAPABILITY_EXPECTED,
2237            ));
2238        }
2239        Ok(WitTarget::Capability)
2240    }
2241
2242    /// Substrate-canonical post-validation projection of the typed
2243    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
2244    /// downstream of an [`AplicacaoSpec`] that has already crossed the
2245    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
2246    /// [`typed_view`]-shaped entry point that composes `validate` into
2247    /// the projection) reaches through when it needs the typed
2248    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
2249    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
2250    /// coherence for every `:contratos` entry. The peer accessor to the
2251    /// [`Self::target`] `Result`-returning validator on the same
2252    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
2253    /// pre-validation validator that computes the projection *and* raises
2254    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
2255    /// (`:wit`, payload) mismatch; this method is the post-validation
2256    /// projection every downstream consumer reaches through once the
2257    /// pre-validation gate has succeeded.
2258    ///
2259    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2260    ///
2261    /// Prior to this lift the "call `.target()` then `.expect(…)` with
2262    /// the same message" pattern sat inline at two production sites with
2263    /// no compile-time link between them: the
2264    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
2265    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
2266    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
2267    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
2268    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
2269    /// (`c.target().expect("validated by typed_view").graph_label()`),
2270    /// each open-coding the same `.target().expect("validated by
2271    /// typed_view")` pair with the message spelled twice. A future
2272    /// vocabulary shift on the panic-message axis (a tightening from
2273    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
2274    /// validate"` as the substrate's validator entry-point vocabulary
2275    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
2276    /// panic to a `debug_assert` under a `--release` build profile) would
2277    /// have had to be threaded through both open-coded call sites in
2278    /// lockstep or one consumer would silently disagree with the peer on
2279    /// which invariant the panic message names. Same "same shape written
2280    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
2281    /// discipline the sibling [`Self::edge_pair`] /
2282    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
2283    /// lifts already establish on the paired composite-projection axis;
2284    /// this lift extends it onto the post-validation typed-view axis.
2285    ///
2286    /// Every future downstream consumer of the projected typed view
2287    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
2288    /// CR materializer's per-edge admission webhook, the future
2289    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
2290    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
2291    /// resolver, the future `feira app graph --l7` / `--pubsub` /
2292    /// `--kv` per-shape column emitters) reaches through this one typed
2293    /// dispatch on the substrate primitive rather than an open-coded
2294    /// per-consumer `.target().expect(…)` pair with the message
2295    /// re-inlined. The invariant the accessor's panic path pins — "this
2296    /// call is only reachable after [`AplicacaoSpec::validate`] has
2297    /// succeeded on the containing spec" — is the substrate's answer to
2298    /// give exactly once, at the primitive, not once per consumer.
2299    ///
2300    /// # Panics
2301    ///
2302    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
2303    /// would return an `Err` — i.e. if this contract's
2304    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
2305    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
2306    /// this accessor only from a code path that has already reached the
2307    /// containing [`AplicacaoSpec`] through a validating entry-point
2308    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
2309    /// [`typed_view`] compose, the future M4 CR admission webhook's
2310    /// per-CR validate). Use [`Self::target`] instead on any pre-
2311    /// validation code path.
2312    ///
2313    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2314    #[must_use]
2315    pub fn target_projected(&self) -> WitTarget<'_> {
2316        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
2317    }
2318
2319    /// Canonical panic message the [`Self::target_projected`]
2320    /// post-validation projection accessor threads through when the
2321    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
2322    /// has succeeded" precondition. Lifted as a `pub const` on the
2323    /// [`WitContract`] surface so the byte-string lives in one place
2324    /// across the substrate — the [`Self::target_projected`] method
2325    /// body, the two prior production call sites' comments now naming
2326    /// the const, and every future consumer that must format-match the
2327    /// panic-message shape (a future test suite that asserts the panic-
2328    /// message byte-string across a fuzzed invalid-contract corpus,
2329    /// a future custom-panic hook in `caixa-operator` that surfaces the
2330    /// message with per-`:contratos` telemetry, the future admission
2331    /// webhook's per-CR validate-error report) reaches through the same
2332    /// canonical `&'static str`. A future rebrand on the panic-message
2333    /// axis (a tightening from `"validated by typed_view"` to `"validated
2334    /// by AplicacaoSpec::validate"` as the substrate's validator
2335    /// entry-point vocabulary sharpens once caixa-core grows a
2336    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
2337    /// [`typed_view`]) lands at one caixa-core edit rather than a
2338    /// coordinated per-consumer sweep — same "one canonical declaration
2339    /// per axis, next to the accessor that reads it" discipline the peer
2340    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
2341    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
2342    /// const family already establishes on the paired per-consumer-axis
2343    /// diagnostic-scalar surface.
2344    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
2345}
2346
2347/// Borrowed identity key for the typed-graph duplicate-`:contratos`
2348/// gate (see [`AplicacaoSpec::validate`]): every field that
2349/// distinguishes one contract from another, in declaration order
2350/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
2351/// with equal [`ContratoIdentity`]s are the same typed edge declared
2352/// twice — the graph-edge analogue of duplicate `:membros` /
2353/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
2354/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
2355/// clippy's `type_complexity` lint (and so a future axis added to
2356/// `WitContract` is one alias edit, not a coordinated rewrite of
2357/// every set instantiation).
2358pub type ContratoIdentity<'a> = (
2359    &'a str,
2360    &'a str,
2361    &'a str,
2362    Option<&'a str>,
2363    Option<&'a str>,
2364    Option<&'a str>,
2365);
2366
2367/// Typed view of a [`WitContract`]'s payload target. Each variant
2368/// carries the field its WIT shape requires; constructing a `Http`
2369/// view without an endpoint is impossible by the type system.
2370///
2371/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
2372/// instead of probing `Option<String>` fields one by one — the
2373/// "which payload field is set?" question is answered once, at
2374/// validation time.
2375#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
2376pub enum WitTarget<'a> {
2377    /// HTTP-shaped WIT world. Carries the configured request path.
2378    Http { endpoint: &'a str },
2379    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
2380    ///
2381    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
2382    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
2383    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
2384    /// method name byte-identical to the sibling
2385    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
2386    /// arm-discriminator that routes through
2387    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
2388    /// through `matches!` on the variant), so the two arm-discriminator
2389    /// axes — target-side variant-arm and shape-side ref-prefix — reach
2390    /// every downstream consumer through the same `is_pubsub()` name.
2391    #[is_variant(name = "pubsub")]
2392    PubSub { subject: &'a str },
2393    /// Key-value-shaped WIT world. Carries the slot template.
2394    Store { slot: &'a str },
2395    /// A typed capability edge with no payload selector — the WIT
2396    /// world stands on its own (rare; reserved for plain capability
2397    /// imports or M4-and-later WIT worlds we haven't shaped yet).
2398    Capability,
2399}
2400
2401impl<'a> WitTarget<'a> {
2402    /// Canonical author-facing `:contratos` payload field name for the
2403    /// HTTP-shaped arm — the `expected: &'static str` scalar the
2404    /// [`AplicacaoError::ContratoMissingTarget`] /
2405    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2406    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
2407    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
2408    /// the `feira app graph` verb prints. Peer of
2409    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
2410    /// on the payload-field-name axis; declared as a peer const next
2411    /// to the [`WitTarget::Http`] variant so a future rename on the
2412    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
2413    /// :endpoint …)))` field lands in exactly one place, not scattered
2414    /// across the [`WitContract::target`] gate's six `expected:`
2415    /// literals, the label template, and every downstream consumer
2416    /// that prints a per-arm prefix. Same trajectory as the peer
2417    /// [`WitTarget::label`] lift (174e96a): a single source of truth
2418    /// for the arm's shape, next to the variant declaration.
2419    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
2420    /// Canonical author-facing `:contratos` payload field name for the
2421    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
2422    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
2423    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2424    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
2425    /// Canonical author-facing `:contratos` payload field name for the
2426    /// key/value-store-shaped arm. Peer of
2427    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
2428    /// on the payload-field-name axis; see
2429    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2430    pub const STORE_FIELD_NAME: &'static str = "slot";
2431
2432    /// Canonical stable human-readable label the payload-less
2433    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
2434    /// the byte-string every consumer that formats a payload-less
2435    /// typed capability edge as text lands on (the
2436    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
2437    /// naming which identical edge was declared twice, the future
2438    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
2439    /// policy resolver's audit view, the operator's mesh-graph audit).
2440    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
2441    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
2442    /// author-facing label-scalar consts — the same
2443    /// "one canonical declaration per arm, next to the variant, so a
2444    /// future rename lands in one place" discipline extended to the
2445    /// payload-less arm. Until this lift landed the byte-string sat
2446    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
2447    /// match arm, once in the pin test asserting the label's
2448    /// [`WitTarget::Capability`] output — with no compile-time link
2449    /// between the two: a rebrand on either side (an operator-facing
2450    /// vocabulary shift, a per-consumer disambiguation like
2451    /// `"(capability — no payload; typed edge only)"`) would silently
2452    /// desynchronize until a downstream consumer surfaced the drift at
2453    /// runtime.
2454    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
2455
2456    /// Canonical `expected:` scalar the
2457    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2458    /// through for the payload-less [`WitTarget::Capability`] arm — the
2459    /// byte-string authors read as "this WIT world's shape is not one
2460    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
2461    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
2462    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2463    /// [`Self::STORE_FIELD_NAME`] consts on the
2464    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
2465    /// same "which payload field name goes in the diagnostic" dispatch
2466    /// the three payload-arm consts cover, extended to the payload-less
2467    /// arm. Until this lift landed the byte-string sat twice — once
2468    /// inline in the [`Self::target`] Capability-arm rejection at the
2469    /// production dispatch, once in the pin test asserting the
2470    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
2471    /// no compile-time link between the two: a rebrand on either side
2472    /// (an author-facing vocabulary shift to `"capability"` /
2473    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
2474    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
2475    /// [`WitTarget::Capability`] into per-shape peers) would silently
2476    /// desynchronize until a downstream consumer surfaced the drift at
2477    /// runtime. Same "one canonical declaration per arm, next to the
2478    /// variant, so a future rename lands in one place" discipline the
2479    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
2480    /// established for the payload-less arm's human-readable label
2481    /// axis; this lift extends it onto the peer diagnostic-scalar axis
2482    /// so both halves of the "how does the Capability arm surface at
2483    /// its two consumer axes (human-readable label, wrong-target
2484    /// diagnostic)" pipeline route through peer consts declared next
2485    /// to the variant.
2486    ///
2487    /// Pairwise-distinctness against the three payload-arm scalars
2488    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2489    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
2490    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
2491    /// test — the 4-way closure of the 3-way
2492    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
2493    /// the `ContratoWrongTarget::expected` axis, matching the peer
2494    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
2495    /// scalar-value distinctness discipline the sibling M3 typed-enum
2496    /// discriminator axis already carries.
2497    pub const CAPABILITY_EXPECTED: &'static str = "none";
2498
2499    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
2500    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
2501    /// as under [`Self::graph_label`] — the sibling
2502    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
2503    /// payload-column axis (the graph verb spells payload-less as
2504    /// `(capability-only)`, distinct from the duplicate-`:contratos`
2505    /// diagnostic's `(capability — no payload)` on the human-readable
2506    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
2507    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
2508    /// family — extends the "one canonical declaration per arm, next to
2509    /// the variant, so a future rename lands in one place" discipline
2510    /// onto the third payload-less-arm consumer axis (`feira app graph`
2511    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
2512    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
2513    /// axis).
2514    ///
2515    /// Until this lift landed the byte-string sat inline in
2516    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
2517    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
2518    /// `"(capability-only)".to_string()` literal, with no compile-time link
2519    /// back to the [`WitTarget::Capability`] variant declaration nor to
2520    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
2521    /// peer consts already carrying the "one canonical declaration per
2522    /// payload-less-arm consumer axis" discipline. A rebrand on either
2523    /// side (the graph verb's operator-facing vocabulary tightening from
2524    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
2525    /// the WIT registry vocabulary sharpens, an M4 split of
2526    /// [`Self::Capability`] into per-shape peers) would silently
2527    /// desynchronize the graph-verb byte-string from the paired
2528    /// per-arm-adjacent const and land two spellings of the same axis in
2529    /// two spots.
2530    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
2531
2532    /// The `(author-facing field name, payload)` pair this typed target
2533    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
2534    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
2535    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
2536    /// [`Self::Store`], `None` for the payload-less
2537    /// [`Self::Capability`] arm.
2538    ///
2539    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
2540    /// (formats `":{field} {payload:?}"` on `Some`, falls to
2541    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
2542    /// (returns the first component) route through, so a future
2543    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
2544    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
2545    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
2546    /// exactly one new match-arm here (a compile-time exhaustiveness
2547    /// error otherwise), not a coordinated three-way rewrite of the
2548    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
2549    /// + every downstream consumer that reaches for the pair.
2550    ///
2551    /// Until this lift landed the three payload arms sat in
2552    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
2553    /// invocations (one per variant, each hand-quoting the paired
2554    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2555    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
2556    /// "same shape, written N times" duplication THEORY.md §I.3.5
2557    /// ("Generation first, composition second, hand-authoring last;
2558    /// the duplication budget is zero") promotes to a build-time
2559    /// concern, with each per-arm site paired to its own const with no
2560    /// compile-time link between the format template and the arm's
2561    /// payload extraction.
2562    #[must_use]
2563    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
2564        match *self {
2565            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
2566            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
2567            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
2568            WitTarget::Capability => None,
2569        }
2570    }
2571
2572    /// The canonical author-facing `:contratos` payload field name
2573    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2574    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2575    /// `None` for the payload-less `Capability` arm.
2576    ///
2577    /// Routes through [`Self::payload_pair`] — the single 4-arm
2578    /// dispatch [`Self::label`] also reads — so a future variant
2579    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2580    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2581    /// dispatch, thin projections at each consumer" trajectory the
2582    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2583    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2584    #[must_use]
2585    pub const fn field_name(&self) -> Option<&'static str> {
2586        match self.payload_pair() {
2587            Some((f, _)) => Some(f),
2588            None => None,
2589        }
2590    }
2591
2592    /// The underlying scalar the payload-carrying arm carries — the
2593    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2594    /// subject ([`Self::PubSub`] `:subject`), or slot template
2595    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2596    /// `&'a str` storage — or `None` on the payload-less
2597    /// [`Self::Capability`] arm.
2598    ///
2599    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2600    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2601    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2602    /// the paired sub-selector axis. Both per-half accessors read from
2603    /// one authoritative match, so a future [`WitTarget`] variant
2604    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2605    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2606    /// on [`Self::payload_pair`] and both per-half projections + every
2607    /// downstream consumer picks the new arm up by construction — no
2608    /// coordinated N-way rewrite across the paired accessor dispatches,
2609    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2610    /// and every future WIT-registry-shaped consumer.
2611    ///
2612    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2613    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2614    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2615    /// both per-half projections as thin readers, every downstream
2616    /// consumer through the same match" discipline extended onto the
2617    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2618    /// gap between the two paired-dispatch surfaces: the peer
2619    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2620    /// the first-component projection until this lift; the second-
2621    /// component sibling now sits alongside so both halves reach every
2622    /// future consumer through the same substrate-primitive dispatch.
2623    ///
2624    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2625    #[must_use]
2626    pub const fn payload(&self) -> Option<&'a str> {
2627        match self.payload_pair() {
2628            Some((_, p)) => Some(p),
2629            None => None,
2630        }
2631    }
2632
2633    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2634    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2635    /// returns the [`Self::Http`]-arm's author-declared request path
2636    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2637    /// projected target is [`Self::Http { endpoint }`], `None` on the
2638    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2639    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2640    /// definition).
2641    ///
2642    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2643    /// `path:` rule payload every substrate-side L7-introspecting
2644    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2645    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2646    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2647    /// on the L7 introspection branch; every peer WIT shape stays
2648    /// L4-only because Cilium can't introspect NATS / key-value / plain
2649    /// capability edges), and every future L7-introspecting consumer
2650    /// of the projected target's HTTP endpoint (the future M4
2651    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2652    /// materializer's per-edge L7 admission-webhook overlay, the
2653    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2654    /// path bucket-key resolver, the future per-`:contratos`-edge
2655    /// mTLS-required overlay's HTTP-shape scope filter, the future
2656    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2657    /// through the same typed dispatch.
2658    ///
2659    /// Prior to this lift the sole production consumer of the projected-
2660    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2661    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2662    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2663    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2664    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2665    /// match that expressed no compile-time link back to the substrate
2666    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2667    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2668    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2669    /// with no post-projection peer on the typed-view surface. A future
2670    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2671    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2672    /// gRPC-shaped worlds per this enum's own docstring at
2673    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2674    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2675    /// would have had to be threaded through the caixa-mesh L7 emit
2676    /// branch's raw `if let` in lockstep — either coalescing the two
2677    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2678    /// emit path per-arm — with no substrate-primitive dispatch making
2679    /// the "which arms count as L7-HTTP-shaped for path-emission
2680    /// purposes" question the substrate's answer to give. Lifting the
2681    /// resolution to a typed method on the substrate primitive means
2682    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2683    /// projected-target HTTP endpoint reaches for exactly one typed
2684    /// dispatch — the resolver's accept-set migrates as a unit on any
2685    /// future arm-family widening, and the caixa-mesh L7 emit branch
2686    /// reads through the same substrate primitive.
2687    ///
2688    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2689    /// (7020470) `Option<&str>` scalar accessor on the raw
2690    /// `:contratos :endpoint` field-access axis — same "one typed
2691    /// dispatch on the substrate primitive, thin projections at each
2692    /// consumer" discipline extended onto the peer post-projection typed-
2693    /// view surface (the [`WitContract::endpoint`] pre-projection
2694    /// accessor returns `Some` for any author-declared `:endpoint`
2695    /// value regardless of the paired `:wit` world's HTTP-shape
2696    /// classification — the raw slot before validation crosses it —
2697    /// while this post-projection [`Self::http_endpoint`] accessor
2698    /// returns `Some` iff the target has been projected onto the
2699    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2700    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2701    /// coherence; the two accessors close the pre-projection /
2702    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2703    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2704    /// the three payload-carrying arms) — extends the per-arm
2705    /// projection family onto the [`Self::Http`] specialization axis
2706    /// that the pan-arm accessor's shape blends into a single arm-
2707    /// agnostic view; paired with [`Self::pubsub_subject`] /
2708    /// [`Self::store_slot`] on the sibling per-arm axes so every
2709    /// per-payload-arm shape carries a named post-projection accessor
2710    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2711    /// accept-set the substrate primitive owns.
2712    #[must_use]
2713    pub const fn http_endpoint(&self) -> Option<&'a str> {
2714        match *self {
2715            WitTarget::Http { endpoint } => Some(endpoint),
2716            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2717        }
2718    }
2719
2720    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2721    /// consumer that fans on the pub-sub-shaped payload keys off —
2722    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2723    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2724    /// the projected target is [`Self::PubSub { subject }`], `None` on
2725    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2726    /// [`Self::Capability`], each of which carries no NATS-shaped
2727    /// subject by definition).
2728    ///
2729    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2730    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2731    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2732    /// CR materializer's `spec.subjects[]` projection, the future
2733    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2734    /// bucket-key resolver, the future `feira app graph --pubsub`
2735    /// per-Aplicacao subject column, any future substrate-lifted
2736    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2737    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2738    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2739    /// future pub-sub-shape consumer reaches for the same typed
2740    /// dispatch this accessor exposes so the "which arm carries the
2741    /// subject scalar?" answer lives at one caixa-core edit rather
2742    /// than open-coded across per-consumer `if let WitTarget::PubSub
2743    /// { subject } = c.target()…` pattern-matches.
2744    ///
2745    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2746    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2747    /// the pre-projection [`WitContract::subject`] scalar accessor on
2748    /// the raw `:contratos :subject` field-access axis — same "one
2749    /// typed dispatch on the substrate primitive, thin projections at
2750    /// each consumer" discipline extended onto the per-arm pub-sub
2751    /// post-projection axis. The pre-projection accessor returns
2752    /// `Some` for any author-declared `:subject` value regardless of
2753    /// the paired `:wit` world's pub-sub-shape classification (the raw
2754    /// slot before validation crosses it); this post-projection
2755    /// accessor returns `Some` iff the target has been projected onto
2756    /// the [`Self::PubSub`] arm, i.e. only after the
2757    /// [`WitContract::target`] gate has admitted the
2758    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2759    /// the pre-/post-projection pair on the pub-sub-subject axis to
2760    /// match the pair the [`WitContract::endpoint`] +
2761    /// [`Self::http_endpoint`] surfaces already close on the peer
2762    /// HTTP-endpoint axis.
2763    ///
2764    /// Sibling of the unified pan-arm [`Self::payload`]
2765    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2766    /// extends the per-arm projection family onto the [`Self::PubSub`]
2767    /// specialization axis that the pan-arm accessor's shape blends
2768    /// into a single arm-agnostic view; the pair
2769    /// (`pubsub_subject`, `store_slot`) closes the trio
2770    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2771    /// payload arm now carries its own per-arm-shape post-projection
2772    /// accessor.
2773    #[must_use]
2774    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2775        match *self {
2776            WitTarget::PubSub { subject } => Some(subject),
2777            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2778        }
2779    }
2780
2781    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2782    /// every consumer that fans on the store-shaped payload keys off —
2783    /// returns the [`Self::Store`]-arm's author-declared slot template
2784    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2785    /// projected target is [`Self::Store { slot }`], `None` on the
2786    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2787    /// [`Self::Capability`], each of which carries no
2788    /// key/value-store slot by definition).
2789    ///
2790    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2791    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2792    /// every future substrate-side store-introspecting per-`(:de,
2793    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2794    /// namespace / prefix reconciler's per-slot projection, the future
2795    /// per-store-backend routing overlay's slot-shape gate, the future
2796    /// `feira app graph --store` per-Aplicacao slot column, any future
2797    /// substrate-lifted store-shape emitter that reads a projected
2798    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2799    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2800    /// Every future store-shape consumer reaches for the same typed
2801    /// dispatch this accessor exposes so the "which arm carries the
2802    /// slot scalar?" answer lives at one caixa-core edit rather than
2803    /// open-coded across per-consumer
2804    /// `if let WitTarget::Store { slot } = c.target()…`
2805    /// pattern-matches.
2806    ///
2807    /// Peer of the sibling [`Self::http_endpoint`] +
2808    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2809    /// axes and of the pre-projection [`WitContract::slot`] scalar
2810    /// accessor on the raw `:contratos :slot` field-access axis — same
2811    /// "one typed dispatch on the substrate primitive, thin projections
2812    /// at each consumer" discipline extended onto the per-arm store
2813    /// post-projection axis. Closes the pre-/post-projection pair on
2814    /// the store-slot axis to match the pairs the
2815    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2816    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2817    /// already close on the peer HTTP-endpoint and pub-sub-subject
2818    /// axes; the substrate-side pre-/post-projection accessor family
2819    /// now spans all three payload arms as a matched trio, so any
2820    /// future arm-shape widening (a `Rest`/`Grpc` split of
2821    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2822    /// lands one accessor without threading through the sibling
2823    /// pre-projection or the peer per-arm post-projection surfaces a
2824    /// compile-time exhaustiveness error at the substrate primitive,
2825    /// not a silent per-consumer split at renderer emit time.
2826    ///
2827    /// Sibling of the unified pan-arm [`Self::payload`]
2828    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2829    /// closes the per-arm projection family onto the [`Self::Store`]
2830    /// specialization axis that the pan-arm accessor's shape blends
2831    /// into a single arm-agnostic view. The trio
2832    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2833    /// pan-arm accept-set on every payload-carrying arm: exactly one
2834    /// per-arm accessor returns `Some(payload)` and the two peers
2835    /// return `None`, and every payload-less [`Self::Capability`]
2836    /// input returns `None` on all three — the partition the sibling
2837    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2838    /// pin locks in load-bearing.
2839    #[must_use]
2840    pub const fn store_slot(&self) -> Option<&'a str> {
2841        match *self {
2842            WitTarget::Store { slot } => Some(slot),
2843            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2844        }
2845    }
2846
2847    /// Render this typed target as a stable human-readable label
2848    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2849    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2850    /// the WIT world is a pure capability edge).
2851    ///
2852    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2853    /// gate so the diagnostic names *which* identical edge was
2854    /// declared twice (not just which `(de, para, wit)` triple).
2855    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2856    /// on the payload-carrying arms (`Some((field, payload)) →
2857    /// format!(":{field} {payload:?}")`) and through the lifted
2858    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2859    /// [`Self::Capability`] arm — so a future variant addition (the
2860    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2861    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2862    /// `Queue`-shaped peer) becomes a single new match-arm on
2863    /// [`Self::payload_pair`] rather than a rewrite of this template
2864    /// (and every downstream consumer that reaches for the label
2865    /// shape: the per-edge policy resolver in M4, the `feira app
2866    /// graph` view, the operator's mesh-graph audit). Until this
2867    /// lift landed the three payload arms carried three near-identical
2868    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2869    /// [`Self::Capability`] arm carried the payload-less byte-string
2870    /// twice (once inline here, once in the pin test) — closing the
2871    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2872    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2873    /// / 4a1e490) peer-const lifts already established for the
2874    /// payload-carrying arms.
2875    #[must_use]
2876    pub fn label(&self) -> String {
2877        match self.payload_pair() {
2878            Some((field, payload)) => format!(":{field} {payload:?}"),
2879            None => Self::CAPABILITY_LABEL.to_string(),
2880        }
2881    }
2882
2883    /// Render this typed target as the `feira app graph` per-`:contratos`
2884    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2885    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2886    /// payload-less arm).
2887    ///
2888    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2889    /// on the payload-carrying arms (`Some((field, payload)) →
2890    /// format!("{field}={payload}")`) and through the lifted
2891    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2892    /// [`Self::Capability`] arm — so a future variant addition
2893    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2894    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2895    /// `Queue`-shaped peer) becomes one match-arm edit at
2896    /// [`Self::payload_pair`], propagating through this graph-verb
2897    /// projection at zero call-site cost, sibling to the peer
2898    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2899    /// same 4-arm dispatch.
2900    ///
2901    /// Until this lift landed the [`caixa-feira`]
2902    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2903    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2904    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2905    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2906    /// `format!("{}={endpoint}", ...)` template and hard-coding
2907    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2908    /// back to the paired [`WitTarget::Capability`] variant declaration.
2909    /// A future variant addition would have had to be threaded through
2910    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2911    /// verb's inline match in lockstep or the two projections would
2912    /// silently disagree on the arm-set the graph verb prints — the
2913    /// duplicate-`:contratos` diagnostic reading one shape while the
2914    /// graph verb's payload column silently dropped the new arm to
2915    /// `(capability-only)`. Lifting the graph-verb projection onto the
2916    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2917    /// the axis: both projections migrate as a unit.
2918    ///
2919    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2920    /// quoting) shape is graph-verb-canonical — distinct from the
2921    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2922    /// duplicate-`:contratos` diagnostic seeds (see
2923    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2924    /// on the payload-less axis for the paired distinction).
2925    #[must_use]
2926    pub fn graph_label(&self) -> String {
2927        match self.payload_pair() {
2928            Some((field, payload)) => format!("{field}={payload}"),
2929            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2930        }
2931    }
2932}
2933
2934/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2935/// pretty-printed byte-string every consumer that formats a typed
2936/// payload target as user-facing text lands on (the
2937/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2938/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2939/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2940/// graph` per-`:contratos`-edge payload column that reaches the graph
2941/// verb through `format!("{target}")`, the future M4 per-edge policy
2942/// resolver's per-edge audit-log line, the operator's mesh-graph
2943/// per-edge inspection view) reaches for the same lifted
2944/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2945/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2946/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2947/// routes through — extending the three-path-convergence
2948/// (`Debug` for structural inspection, `Display` for user-facing text,
2949/// per-arm typed accessor for the canonical byte-string) discipline the
2950/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2951/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2952/// onto the fourth (and only remaining) typed-shape-discriminator axis
2953/// on the caixa surface.
2954///
2955/// Pre-lift the two paths were structurally independent — every consumer
2956/// reaching for a payload byte-string past the [`WitTarget::label`]
2957/// helper had to pick between three paths ([`WitTarget::label`],
2958/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2959/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2960/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2961/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2962/// that reached for `format!("{target}")` — the canonical shape every
2963/// user-facing pretty-print site on the sibling typed-enum axes already
2964/// uses — would silently land on the `Debug` derive's structural output
2965/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2966/// than the `label()` helper's stable byte-string (`:endpoint
2967/// "/charge"` — the author-facing `:contratos` keyword form) the
2968/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2969/// already threads through. The two spellings would diverge silently in
2970/// every downstream diagnostic / graph / audit line reached through
2971/// `format!` rather than through the `label()` helper. Routing
2972/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2973/// path: every `format!("{v}")` call reaches the same
2974/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2975/// and the duplicate-`:contratos` gate already route through, so a
2976/// future variant addition (the M4-and-later per-edge WIT registry may
2977/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2978/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2979/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2980/// match — rather than fanning out through hand-rolled per-arm
2981/// [`std::fmt::Display`] arms.
2982///
2983/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2984/// is the typed view returned by [`WitContract::target`], not a
2985/// closed-set discriminator enum with a gen-platform Discriminant
2986/// registration, so the `Debug` derive's structural output (which every
2987/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2988/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2989/// shape for structural inspection; `Display` (via `label`) reveals the
2990/// stable author-facing payload projection.
2991///
2992/// Pin tests
2993/// [`tests::wit_target_display_routes_through_label_helper`] and
2994/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2995/// assert the two paths agree byte-for-byte on every variant, so a
2996/// future variant addition or `label()` reimplementation that hand-rolls
2997/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2998/// build error visible at caixa-core test time, not a silent
2999/// per-consumer dispatch miss at diagnostic / audit / graph time.
3000impl std::fmt::Display for WitTarget<'_> {
3001    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3002        f.write_str(&self.label())
3003    }
3004}
3005
3006// ── one Aplicacao member ─────────────────────────────────────────────
3007
3008/// A Servico participating in the Aplicacao. Same shape as
3009/// `crate::supervisor::ChildSpec` but without a restart policy —
3010/// supervision is per-Servico (each member has its own
3011/// `:supervisor`), the Aplicacao orchestrates *placement*.
3012#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3013#[serde(rename_all = "camelCase")]
3014pub struct Membro {
3015    /// Member caixa's `:nome`. Resolves through the same dep
3016    /// resolution path as `crate::dep::Dep`.
3017    pub caixa: String,
3018
3019    /// Semver constraint.
3020    pub versao: String,
3021}
3022
3023impl Membro {
3024    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
3025    /// accessor every consumer that reads the member's Servico identity
3026    /// keys off — returns the author-declared `:membros :caixa`
3027    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
3028    /// own [`String`] storage.
3029    ///
3030    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
3031    /// participating in the Aplicacao — validated by
3032    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
3033    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
3034    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
3035    /// [`validate_no_self_membership`]) — and every downstream consumer
3036    /// that fans on the member's identity keys off this scalar (the
3037    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
3038    /// lookup, the per-`:membros` duplicate gate's dedup key, the
3039    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
3040    /// identity, the self-membership gate, the
3041    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
3042    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
3043    /// CR materializer's per-member resolver).
3044    ///
3045    /// Prior to this lift the `.caixa` byte-string was read inline at
3046    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
3047    /// set collector at
3048    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
3049    /// [`validate_membros`] validation-side member-caixa gate at
3050    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
3051    /// per-member duplicate-gate dedup key at
3052    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
3053    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
3054    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
3055    /// [`validate_no_self_membership`] self-loop gate at
3056    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
3057    /// expressed no compile-time link back to the typed slot. Every
3058    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
3059    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
3060    /// `name:` axis, so a future extension of the `:membros :caixa`
3061    /// axis to a richer author surface — a per-cluster alias table the
3062    /// operator pins through a future `:placement`-scoped slot, a
3063    /// namespace-qualified rewrite the M4 CR materializer applies
3064    /// per-CR, a per-member overlay from the future `:membros
3065    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
3066    /// acknowledges — would have had to be threaded through every
3067    /// open-coded copy in lockstep or one consumer would silently
3068    /// disagree with the peers on which caixa a given member resolves
3069    /// to. A member-set lookup that treated the name as `"cart"` while
3070    /// the peer adjacency map treated it as `"tenant-a/cart"` would
3071    /// silently split the `:contratos` membership-lookup diagnostic from
3072    /// the cycle-detector's node identity — a two-consumer split at the
3073    /// validator far from the source `caixa.lisp` with no field naming
3074    /// the identity-drift root cause. Lifting the resolution rule to a
3075    /// typed method on the substrate primitive means every downstream
3076    /// consumer of the Aplicacao's per-`:membros` identity surface
3077    /// reaches for exactly one typed dispatch — the resolver's
3078    /// accept-set migrates as a unit on any future axis addition.
3079    ///
3080    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
3081    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
3082    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
3083    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
3084    /// destination-Servico scalar accessors — same "one typed dispatch
3085    /// on the substrate primitive, thin projections at each consumer"
3086    /// discipline extended onto the per-`:membros` member-caixa `:nome`
3087    /// byte-string axis. Named `nome()` to match the tatara-lisp
3088    /// author-surface term the field's docstring already reaches for
3089    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
3090    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
3091    /// already carries — the accessor's name maps directly onto the
3092    /// canonical caixa-identity vocabulary rather than shadowing the
3093    /// field's storage-side `caixa` label.
3094    #[must_use]
3095    pub const fn nome(&self) -> &str {
3096        self.caixa.as_str()
3097    }
3098
3099    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
3100    /// requirement scalar accessor every consumer that reads the
3101    /// member's version pin keys off — returns the author-declared
3102    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
3103    /// from the typed slot's own [`String`] storage.
3104    ///
3105    /// The `:membros :versao` slot carries the Cargo-shaped semver
3106    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
3107    /// pins which release of the member-caixa the Aplicacao composes
3108    /// against — the same requirement grammar the peer `:deps :versao`
3109    /// / `:children :versao` axes carry, resolved through the shared
3110    /// [`crate::render::require_valid_versao_requirement`] cascade and
3111    /// the shared [`crate::version::parse_requirement`] parser. Every
3112    /// downstream consumer that fans on the member's version pin keys
3113    /// off this scalar (the [`validate_membros`] per-member requirement
3114    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
3115    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
3116    /// m.nome(), m.versao_requirement())` line, every future per-cluster
3117    /// version-lock overlay the operator pins through a future
3118    /// `:placement`-scoped slot, the future
3119    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
3120    /// version resolver, the future `feira app deploy` pipeline's
3121    /// per-member lacre BLAKE3-closure lookup).
3122    ///
3123    /// Prior to this lift the `.versao` byte-string was accessed inline
3124    /// at two `&str`-shaped sites — the [`validate_membros`]
3125    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
3126    /// …)` and the `feira app graph` per-member printer's `println!(
3127    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
3128    /// prior to this lift) — two open-coded field-accesses that expressed
3129    /// no compile-time link back to the typed slot. A future extension of
3130    /// the `:membros :versao` axis to a richer author surface (a
3131    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
3132    /// flow, a lacre-projected concrete-version rewrite the operator
3133    /// materializes at CR-admission time, a future `:membros :versao-lock`
3134    /// per-cluster override slot) would have had to be threaded through
3135    /// every open-coded copy in lockstep or one consumer would silently
3136    /// disagree with the peers on which release constraint a given
3137    /// member resolves to. Lifting the resolution rule to a typed method
3138    /// on the substrate primitive means every downstream requirement-
3139    /// facing consumer reaches for exactly one typed dispatch — the
3140    /// resolver's accept-set migrates as a unit on any future axis
3141    /// addition.
3142    ///
3143    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
3144    /// member-caixa `:nome` scalar accessor — the pair
3145    /// `(nome(), versao_requirement())` jointly projects the
3146    /// `(caixa, versao)` field pair every renderer that fans on
3147    /// per-member identity + version pin keys off, closing the last
3148    /// unlifted per-`:membros` scalar axis so every downstream
3149    /// per-`:membros` reader now routes through a typed dispatch on the
3150    /// substrate primitive. Named `versao_requirement()` rather than
3151    /// `versao()` because the field's storage-side `.versao` label is
3152    /// already the author-surface term (`:versao`); the accessor's name
3153    /// carries the semantic role — the semver *requirement* string the
3154    /// shared [`crate::version::parse_requirement`] entry-point consumes
3155    /// — so a raw field access and a typed dispatch read differently at
3156    /// every consumer site.
3157    ///
3158    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
3159    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
3160    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
3161    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
3162    /// destination-Servico scalar accessors — same "one typed dispatch
3163    /// on the substrate primitive, thin projections at each consumer"
3164    /// discipline extended onto the per-`:membros` member-`:versao`
3165    /// semver-requirement byte-string axis.
3166    #[must_use]
3167    pub const fn versao_requirement(&self) -> &str {
3168        self.versao.as_str()
3169    }
3170}
3171
3172// ── mesh-level policies ──────────────────────────────────────────────
3173
3174/// Mesh policies that apply to every `:contratos` edge unless
3175/// overridden per-edge in M4. V0 is a single global policy block.
3176#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3177#[serde(rename_all = "camelCase")]
3178pub struct MeshPolicy {
3179    /// Per-call timeout. Authored as a duration string (`"30s"`).
3180    #[serde(
3181        default,
3182        skip_serializing_if = "Option::is_none",
3183        with = "supervisor::duration_codec"
3184    )]
3185    pub timeout: Option<Duration>,
3186
3187    /// Number of retries on transient failure. None = no retries.
3188    #[serde(default, skip_serializing_if = "Option::is_none")]
3189    pub retries: Option<u32>,
3190
3191    /// Circuit breaker config. Trips after N failures within W
3192    /// duration; closes after a cooldown.
3193    #[serde(default, skip_serializing_if = "Option::is_none")]
3194    pub circuit_breaker: Option<CircuitBreaker>,
3195
3196    /// Whether mTLS is required for every contrato. Default: true
3197    /// (sandboxing-by-default; explicit opt-out only).
3198    #[serde(default, skip_serializing_if = "Option::is_none")]
3199    pub mtls_required: Option<bool>,
3200
3201    /// Token-bucket rate limit. Authored as `"100/s"` or
3202    /// `"5000/m"`; stored as `(rate, window)`.
3203    #[serde(
3204        default,
3205        skip_serializing_if = "Option::is_none",
3206        with = "rate_limit_codec"
3207    )]
3208    pub rate_limit: Option<RateLimit>,
3209}
3210
3211/// Route the derived-style [`Default`] impl on [`MeshPolicy`] through
3212/// the substrate-canonical [`MeshPolicy::empty`] `pub const fn`
3213/// constructor rather than the derive-generated per-field
3214/// `<Option<_> as Default>::default` cascade — one source of truth for
3215/// the "canonical unset per-`:politicas` slot" shape across the two
3216/// paths every downstream consumer already reaches through (the
3217/// derived-until-now [`Default::default`] the `..Default::default()`
3218/// struct-update-syntax on every one-axis-under-test fixture in this
3219/// crate's test module rests on, and the `pub const fn`
3220/// [`MeshPolicy::empty`] constructor every `const`-context consumer
3221/// reaches through).
3222///
3223/// Prior to this fold the two paths were byte-equal by *coincidence*
3224/// under the pinning test
3225/// [`tests::mesh_policy_empty_byte_equals_default`] rather than
3226/// byte-equal by *construction* — the derive-generated
3227/// [`Default::default`] resolved each `Option<_>` field through its
3228/// own `<Option<_> as Default>::default` (which returns `None`) and
3229/// the lifted `pub const fn` [`MeshPolicy::empty`] named the same five
3230/// `None` arms verbatim in its struct-literal. Two hand-authored (or
3231/// derive-authored) sources of the same "canonical unset baseline"
3232/// shape on the same primitive is exactly the substrate-canonical-
3233/// source-of-truth duplication the [`crate::LimitsSpec::empty`]
3234/// (9739971) / [`MeshPolicy::empty`] (6df969b) /
3235/// [`crate::BehaviorSpec::empty`] (f9b18e3) lifts closed on the
3236/// forward `const`-context path — extending the same discipline onto
3237/// the paired [`Default`] impl means every consumer of the derived-
3238/// until-now [`Default::default`] surface (every `..Default::default()`
3239/// struct-update-syntax fixture in this crate's test module — the
3240/// five per-axis-only pins at [`tests::mesh_policy_with_only_timeout_is_not_empty`],
3241/// [`tests::mesh_policy_with_only_retries_is_not_empty`],
3242/// [`tests::mesh_policy_with_only_circuit_breaker_is_not_empty`],
3243/// [`tests::mesh_policy_with_only_mtls_required_is_not_empty`],
3244/// [`tests::mesh_policy_with_only_rate_limit_is_not_empty`] — and the
3245/// entry pin at [`tests::mesh_policy_default_is_empty`], the future
3246/// M4 per-edge `:politicas` overlay CR materializer's admission-time
3247/// default-overlay-emit gate, every future `..Default::default()`
3248/// struct-update-syntax fixture-builder arm) also routes through the
3249/// substrate primitive's single source of truth.
3250///
3251/// A future extension of the `:politicas` axis set (a per-edge
3252/// `:politicas` overlay the M4 roadmap grows once per-`:contratos`-
3253/// edge overrides land, a sixth `:politicas` sub-slot the roadmap
3254/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3255/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3256/// reaches this impl's return value through exactly one edit on
3257/// [`MeshPolicy::empty`] — the derived path could silently disagree
3258/// with the constructor's shape on any new field whose
3259/// `Default::default` is not `None` (a future non-`Option<_>` field
3260/// with a non-`Default::default`-equivalent baseline, a `Vec<_>` field
3261/// defaulting to an empty vector, an enum arm-carrying field with a
3262/// non-`Default::default` canonical unset arm), while this delegated
3263/// impl reaches the constructor directly and picks up every future
3264/// extension by construction.
3265///
3266/// Direct peer of [`crate::LimitsSpec`]'s
3267/// [`Default`]-through-[`crate::LimitsSpec::empty`] fold (abd52c2) on
3268/// the M2 `:limits` typed slot — same "one source of truth for the
3269/// canonical unset baseline" discipline extended onto the M3
3270/// `:politicas` typed slot. The sibling [`crate::BehaviorSpec`] impl
3271/// on the M2 `:behavior` slot is the third and last established
3272/// candidate for the same delegation fold once the per-slot peer pin
3273/// on this axis lands in a future run. Pinned load-bearing by
3274/// [`tests::mesh_policy_default_routes_through_empty_ctor`]
3275/// (byte-parity pin against [`MeshPolicy::empty`] under `PartialEq`,
3276/// sharpening the pre-existing
3277/// [`tests::mesh_policy_empty_byte_equals_default`] pin from a "two
3278/// paths byte-equal by coincidence" invariant into a "two paths
3279/// byte-equal by construction — one delegates to the other" invariant)
3280/// and by [`tests::mesh_policy_empty_validates_ok`] (the canonical
3281/// unset baseline must pass [`MeshPolicy::validate`] — every per-axis
3282/// value-shape gate is `if let Some(_)` guarded and every cross-axis
3283/// arm on [`MeshPolicy::first_cross_axis_violation`] is a
3284/// `let (Some(_), Some(_))` pattern, so an all-`None` input
3285/// structurally short-circuits every arm; the pin makes the invariant
3286/// load-bearing so a future extension that adds a non-`Option`-guarded
3287/// gate to [`MeshPolicy::validate`] trips at caixa-core test time
3288/// rather than at a downstream consumer that composed
3289/// [`MeshPolicy::default`]/[`MeshPolicy::empty`] with
3290/// [`MeshPolicy::validate`] as its "no-op axis short-circuit").
3291impl Default for MeshPolicy {
3292    #[inline]
3293    fn default() -> Self {
3294        Self::empty()
3295    }
3296}
3297
3298impl MeshPolicy {
3299    /// Substrate-canonical `const`-context peer of the derived
3300    /// [`Default::default`] on [`MeshPolicy`] — returns the fully-empty
3301    /// per-`:politicas` slot (every one of the five `Option<_>`-carrying
3302    /// per-axis fields set to `None`), materializable at `const`-eval
3303    /// time.
3304    ///
3305    /// Named `empty()` (not `default()` / `new()`) to match the sibling
3306    /// `is_empty()` predicate on the same primitive: the pair
3307    /// (`empty()` / `is_empty()`) forms the round-trip discipline
3308    /// `MeshPolicy::empty().is_empty() == true` the pin
3309    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3310    /// locks load-bearing, and every `const`-context consumer that
3311    /// wants a canonical unset baseline reads through this constructor
3312    /// rather than the derived (non-`const`) [`Default::default`] or
3313    /// the five-field struct-literal `MeshPolicy { timeout: None,
3314    /// retries: None, circuit_breaker: None, mtls_required: None,
3315    /// rate_limit: None }` open-coded per-site.
3316    ///
3317    /// Direct peer of [`crate::LimitsSpec::empty`] (9739971) on the
3318    /// M2 `:limits` typed slot — same "`const`-context peer of the
3319    /// derived non-`const` [`Default::default`]" discipline extended
3320    /// onto the M3 `:politicas` typed slot. The two lifted `pub const
3321    /// fn` constructors together now cover the two per-slot
3322    /// [`Default`]-carrying M2/M3 typed slots that also carry an
3323    /// `is_empty()` emptiness predicate: every `const`-context consumer
3324    /// of a canonical unset per-slot baseline reads through the same
3325    /// paired-`(empty(), is_empty())` shape on either slot without a
3326    /// runtime dispatch on the derived [`Default::default`].
3327    ///
3328    /// Prior to this lift the "canonical unset [`MeshPolicy`]" shape
3329    /// was reached through one of two paths — the derived
3330    /// [`Default::default`] (`fn`, not `const fn` — a downstream
3331    /// `const _: MeshPolicy = MeshPolicy::default();` cannot compile
3332    /// because [`Default::default`] is not `const`-stable on stable
3333    /// Rust; the tracking issue on `const Default` still blocks the
3334    /// promotion) or an open-coded struct-literal with five `None`
3335    /// arms threaded verbatim at every call site (the five
3336    /// `MeshPolicy { timeout: Some(_), ..Default::default() }` /
3337    /// `MeshPolicy { retries: Some(_), ..Default::default() }` /
3338    /// sibling per-axis-only fixtures in this crate's own test module
3339    /// each rest on `..Default::default()` for the four peer arms; a
3340    /// future axis addition silently drifts the fixture's intent from
3341    /// "one axis under test, the other four unset" to "one axis under
3342    /// test, N axes unset, one field forgotten"). A future extension
3343    /// of the axis (a per-edge `:politicas` overlay the M4 roadmap
3344    /// grows once per-`:contratos`-edge overrides land, a sixth
3345    /// `:politicas` sub-slot the roadmap
3346    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3347    /// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3348    /// reaches this constructor at one edit (one added struct field
3349    /// on the type + one added `<axis>: None` line here) rather than
3350    /// a coordinated rewrite of every open-coded struct-literal at
3351    /// every downstream consumer.
3352    ///
3353    /// `pub const fn` — matches the sibling
3354    /// [`MeshPolicy::is_empty`] `pub const fn` shape verbatim, so
3355    /// every downstream consumer that folds a canonical unset
3356    /// baseline into a `const` position (a `const EMPTY: MeshPolicy =
3357    /// MeshPolicy::empty();` module-scope binding a future per-edge
3358    /// `:politicas` overlay reads through as its "no override
3359    /// declared" arm, a compile-time per-fixture-builder default the
3360    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3361    /// admission-time default-overlay-emit gate consults, a
3362    /// compile-time lookup table the LSP hover renderer materializes
3363    /// per typed-slot fixture) reads through one `const` dispatch
3364    /// rather than being forced onto the runtime code path. Pinned
3365    /// load-bearing at the substrate-primitive level by
3366    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3367    /// (round-trip pin against [`Self::is_empty`]),
3368    /// [`tests::mesh_policy_empty_byte_equals_default`] (byte-parity
3369    /// pin against the derived [`Default::default`]), and
3370    /// [`tests::mesh_policy_empty_ctor_is_const_fn`] (const-eval-surface
3371    /// pin via `const` binding — any future accidental downgrade to
3372    /// `pub fn` fires E0015 at the binding at caixa-core build time,
3373    /// strictly stronger than a runtime `assert!`).
3374    #[must_use]
3375    pub const fn empty() -> Self {
3376        Self {
3377            timeout: None,
3378            retries: None,
3379            circuit_breaker: None,
3380            mtls_required: None,
3381            rate_limit: None,
3382        }
3383    }
3384
3385    /// True when no `:politicas` axis carries a value — every field is
3386    /// `None`. The same emptiness contract every other M2/M3 typed
3387    /// surface carries ([`crate::LimitsSpec::is_empty`],
3388    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
3389    /// typed slot onto a cluster artifact key off this predicate to
3390    /// decide "emit the slot" vs "skip the slot entirely", so an
3391    /// authored-but-unset `:politicas (())` round-trips to a rendered
3392    /// artifact that's structurally identical to one that omits the
3393    /// slot. Lifted as a typed predicate (rather than per-renderer
3394    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
3395    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
3396    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
3397    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
3398    /// not a coordinated rewrite of every consumer that's reaching
3399    /// for the emptiness semantic.
3400    #[must_use]
3401    pub const fn is_empty(&self) -> bool {
3402        self.timeout().is_none()
3403            && self.retries().is_none()
3404            && self.circuit_breaker().is_none()
3405            && self.mtls_required().is_none()
3406            && self.rate_limit().is_none()
3407    }
3408
3409    /// Substrate-canonical cross-axis coherence predicate on the
3410    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
3411    /// failure-observation interval span at least one full
3412    /// `:timeout`-bounded call?
3413    ///
3414    /// The first *cross-axis* invariant on the `:politicas` surface —
3415    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
3416    /// zero-floor + canonical-form + cap brackets) validates one axis
3417    /// in isolation, so a `MeshPolicy` whose axes are each individually
3418    /// well-formed could still name a structurally inert pair. The
3419    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
3420    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
3421    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
3422    /// both above the zero floor) and is nonetheless a breaker that
3423    /// cannot trip on the failure mode it exists to catch: a call
3424    /// dispatched at t=0 is declared failed at t=30s, by which point
3425    /// the 10s window open at dispatch has rolled twice over, so no
3426    /// window can ever hold even one timeout-derived failure however
3427    /// high the call volume. Envoy's `outlier_detection.interval`
3428    /// carries the identical relation against the per-route request
3429    /// timeout; Hystrix ships the canonical ratio in its defaults
3430    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
3431    /// `execution.isolation.thread.timeoutInMilliseconds`).
3432    ///
3433    /// Vacuously `true` when either axis is absent — a `:politicas`
3434    /// that names only one of the pair declares no relation for the
3435    /// substrate to hold it to (`:timeout` alone is a per-call deadline
3436    /// with no breaker; `:circuit-breaker` alone is a breaker whose
3437    /// failures arrive from the transport's own error signal rather
3438    /// than from a substrate-imposed deadline, so no dispatch-to-report
3439    /// lag is knowable at author time). This is the same
3440    /// "unset means the cluster default applies, not zero" partition
3441    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
3442    /// arm already carry.
3443    ///
3444    /// Lifted as a typed predicate on the substrate primitive rather
3445    /// than open-coded at the validate gate so every downstream
3446    /// consumer of the pair reaches the invariant through one dispatch:
3447    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3448    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3449    /// (MESH-COMPOSITION §III.2 #3) that must emit
3450    /// `outlier_detection.interval` and the per-route `timeout` as one
3451    /// coherent Envoy block, the future M4
3452    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3453    /// webhook, and the future per-`:contratos`-edge `:politicas`
3454    /// override that same roadmap acknowledges — which resolves an
3455    /// *effective* pair per edge (edge-level `:timeout` against the
3456    /// Aplicacao-level `:window`, or vice versa) and so must re-check
3457    /// the relation on a pair neither axis's declaration site can see
3458    /// whole. Naming the invariant once means that resolver folds this
3459    /// predicate over its resolved pair instead of re-deriving the
3460    /// comparison, exactly as the sibling cross-slot
3461    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
3462    /// `:placement`/`:shard-key` relation for its own consumers.
3463    #[must_use]
3464    pub const fn breaker_window_observes_timeout(&self) -> bool {
3465        match (self.timeout(), self.circuit_breaker()) {
3466            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
3467            _ => true,
3468        }
3469    }
3470
3471    /// Substrate-canonical cross-axis coherence predicate on the
3472    /// `:politicas` slot: can the token-bucket rate declared by
3473    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
3474    /// :window` to reach `:max-failures`?
3475    ///
3476    /// The second cross-axis invariant on the `:politicas` surface —
3477    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3478    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
3479    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
3480    /// pair is validated in isolation by the per-axis brackets in
3481    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
3482    /// max-failures zero-floor + cap, both windows zero-floor +
3483    /// integer-millisecond + cap, rate-limit window canonical-form),
3484    /// so a `MeshPolicy` whose axes are each individually well-formed
3485    /// can still name a structurally inert pair. The pair
3486    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
3487    /// "10s") }` passes every per-axis bracket and is nonetheless a
3488    /// breaker that cannot trip on the failure mode it exists to
3489    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
3490    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
3491    /// no window can accumulate five failures however catastrophically
3492    /// the upstream is failing. Envoy's
3493    /// `outlier_detection.consecutive_5xx` paired against
3494    /// `local_rate_limit.token_bucket.max_tokens` /
3495    /// `fill_interval` carries the identical relation; every
3496    /// production playbook that pairs the two axes (Envoy, Istio, AWS
3497    /// App Mesh, Kong) recommends sizing the rate at or above the
3498    /// breaker's minimum-request-volume threshold for exactly this
3499    /// reason.
3500    ///
3501    /// The typed test is the integer inequality
3502    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
3503    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
3504    /// so no floating-point division mediates the comparison and so
3505    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
3506    /// exactly). Both multiplicands are `saturating_mul`'d into
3507    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
3508    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
3509    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
3510    /// panic the predicate; a saturated pair collapses to the
3511    /// "vacuously coherent" branch the peer per-axis brackets reject
3512    /// via their own zero-floor / cap arms first.
3513    ///
3514    /// Vacuously `true` when either axis is absent — a `:politicas`
3515    /// that names only one of the pair declares no relation for the
3516    /// substrate to hold it to (`:rate-limit` alone is a per-edge
3517    /// token-bucket declaration with no failure counter to starve;
3518    /// `:circuit-breaker` alone is a rolling-window failure counter
3519    /// whose call rate is unconstrained by the substrate, so no
3520    /// bucket-derived upper bound on calls-per-window is knowable at
3521    /// author time). Same "unset means the cluster default applies,
3522    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
3523    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3524    /// carry.
3525    ///
3526    /// Lifted as a typed predicate on the substrate primitive rather
3527    /// than open-coded at the validate gate so every downstream
3528    /// consumer of the pair reaches the invariant through one
3529    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3530    /// below, the future `CiliumClusterwideEnvoyConfig`
3531    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3532    /// must emit `local_rate_limit.token_bucket.{max_tokens,
3533    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
3534    /// / `outlier_detection.interval` as one coherent Envoy block,
3535    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3536    /// materializer's admission webhook, and the future
3537    /// per-`:contratos`-edge `:politicas` override the same roadmap
3538    /// acknowledges — which resolves an *effective* pair per edge
3539    /// (edge-level `:rate-limit` against the Aplicacao-level
3540    /// `:circuit-breaker`, or vice versa) and so must re-check the
3541    /// relation on a pair neither axis's declaration site can see
3542    /// whole. Naming the invariant once means that resolver folds
3543    /// this predicate over its resolved pair instead of re-deriving
3544    /// the comparison, exactly as the sibling cross-axis
3545    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3546    /// names the `(:timeout, :window)` relation for its own consumers.
3547    #[must_use]
3548    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
3549        match (self.rate_limit(), self.circuit_breaker()) {
3550            (Some(rl), Some(cb)) => {
3551                let calls_per_cb_window =
3552                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
3553                let trip_threshold_per_cb_window =
3554                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
3555                calls_per_cb_window >= trip_threshold_per_cb_window
3556            }
3557            _ => true,
3558        }
3559    }
3560
3561    /// Substrate-canonical cross-axis coherence predicate on the
3562    /// `:politicas` slot: can one client's declared `:retries` all
3563    /// complete before `:circuit-breaker :max-failures` trips the
3564    /// breaker mid-retry?
3565    ///
3566    /// The third cross-axis invariant on the `:politicas` surface —
3567    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3568    /// the `(:timeout, :circuit-breaker :window)` pair and
3569    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3570    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
3571    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
3572    /// the pair is validated in isolation by the per-axis brackets in
3573    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3574    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
3575    /// are each individually well-formed can still name a
3576    /// structurally-inert retry policy. The pair
3577    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
3578    /// passes every per-axis bracket and is nonetheless a retry
3579    /// policy the substrate cannot honor: one client's initial attempt
3580    /// plus three retries is four attempts, but the breaker trips on
3581    /// the third failure — the fourth attempt (the last declared
3582    /// retry) is blocked by the open breaker, so the substrate
3583    /// declared four attempts and structurally allows three.
3584    ///
3585    /// The typed test is the integer inequality
3586    /// `cb.max_failures() > retries` — the retries count is the
3587    /// *number of retry attempts beyond the initial* (Envoy's
3588    /// `retry_policy.num_retries` semantics), so a client makes at
3589    /// most `retries + 1` attempts per client call, each of which may
3590    /// fail. For the breaker to *admit* the retry policy through
3591    /// completion, its trip threshold must not be reached by one
3592    /// client's failures alone: `retries + 1 <= max_failures`,
3593    /// equivalently `retries < max_failures`, equivalently
3594    /// `max_failures > retries`. The boundary case
3595    /// `max_failures == retries + 1` accepts (the R+1th failure — the
3596    /// last retry — trips the breaker exactly as it completes; retries
3597    /// are fully executed). The strict-below case
3598    /// `max_failures <= retries` rejects (the breaker trips before
3599    /// retries exhaust, silently truncating the declared retry policy
3600    /// mid-run — the same declared-but-structurally-inert footgun the
3601    /// sibling per-axis cap arms close on the single-axis surfaces).
3602    ///
3603    /// Vacuously `true` when either axis is absent — a `:politicas`
3604    /// that names only one of the pair declares no relation for the
3605    /// substrate to hold it to (`:retries` alone is a client-retry
3606    /// policy with no failure counter to trip; `:circuit-breaker`
3607    /// alone is a failure counter whose per-client attempt count is
3608    /// unconstrained by the substrate, so no per-client saturation
3609    /// bound on failures-per-client-call is knowable at author time).
3610    /// Same "unset means the cluster default applies, not zero"
3611    /// partition [`MeshPolicy::is_empty`] and the sibling
3612    /// [`MeshPolicy::breaker_window_observes_timeout`] /
3613    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3614    /// carry.
3615    ///
3616    /// Lifted as a typed predicate on the substrate primitive rather
3617    /// than open-coded at the validate gate so every downstream
3618    /// consumer of the pair reaches the invariant through one
3619    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3620    /// below, the future `CiliumClusterwideEnvoyConfig`
3621    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3622    /// must emit `retry_policy.num_retries` alongside
3623    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
3624    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3625    /// materializer's admission webhook, and the future
3626    /// per-`:contratos`-edge `:politicas` override the same roadmap
3627    /// acknowledges — which resolves an *effective* pair per edge
3628    /// (edge-level `:retries` against the Aplicacao-level
3629    /// `:circuit-breaker`, or vice versa) and so must re-check the
3630    /// relation on a pair neither axis's declaration site can see
3631    /// whole. Naming the invariant once means that resolver folds
3632    /// this predicate over its resolved pair instead of re-deriving
3633    /// the comparison, exactly as the sibling cross-axis
3634    /// [`MeshPolicy::breaker_window_observes_timeout`] and
3635    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3636    /// name the `(:timeout, :window)` and `(:rate-limit,
3637    /// :circuit-breaker)` relations for their own consumers.
3638    #[must_use]
3639    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
3640        match (self.retries(), self.circuit_breaker()) {
3641            (Some(retries), Some(cb)) => cb.max_failures() > retries,
3642            _ => true,
3643        }
3644    }
3645
3646    /// Substrate-canonical cross-axis coherence predicate on the
3647    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
3648    /// admit one client's full `:retries + 1` attempt burst inside a
3649    /// single refill window?
3650    ///
3651    /// The fourth cross-axis invariant on the `:politicas` surface,
3652    /// completing the triangle of pairs the three sibling gates carve
3653    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
3654    /// on the `(:timeout, :circuit-breaker :window)` pair,
3655    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3656    /// `(:rate-limit, :circuit-breaker)` pair, and
3657    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
3658    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
3659    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
3660    /// among the three scalar `:politicas` axes (`:retries`,
3661    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
3662    /// coherence surface every production overlay (Envoy, Istio,
3663    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
3664    /// the pair is validated in isolation by the per-axis brackets in
3665    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3666    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
3667    /// whose axes are each individually well-formed can still name a
3668    /// structurally-truncated retry policy the rate limiter refuses to
3669    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
3670    /// per-axis bracket and is nonetheless a retry policy the substrate
3671    /// cannot honor: one client's initial attempt plus five retries is
3672    /// six attempts, but the token bucket admits at most three tokens
3673    /// per one-second refill window, so the fourth attempt onward is
3674    /// blocked by the rate limiter itself — the substrate declared six
3675    /// attempts and structurally allows three. Envoy's
3676    /// `local_rate_limit.token_bucket.max_tokens` paired against
3677    /// `retry_policy.num_retries` carries the identical relation; every
3678    /// production playbook that pairs the two axes recommends sizing
3679    /// the bucket capacity above any single client's retry budget so
3680    /// the retry policy is not silently truncated by the same rate
3681    /// limiter it feeds through.
3682    ///
3683    /// The typed test is the integer inequality
3684    /// `rl.rate() >= retries + 1` — the retries count is the *number of
3685    /// retry attempts beyond the initial* (Envoy's
3686    /// `retry_policy.num_retries` semantics), so a client makes at most
3687    /// `retries + 1` attempts per client call, each of which consumes
3688    /// one token from the local rate-limit bucket. For the bucket to
3689    /// *admit* the retry burst without dropping tokens, its capacity
3690    /// must not be reached by one client's attempts alone:
3691    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
3692    /// boundary case `rate == retries + 1` accepts (the bucket admits
3693    /// exactly one client's full retry sequence per refill window —
3694    /// retries fully executed). The strict-below case `rate <= retries`
3695    /// rejects (the bucket exhausts before retries complete, silently
3696    /// truncating the declared retry policy mid-run — the same
3697    /// declared-but-structurally-inert footgun the sibling per-axis cap
3698    /// arms close on the single-axis surfaces). The equivalent
3699    /// coherent-direction form `rl.rate() > retries` sidesteps the
3700    /// `retries + 1` addition entirely (both `rate` and `retries` are
3701    /// `u32`; the `>` comparison is total on the type with no overflow
3702    /// against past-the-guard struct-literal `retries` values a caller
3703    /// might pass before `validate` runs), matching the peer
3704    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
3705    /// `>`-comparison discipline on the sibling
3706    /// `(:retries, :max-failures)` pair.
3707    ///
3708    /// Vacuously `true` when either axis is absent — a `:politicas`
3709    /// that names only one of the pair declares no relation for the
3710    /// substrate to hold it to (`:retries` alone is a client-retry
3711    /// policy with no rate limiter to saturate; `:rate-limit` alone is
3712    /// a token-bucket declaration whose per-client attempt count is
3713    /// unconstrained by the substrate, so no per-client saturation
3714    /// bound on tokens-per-client-call is knowable at author time).
3715    /// Same "unset means the cluster default applies, not zero"
3716    /// partition [`MeshPolicy::is_empty`] and the three sibling
3717    /// cross-axis predicates
3718    /// ([`MeshPolicy::breaker_window_observes_timeout`],
3719    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
3720    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
3721    ///
3722    /// Lifted as a typed predicate on the substrate primitive rather
3723    /// than open-coded at the validate gate so every downstream
3724    /// consumer of the pair reaches the invariant through one dispatch:
3725    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3726    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3727    /// (MESH-COMPOSITION §III.2 #3) that must emit
3728    /// `local_rate_limit.token_bucket.max_tokens` alongside
3729    /// `retry_policy.num_retries` as one coherent Envoy block, the
3730    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3731    /// admission webhook, and the future per-`:contratos`-edge
3732    /// `:politicas` override the same roadmap acknowledges — which
3733    /// resolves an *effective* pair per edge (edge-level `:retries`
3734    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
3735    /// so must re-check the relation on a pair neither axis's
3736    /// declaration site can see whole. Naming the invariant once means
3737    /// that resolver folds this predicate over its resolved pair
3738    /// instead of re-deriving the comparison, exactly as the three
3739    /// sibling cross-axis predicates name the
3740    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
3741    /// `(:retries, :max-failures)` relations for their own consumers,
3742    /// closing the fourth and last cross-axis relation on the scalar
3743    /// `:politicas` axis-triple.
3744    #[must_use]
3745    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3746        match (self.retries(), self.rate_limit()) {
3747            (Some(retries), Some(rl)) => rl.rate() > retries,
3748            _ => true,
3749        }
3750    }
3751
3752    /// Substrate-canonical fold over the four cross-axis coherence
3753    /// predicates on the `:politicas` slot — returns the *first*
3754    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3755    /// canonical "more-foundational-cross-axis first" ordering
3756    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3757    /// `(:timeout, :circuit-breaker :window)` →
3758    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3759    /// `(:rate-limit, :circuit-breaker)` →
3760    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3761    /// `(:retries, :circuit-breaker :max-failures)` →
3762    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3763    /// :rate-limit)`. Returns `None` when every cross-axis relation
3764    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3765    /// coherent shape both land here).
3766    ///
3767    /// The ordering discipline this method encodes was open-coded four
3768    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3769    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3770    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3771    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3772    /// axis-fetch step depended on the predicate having just returned
3773    /// `false` (structurally guaranteed both paired axes are `Some`,
3774    /// but the compiler cannot see through the predicate body, so
3775    /// every arm re-called the accessor with `.expect(…)` to reach
3776    /// the axis it just tested). Two unsound consequences: (1) the
3777    /// validate gate carried eight `.expect(…)` panic call sites the
3778    /// predicate contract already forbids on every well-typed input
3779    /// but the type system does not enforce; (2) the
3780    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3781    /// twice — once in each predicate's own doc comments and once at
3782    /// the validate call site's four-arm cascade. Lifting the four-arm
3783    /// cascade onto this substrate primitive collapses both
3784    /// duplications: the predicate contract and the axis-fetch step
3785    /// live in the same body (no `.expect(…)` — the pattern match at
3786    /// each arm rebinds the paired axes so their `Some` presence is a
3787    /// compile-time property of the local scope), and the ordering
3788    /// discipline lives once at the top of the primitive rather than
3789    /// scattered across four sibling doc-comment blocks that must
3790    /// stay in lockstep.
3791    ///
3792    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3793    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3794    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3795    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3796    /// §III.2 #3 acknowledges — the last of which resolves an
3797    /// *effective* per-edge pair and must emit *the same* diagnostic
3798    /// on the same paired-axis input as `feira build`) reaches through
3799    /// one call rather than re-inlining the four pattern-matches +
3800    /// accessor-fetches + variant-constructions + ordering-cascade.
3801    ///
3802    /// Returns owned copies of every axis carried into the diagnostic:
3803    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3804    /// occurs on the happy path when no violation fires.
3805    #[must_use]
3806    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3807        // Ordering discipline this fold encodes matches the four
3808        // per-arm predicate doc comments' pairwise-ordering contract:
3809        // window-below-timeout wins over every arm that names `:rate-
3810        // limit` or `:retries` (its diagnostic is more self-locating —
3811        // the pair is a per-call-deadline invariant every synchronous
3812        // edge carries whether or not `:rate-limit`/`:retries` is
3813        // declared); the starve arm wins over the two retry arms (its
3814        // diagnostic reasons across the token-bucket-vs-breaker
3815        // relation, an axis the retry arms do not touch); the
3816        // retries-saturate arm wins over the retries-burst arm (its
3817        // diagnostic reasons across the per-client-vs-breaker
3818        // relation, which carries whether or not `:rate-limit` is
3819        // declared). Each arm rebinds the paired axes through the
3820        // pattern match, so the `.expect(…)` panics the four-block
3821        // cascade at `validate_politicas` carried collapse to no-op
3822        // pattern rebindings the compiler statically proves exhaust.
3823        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3824            && !self.breaker_window_observes_timeout()
3825        {
3826            return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
3827        }
3828        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3829            && !self.breaker_can_trip_under_rate_limit()
3830        {
3831            return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
3832                &rl, &cb,
3833            ));
3834        }
3835        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3836            && !self.retries_fit_under_breaker_trip_threshold()
3837        {
3838            return Some(
3839                AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
3840            );
3841        }
3842        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3843            && !self.rate_limit_admits_retry_burst()
3844        {
3845            return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
3846                retries, &rl,
3847            ));
3848        }
3849        None
3850    }
3851
3852    /// Substrate-canonical compound entry gate over the whole
3853    /// `:politicas` typed slot — folds every per-axis bracket
3854    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3855    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3856    /// window-canonical-form) *and* the compound cross-axis fold
3857    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3858    /// consumer of a validated [`MeshPolicy`] reaches through.
3859    ///
3860    /// Returns the first violation as its [`AplicacaoError`] variant,
3861    /// or `Ok(())` when every per-axis value lies in its accept-set and
3862    /// every cross-axis relation holds. Per-axis brackets run strictly
3863    /// before the cross-axis fold — the sibling
3864    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3865    /// ordering discipline for the same reason: a per-axis
3866    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3867    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3868    /// diagnostic first, ahead of any cross-axis arm that would send
3869    /// the author to reconcile two values one of which is not a
3870    /// meaningful window at all. Within the per-axis phase, arms fire
3871    /// in the same slot-order the peer per-axis brackets carry
3872    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3873    /// each internally ordered zero-floor before canonical-form before
3874    /// cap by [`crate::render::require_positive_bounded_u32`] /
3875    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3876    /// within the cross-axis phase, arms fire in the canonical
3877    /// more-foundational-cross-axis-first ordering
3878    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3879    ///
3880    /// Lifted as a typed method on the substrate primitive so every
3881    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3882    /// invariant through one dispatch: the
3883    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3884    /// body collapses to `self.politicas().validate()`), the future
3885    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3886    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3887    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3888    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3889    /// emit *the same* diagnostic on the same input as `feira build`.
3890    /// Naming the compound gate once on the substrate primitive means
3891    /// every downstream consumer inherits both the per-axis brackets
3892    /// *and* the cross-axis fold through one call, rather than
3893    /// re-inlining the four-per-axis + one-cross-axis cascade in
3894    /// lockstep with `validate_politicas`.
3895    ///
3896    /// Peer of the per-kind compound entry gates lifted at
3897    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3898    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3899    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3900    /// layout axis, and the sibling compound cross-axis fold
3901    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3902    /// `:politicas` axis — extended here onto the per-slot per-axis +
3903    /// cross-axis compound entry gate that folds both surfaces.
3904    pub fn validate(&self) -> Result<(), AplicacaoError> {
3905        if let Some(t) = self.timeout() {
3906            crate::render::require_positive_canonical_bounded_duration(
3907                t,
3908                POLICY_TIMEOUT_MAX,
3909                || AplicacaoError::PolicyTimeoutZero,
3910                AplicacaoError::policy_timeout_not_canonical,
3911                AplicacaoError::policy_timeout_exceeds_cap,
3912            )?;
3913        }
3914        if let Some(r) = self.retries() {
3915            crate::render::require_positive_bounded_u32(
3916                r,
3917                POLICY_RETRIES_MAX,
3918                || AplicacaoError::PolicyRetriesZero,
3919                AplicacaoError::policy_retries_exceeds_cap,
3920            )?;
3921        }
3922        if let Some(cb) = self.circuit_breaker() {
3923            crate::render::require_positive_bounded_u32(
3924                cb.max_failures(),
3925                POLICY_BREAKER_MAX_FAILURES_MAX,
3926                || AplicacaoError::PolicyBreakerZeroFailures,
3927                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3928            )?;
3929            crate::render::require_positive_canonical_bounded_duration(
3930                cb.window(),
3931                POLICY_BREAKER_WINDOW_MAX,
3932                || AplicacaoError::PolicyBreakerZeroWindow,
3933                AplicacaoError::policy_breaker_window_not_canonical,
3934                AplicacaoError::policy_breaker_window_exceeds_cap,
3935            )?;
3936        }
3937        if let Some(rl) = self.rate_limit() {
3938            crate::render::require_positive_bounded_u32(
3939                rl.rate(),
3940                POLICY_RATE_LIMIT_MAX,
3941                || AplicacaoError::PolicyRateLimitZero,
3942                AplicacaoError::policy_rate_limit_exceeds_cap,
3943            )?;
3944            if rl.canonical_unit().is_none() {
3945                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3946                    rl.window(),
3947                ));
3948            }
3949        }
3950        if let Some(err) = self.first_cross_axis_violation() {
3951            return Err(err);
3952        }
3953        Ok(())
3954    }
3955
3956    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3957    /// per-call-deadline scalar accessor every consumer of the
3958    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3959    /// returns the author-declared `:politicas :timeout` typed
3960    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3961    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3962    /// is `Copy`, so the accessor returns by value; no borrow of
3963    /// `&self` past the call). `None` when the slot is absent (the
3964    /// "cluster default applies — typically the gateway class's
3965    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3966    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3967    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3968    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3969    /// round-trips to a rendered `HTTPRoute` structurally identical to
3970    /// one that omits the slot).
3971    ///
3972    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3973    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3974    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3975    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3976    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3977    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3978    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3979    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3980    /// Every downstream consumer that reads the per-call cap keys off
3981    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3982    /// renderers key off to decide "emit :politicas overlay" vs "skip
3983    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3984    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3985    /// fans the deadline into every rule via
3986    /// [`crate::render::single_field_overlay`], the future M4 per-
3987    /// Aplicacao Gateway API reconciler materialization pass, the
3988    /// future per-`:contratos`-edge timeout-override overlay the
3989    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3990    ///
3991    /// Prior to this lift the `.timeout` field was accessed inline at
3992    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3993    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3994    /// …)` call — two open-coded field-accesses that expressed no
3995    /// compile-time link back to the typed slot. A future extension of
3996    /// the `:politicas :timeout` axis to a richer author surface — a
3997    /// per-`:contratos`-edge timeout override the operator pins through
3998    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3999    /// roadmap acknowledges, a per-cluster timeout-default overlay the
4000    /// M4 CR materializer resolves per-CR, a split of the single
4001    /// per-call `Duration` into a richer `{request, backendRequest}`
4002    /// pair once the Gateway API's per-rule `timeouts` block grows the
4003    /// upstream-facing backendRequest arm alongside the client-facing
4004    /// request arm — would have had to be threaded through both open-
4005    /// coded copies in lockstep or the emptiness predicate and the
4006    /// caixa-mesh emit path would silently disagree on which per-call
4007    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
4008    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
4009    /// == false` while the renderer's overlay-emit path silently read
4010    /// a drifted other value, or vice versa: an author's `:timeout
4011    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
4012    /// the emptiness predicate still classified the policy as non-
4013    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
4014    /// | grep -A2 timeouts` audit would land on a route whose author's
4015    /// typed slot value silently vanished at the renderer layer).
4016    /// Lifting the resolution to a typed method on the substrate
4017    /// primitive means every downstream consumer of the Aplicacao's
4018    /// per-`:politicas` deadline surface reaches for exactly one typed
4019    /// dispatch — the resolver's accept-set migrates as a unit on any
4020    /// future axis addition.
4021    ///
4022    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
4023    /// family (sibling of the peer per-`:politicas`
4024    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
4025    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
4026    /// `Option<bool>` accessor — same "one typed dispatch on the
4027    /// substrate primitive, thin projections at each consumer"
4028    /// discipline extended onto the peer per-`:politicas` typed-
4029    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
4030    /// numeric-Copy-T scalar" projection pattern the sibling
4031    /// `Option<u32>` / `Option<bool>` lifts opened, since every
4032    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
4033    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
4034    /// than a scalar). Named `timeout()` to match the storage field's
4035    /// name; the accessor's identity maps onto the canonical MESH-
4036    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
4037    #[must_use]
4038    pub const fn timeout(&self) -> Option<Duration> {
4039        self.timeout
4040    }
4041
4042    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
4043    /// retry-budget scalar accessor every consumer of the Aplicacao's
4044    /// Gateway API v1.x per-rule retry-cap keys off — returns the
4045    /// author-declared `:politicas :retries` typed `u32` verbatim as an
4046    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
4047    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
4048    /// value; no borrow of `&self` past the call). `None` when the slot
4049    /// is absent (the "cluster default applies — typically 'no retries
4050    /// beyond a single dispatch attempt'" arm the caixa-mesh
4051    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
4052    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
4053    /// this predicate too, so an authored-but-unset `:politicas
4054    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
4055    /// identical to one that omits the slot).
4056    ///
4057    /// The `:politicas :retries` slot carries the "transient failure
4058    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
4059    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
4060    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
4061    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
4062    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
4063    /// count scalar the caixa-mesh `retry_overlay` builder writes.
4064    /// Every downstream consumer that reads the retry cap keys off this
4065    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
4066    /// renderers key off to decide "emit :politicas overlay" vs "skip
4067    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
4068    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
4069    /// the value into every rule via [`crate::render::single_field_overlay`],
4070    /// the future M4 per-Aplicacao Gateway API reconciler
4071    /// materialization pass, the future per-`:contratos`-edge retry-
4072    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
4073    /// acknowledges).
4074    ///
4075    /// Prior to this lift the `.retries` field was accessed inline at
4076    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
4077    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
4078    /// …)` call — two open-coded field-accesses that expressed no
4079    /// compile-time link back to the typed slot. A future extension of
4080    /// the `:politicas :retries` axis to a richer author surface — a
4081    /// per-`:contratos`-edge retry override the operator pins through a
4082    /// future `:contratos :retries` slot, a per-cluster retry-default
4083    /// overlay the M4 CR materializer resolves per-CR, a promotion of
4084    /// the plain `u32` attempt-count to a richer `{attempts, codes,
4085    /// backoff}` sub-block once the Gateway API grows the peer
4086    /// `retry.codes` / `retry.backoff` axes — would have had to be
4087    /// threaded through both open-coded copies in lockstep or the
4088    /// emptiness predicate and the caixa-mesh emit path would silently
4089    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
4090    /// (a `:politicas` block whose only axis is a `Some :retries` would
4091    /// satisfy `is_empty() == false` while the renderer's overlay-emit
4092    /// path silently read a drifted other value, or vice versa: an
4093    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
4094    /// block while the emptiness predicate still classified the policy
4095    /// as non-empty). Lifting the resolution to a typed method on the
4096    /// substrate primitive means every downstream consumer of the
4097    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
4098    /// one typed dispatch — the resolver's accept-set migrates as a
4099    /// unit on any future axis addition.
4100    ///
4101    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
4102    /// family (sibling of the peer per-`:politicas`
4103    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
4104    /// same "one typed dispatch on the substrate primitive, thin
4105    /// projections at each consumer" discipline extended onto the
4106    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
4107    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
4108    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
4109    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
4110    /// fold on). Named `retries()` to match the storage field's name;
4111    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
4112    /// §III.2 vocabulary the slot's docstring already carries.
4113    #[must_use]
4114    pub const fn retries(&self) -> Option<u32> {
4115        self.retries
4116    }
4117
4118    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
4119    /// enforcement-toggle scalar accessor every consumer of the
4120    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
4121    /// — returns the author-declared `:politicas :mtls-required` typed
4122    /// bool verbatim as an `Option<bool>`, copied out of the typed
4123    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
4124    /// the accessor returns by value; no borrow of `&self` past the
4125    /// call). `None` when the slot is absent (the "cluster default
4126    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
4127    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
4128    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
4129    /// this predicate too, so an authored-but-unset `:politicas
4130    /// (:mtls-required ())` round-trips to a rendered
4131    /// `CiliumNetworkPolicy` structurally identical to one that omits
4132    /// the slot).
4133    ///
4134    /// The `:politicas :mtls-required` slot carries the "explicit opt-
4135    /// out only, sandboxing-by-default" mTLS-enforcement toggle
4136    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
4137    /// `{None, Some(true), Some(false)}` accept-set maps onto the
4138    /// Cilium `authentication.mode` bijection through
4139    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
4140    /// handshake enforced), `Some(false) → "disabled"` (handshake
4141    /// skipped — the debug-edge opt-out), `None` → omit the block
4142    /// (cluster default applies). Every downstream consumer that
4143    /// reads the toggle keys off this scalar (the
4144    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4145    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4146    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
4147    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
4148    /// ingress rule via [`crate::render::single_field_overlay`], the
4149    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
4150    /// materialization pass, the future per-`:contratos`-edge mTLS
4151    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4152    ///
4153    /// Prior to this lift the `.mtls_required` field was accessed
4154    /// inline at two sites — [`MeshPolicy::is_empty`]'s
4155    /// `self.mtls_required.is_none()` arm and caixa-mesh's
4156    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
4157    /// two open-coded field-accesses that expressed no compile-time
4158    /// link back to the typed slot. A future extension of the
4159    /// `:politicas :mtls-required` axis to a richer author surface —
4160    /// a per-`:contratos`-edge mTLS override the operator pins through
4161    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
4162    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
4163    /// M4 CR materializer resolves per-CR, a three-valued
4164    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
4165    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
4166    /// would have had to be threaded through both open-coded copies in
4167    /// lockstep or the emptiness predicate and the caixa-mesh emit
4168    /// path would silently disagree on which toggle a given
4169    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
4170    /// axis is a `Some`
4171    /// `:mtls-required` would satisfy `is_empty() == false` while the
4172    /// renderer's overlay-emit path silently read a drifted other
4173    /// value, or vice versa). Lifting the resolution to a typed method
4174    /// on the substrate primitive means every downstream consumer of
4175    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
4176    /// for exactly one typed dispatch — the resolver's accept-set
4177    /// migrates as a unit on any future axis addition.
4178    ///
4179    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
4180    /// family (peer of the sibling per-`:placement`
4181    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
4182    /// same "one typed dispatch on the substrate primitive, thin
4183    /// projections at each consumer" discipline extended onto the
4184    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
4185    /// the "optional per-slot Copy-T scalar" projection pattern the
4186    /// sibling per-`:politicas` `:retries` (Option<u32>) /
4187    /// `:timeout` (Option<Duration>) future lifts fold on). Named
4188    /// `mtls_required()` to match the storage field's name; the
4189    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4190    /// §III.2 vocabulary the slot's docstring already carries.
4191    #[must_use]
4192    pub const fn mtls_required(&self) -> Option<bool> {
4193        self.mtls_required
4194    }
4195
4196    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
4197    /// `local_rate_limit`-mesh token-bucket-declaration scalar
4198    /// accessor every consumer of the Aplicacao's per-`:politicas`
4199    /// per-`(rate, window)` rate-limit surface keys off — returns the
4200    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
4201    /// verbatim as an `Option<RateLimit>`, copied out of the typed
4202    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
4203    /// `Copy`, so the accessor returns by value; no borrow of `&self`
4204    /// past the call). `None` when the slot is absent (the "cluster
4205    /// default applies — typically 'no per-Aplicacao rate declaration,
4206    /// gateway-class per-listener default applies'" arm the future
4207    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
4208    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
4209    /// `rate_limit().is_none()` arm reads this predicate too, so an
4210    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
4211    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
4212    /// identical to one that omits the slot).
4213    ///
4214    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
4215    /// token-bucket rate declaration" contract (MESH-COMPOSITION
4216    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
4217    /// (rate lower-bounded by 1 through
4218    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
4219    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
4220    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
4221    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
4222    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
4223    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
4224    /// `:politicas` overlay emits. Every downstream consumer that
4225    /// reads the rate declaration keys off this scalar (the
4226    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4227    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4228    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
4229    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
4230    /// `rl.window` against [`is_canonical_rate_limit_window`], the
4231    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
4232    /// the future per-`:contratos`-edge rate-limit override the
4233    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4234    ///
4235    /// Prior to this lift the `.rate_limit` field was accessed inline
4236    /// at two sites — [`MeshPolicy::is_empty`]'s
4237    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
4238    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
4239    /// field-accesses that expressed no compile-time link back to the
4240    /// typed slot. A future extension of the `:politicas :rate-limit`
4241    /// axis to a richer author surface — a per-`:contratos`-edge
4242    /// rate-limit override the operator pins through a future
4243    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
4244    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
4245    /// the M4 CR materializer resolves per-CR, a promotion of the
4246    /// plain `(rate, window)` scalar pair to a richer
4247    /// `{rate, window, burst, key}` sub-block once Envoy's
4248    /// `local_rate_limit` grows the peer `burst_size` /
4249    /// `descriptor_key` axes — would have had to be threaded through
4250    /// both open-coded copies in lockstep or the emptiness predicate
4251    /// and the validate gate would silently disagree on which rate
4252    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
4253    /// block whose only axis is a `Some :rate-limit` would satisfy
4254    /// `is_empty() == false` while the validate path silently read a
4255    /// drifted other value, or vice versa: an author's
4256    /// `:rate-limit "100/s"` would omit the value-shape gate while the
4257    /// emptiness predicate still classified the policy as non-empty).
4258    /// Lifting the resolution to a typed method on the substrate
4259    /// primitive means every downstream consumer of the Aplicacao's
4260    /// per-`:politicas` rate-limit surface reaches for exactly one
4261    /// typed dispatch — the resolver's accept-set migrates as a unit
4262    /// on any future axis addition.
4263    ///
4264    /// First `Option<Copy-composite-T>`-return accessor on the M3
4265    /// mesh-slot family — closes the last un-lifted per-`:politicas`
4266    /// scalar-value axis. Peer of the sibling per-`:politicas`
4267    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
4268    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
4269    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
4270    /// "one typed dispatch on the substrate primitive, thin
4271    /// projections at each consumer" discipline extended onto the
4272    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
4273    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
4274    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
4275    /// sub-accessors rather than a top-level accessor because
4276    /// consumers reach for the axes not the aggregate). Named
4277    /// `rate_limit()` to match the storage field's name; the
4278    /// accessor's identity maps onto the canonical MESH-COMPOSITION
4279    /// §III.2 vocabulary the slot's docstring already carries.
4280    #[must_use]
4281    pub const fn rate_limit(&self) -> Option<RateLimit> {
4282        self.rate_limit
4283    }
4284
4285    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
4286    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
4287    /// declaration scalar accessor every consumer of the Aplicacao's
4288    /// per-`:politicas` breaker declaration keys off — returns the
4289    /// author-declared `:politicas :circuit-breaker` typed
4290    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
4291    /// copied out of the typed slot's own `Option<CircuitBreaker>`
4292    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
4293    /// by value; no borrow of `&self` past the call). `None` when the
4294    /// slot is absent (the "cluster default applies — typically 'no
4295    /// per-Aplicacao breaker declaration, gateway-class per-listener
4296    /// default applies'" arm the future caixa-mesh
4297    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
4298    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
4299    /// arm reads this predicate too, so an authored-but-unset
4300    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
4301    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
4302    /// that omits the slot).
4303    ///
4304    /// The `:politicas :circuit-breaker` slot carries the
4305    /// "per-Aplicacao consecutive-transient-failure trip declaration"
4306    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4307    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
4308    /// zero-floor rejected through
4309    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4310    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
4311    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
4312    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
4313    /// canonical-form pinned through
4314    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
4315    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
4316    /// bijection the future `CiliumClusterwideEnvoyConfig`
4317    /// per-`:politicas` overlay emits. Every downstream consumer that
4318    /// reads the breaker declaration keys off this scalar (the
4319    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4320    /// off to decide "emit :politicas overlay" vs "skip entirely", the
4321    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
4322    /// that brackets `cb.max_failures()` against
4323    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
4324    /// [`POLICY_BREAKER_WINDOW_MAX`] via
4325    /// [`crate::render::require_positive_canonical_bounded_duration`],
4326    /// the future M4 per-Aplicacao Envoy reconciler materialization
4327    /// pass, the future per-`:contratos`-edge breaker override the
4328    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4329    ///
4330    /// Prior to this lift the `.circuit_breaker` field was accessed
4331    /// inline at two sites — [`MeshPolicy::is_empty`]'s
4332    /// `self.circuit_breaker.is_none()` arm and the
4333    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
4334    /// bind — two open-coded field-accesses that expressed no
4335    /// compile-time link back to the typed slot. A future extension of
4336    /// the `:politicas :circuit-breaker` axis to a richer author
4337    /// surface — a per-`:contratos`-edge breaker override the operator
4338    /// pins through a future `:contratos :circuit-breaker` slot the
4339    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
4340    /// breaker-default overlay the M4 CR materializer resolves per-CR,
4341    /// a promotion of the plain `(max_failures, window)` scalar pair to
4342    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
4343    /// sub-block once Envoy's `outlier_detection` grows the peer
4344    /// ejection-percentage / ejection-time axes — would have had to be
4345    /// threaded through both open-coded copies in lockstep or the
4346    /// emptiness predicate and the validate gate would silently
4347    /// disagree on which breaker declaration a given [`MeshPolicy`]
4348    /// resolves to (a `:politicas` block whose only axis is a
4349    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
4350    /// the validate path silently read a drifted other value, or vice
4351    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
4352    /// "60s"))` would omit the value-shape gate while the emptiness
4353    /// predicate still classified the policy as non-empty). Lifting
4354    /// the resolution to a typed method on the substrate primitive
4355    /// means every downstream consumer of the Aplicacao's
4356    /// per-`:politicas` breaker surface reaches for exactly one typed
4357    /// dispatch — the resolver's accept-set migrates as a unit on any
4358    /// future axis addition.
4359    ///
4360    /// Second `Option<Copy-composite-T>`-return accessor on the M3
4361    /// mesh-slot family (sibling of the peer per-`:politicas`
4362    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
4363    /// on the same composite-Copy shape, and of the sibling per-
4364    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
4365    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
4366    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
4367    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
4368    /// same "one typed dispatch on the substrate primitive, thin
4369    /// projections at each consumer" discipline extended onto the last
4370    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
4371    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
4372    /// match the storage field's name; the accessor's identity maps
4373    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4374    /// docstring already carries. Closes the last unlifted
4375    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
4376    /// reader now routes through a typed dispatch on the substrate
4377    /// primitive.
4378    #[must_use]
4379    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
4380        self.circuit_breaker
4381    }
4382}
4383
4384#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
4385#[serde(rename_all = "camelCase")]
4386pub struct CircuitBreaker {
4387    pub max_failures: u32,
4388    #[serde(with = "supervisor::duration_codec_required")]
4389    pub window: Duration,
4390}
4391
4392impl CircuitBreaker {
4393    /// Substrate-canonical per-`:politicas :circuit-breaker`
4394    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
4395    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4396    /// breaker trip-count keys off — returns the author-declared
4397    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
4398    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
4399    /// so the accessor returns by value; no borrow of `&self` past the
4400    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
4401    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
4402    /// axis; a `CircuitBreaker` past pattern-match is definitionally
4403    /// present, and its `:max-failures` field carries the trip count as a
4404    /// required-axis scalar).
4405    ///
4406    /// The `:politicas :circuit-breaker :max-failures` axis carries the
4407    /// "consecutive-transient-failure trip threshold" contract
4408    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
4409    /// (zero-floor rejected through
4410    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4411    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
4412    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
4413    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
4414    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
4415    /// Every downstream consumer that reads the trip threshold keys off
4416    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4417    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
4418    /// canonical `require_positive_bounded_u32` helper, the future M4
4419    /// per-Aplicacao Envoy config reconciler materialization pass, the
4420    /// future per-`:contratos`-edge breaker-override overlay the
4421    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4422    ///
4423    /// Prior to this lift the `.max_failures` field was accessed inline
4424    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
4425    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
4426    /// open-coded field-access that expressed no compile-time link back
4427    /// to the typed sub-struct axis. A future extension of the
4428    /// `:max-failures` axis to a richer author surface — a
4429    /// per-`:contratos`-edge breaker override the operator pins through a
4430    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
4431    /// #3 roadmap acknowledges, a per-cluster max-failures-default
4432    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
4433    /// plain `u32` trip count to a richer
4434    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
4435    /// tuple once Envoy's `outlier_detection` block's peer axes come into
4436    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
4437    /// count arms — would have had to be threaded through every open-
4438    /// coded copy in lockstep or the validate gate and the future M4
4439    /// emit path would silently disagree on which trip threshold a given
4440    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
4441    /// would satisfy validate while the emit path silently read a drifted
4442    /// other value, or vice versa: a validated typed slot would land at
4443    /// the emit boundary as a no-op breaker whose trip threshold is
4444    /// structurally never reached). Lifting the resolution to a typed
4445    /// method on the substrate primitive means every downstream consumer
4446    /// of the Aplicacao's per-`:politicas :circuit-breaker`
4447    /// trip-threshold surface reaches for exactly one typed dispatch —
4448    /// the resolver's accept-set migrates as a unit on any future axis
4449    /// addition.
4450    ///
4451    /// First sub-struct scalar accessor on the M3 mesh-slot family
4452    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
4453    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
4454    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
4455    /// closes the last unlifted per-`:politicas` scalar-value axis after
4456    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
4457    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
4458    /// Same "one typed dispatch on the substrate primitive, thin
4459    /// projections at each consumer" discipline the peer
4460    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4461    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4462    /// [`Membro::versao_requirement`] (a40b0e3),
4463    /// [`Entrada::destination`] (6db982c) accessors carry on their
4464    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
4465    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
4466    /// match the storage field's name; the accessor's identity maps onto
4467    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4468    /// docstring already carries.
4469    #[must_use]
4470    pub const fn max_failures(&self) -> u32 {
4471        self.max_failures
4472    }
4473
4474    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
4475    /// Envoy-outlier-detection rolling-observation-interval scalar
4476    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4477    /// breaker rolling-window duration keys off — returns the
4478    /// author-declared `:politicas :circuit-breaker :window` typed
4479    /// `Duration` verbatim, copied out of the typed slot's own
4480    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
4481    /// by value; no borrow of `&self` past the call). Non-optional (the
4482    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
4483    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
4484    /// `CircuitBreaker` past pattern-match is definitionally present,
4485    /// and its `:window` field carries the rolling-observation interval
4486    /// as a required-axis scalar).
4487    ///
4488    /// The `:politicas :circuit-breaker :window` axis carries the
4489    /// "consecutive-transient-failure rolling-observation interval"
4490    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4491    /// `Duration` accept-set (zero-floor rejected through
4492    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
4493    /// residue rejected through
4494    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
4495    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
4496    /// Envoy `outlier_detection.interval` per-cluster
4497    /// ejection-observation-interval scalar (equivalently the future
4498    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4499    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4500    /// consumer that reads the rolling-observation interval keys off
4501    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4502    /// integer-millisecond canonical-form + cap bracket at
4503    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
4504    /// [`crate::render::require_positive_canonical_bounded_duration`]
4505    /// helper, the future M4 per-Aplicacao Envoy config reconciler
4506    /// materialization pass, the future per-`:contratos`-edge
4507    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4508    /// acknowledges).
4509    ///
4510    /// Prior to this lift the `.window` field was accessed inline at
4511    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
4512    /// `require_positive_canonical_bounded_duration(cb.window, …)`
4513    /// call — one open-coded field-access that expressed no compile-
4514    /// time link back to the typed sub-struct axis. A future extension
4515    /// of the `:window` axis to a richer author surface — a
4516    /// per-`:contratos`-edge window override the operator pins through
4517    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
4518    /// #3 roadmap acknowledges, a per-cluster window-default overlay
4519    /// the M4 CR materializer resolves per-CR, a promotion of the plain
4520    /// `Duration` observation interval to a richer
4521    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
4522    /// once Envoy's `outlier_detection` block's peer axes come into
4523    /// scope, a per-Envoy-cluster minimum-request-volume gate before
4524    /// the window arms — would have had to be threaded through every
4525    /// open-coded copy in lockstep or the validate gate and the future
4526    /// M4 emit path would silently disagree on which observation
4527    /// interval a given [`CircuitBreaker`] resolves to (an author's
4528    /// `:window "60s"` would satisfy validate while the emit path
4529    /// silently read a drifted other value, or vice versa: a validated
4530    /// typed slot would land at the emit boundary as a breaker whose
4531    /// observation window is structurally so wide that no realistic
4532    /// failure-rate shape can trip it). Lifting the resolution to a
4533    /// typed method on the substrate primitive means every downstream
4534    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
4535    /// observation-window surface reaches for exactly one typed
4536    /// dispatch — the resolver's accept-set migrates as a unit on any
4537    /// future axis addition.
4538    ///
4539    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
4540    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
4541    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
4542    /// required-axis, extended onto the per-sub-struct required-`Duration`
4543    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
4544    /// axis. Same "one typed dispatch on the substrate primitive, thin
4545    /// projections at each consumer" discipline the peer
4546    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4547    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4548    /// [`Membro::versao_requirement`] (a40b0e3),
4549    /// [`Entrada::destination`] (6db982c) accessors carry on their
4550    /// respective per-mesh-slot-atom scalar-value axes, extended onto
4551    /// the per-sub-struct required-`Duration` axis. Named `window()` to
4552    /// match the storage field's name; the accessor's identity maps onto
4553    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4554    /// docstring already carries.
4555    #[must_use]
4556    pub const fn window(&self) -> Duration {
4557        self.window
4558    }
4559}
4560
4561#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4562pub struct RateLimit {
4563    /// Requests per window.
4564    pub rate: u32,
4565    /// Window duration.
4566    pub window: Duration,
4567}
4568
4569impl RateLimit {
4570    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
4571    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
4572    /// every consumer of the Aplicacao's per-`:contratos`-edge
4573    /// rate-limit-bucket capacity keys off — returns the author-declared
4574    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
4575    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
4576    /// returns by value; no borrow of `&self` past the call). Non-optional
4577    /// (the surrounding `Option<RateLimit>` is the "slot present?"
4578    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
4579    /// `RateLimit` past pattern-match is definitionally present, and its
4580    /// `:rate` field carries the token-bucket capacity as a required-axis
4581    /// scalar).
4582    ///
4583    /// The `:politicas :rate-limit` `:rate` axis carries the
4584    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
4585    /// the typed slot's `u32` accept-set (zero-floor rejected through
4586    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
4587    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
4588    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
4589    /// token-bucket-capacity scalar (equivalently the future
4590    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4591    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4592    /// consumer that reads the token-bucket capacity keys off this
4593    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4594    /// cap bracket that gates on the canonical
4595    /// [`crate::render::require_positive_bounded_u32`] helper, the
4596    /// [`rate_limit_codec::render`] `Duration → unit` projection that
4597    /// emits the `<n>/<s|m|h>` author surface, the future M4
4598    /// per-Aplicacao Envoy config reconciler materialization pass, the
4599    /// future per-`:contratos`-edge rate-limit-override overlay the
4600    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4601    ///
4602    /// Prior to this lift the `.rate` field was accessed inline at three
4603    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
4604    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
4605    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
4606    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
4607    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
4608    /// field-accesses that expressed no compile-time link back to the
4609    /// typed sub-struct axis. A future extension of the `:rate` axis
4610    /// to a richer author surface — a per-`:contratos`-edge rate
4611    /// override the operator pins through a future `:contratos :rate`
4612    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
4613    /// per-cluster rate-default overlay the M4 CR materializer resolves
4614    /// per-CR, a promotion of the plain `u32` token capacity to a
4615    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
4616    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4617    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
4618    /// before the token arms — would have had to be threaded through
4619    /// every open-coded copy in lockstep or the validate gate, the
4620    /// codec's render path, and the future M4 emit path would silently
4621    /// disagree on which token capacity a given [`RateLimit`] resolves
4622    /// to (an author's `:rate-limit "100/s"` would satisfy validate
4623    /// while the render / emit paths silently read a drifted other
4624    /// value, or vice versa: a validated typed slot would land at the
4625    /// emit boundary as a no-op limiter whose token capacity is
4626    /// structurally so high that no realistic per-edge traffic shape
4627    /// can drain it). Lifting the resolution to a typed method on the
4628    /// substrate primitive means every downstream consumer of the
4629    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
4630    /// reaches for exactly one typed dispatch — the resolver's
4631    /// accept-set migrates as a unit on any future axis addition.
4632    ///
4633    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
4634    /// in shape to the peer per-`CircuitBreaker`
4635    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
4636    /// on the peer per-sub-struct required-axis, extended onto the
4637    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
4638    /// required-axis scalar" projection pattern the sibling
4639    /// [`RateLimit::window`] future lift folds on. Same "one typed
4640    /// dispatch on the substrate primitive, thin projections at each
4641    /// consumer" discipline the peer [`WitContract::source`] /
4642    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
4643    /// (0804823), [`Membro::nome`] (4a32abf),
4644    /// [`Membro::versao_requirement`] (a40b0e3),
4645    /// [`Entrada::destination`] (6db982c),
4646    /// [`CircuitBreaker::max_failures`] (3a74062),
4647    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
4648    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
4649    /// to match the storage field's name; the accessor's identity maps
4650    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4651    /// docstring already carries.
4652    #[must_use]
4653    pub const fn rate(&self) -> u32 {
4654        self.rate
4655    }
4656
4657    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
4658    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
4659    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4660    /// rate-limit-bucket refill period keys off — returns the
4661    /// author-declared `:politicas :rate-limit` typed `Duration`
4662    /// verbatim, copied out of the typed slot's own `Duration` storage
4663    /// (`Duration` is `Copy`, so the accessor returns by value; no
4664    /// borrow of `&self` past the call). Non-optional (the surrounding
4665    /// `Option<RateLimit>` is the "slot present?" projection at the
4666    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
4667    /// pattern-match is definitionally present, and its `:window`
4668    /// field carries the token-bucket refill period as a required-axis
4669    /// scalar).
4670    ///
4671    /// The `:politicas :rate-limit` `:window` axis carries the
4672    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
4673    /// — the typed slot's `Duration` accept-set (constrained to the
4674    /// three canonical windows `{1s, 60s, 3600s}` the
4675    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
4676    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
4677    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
4678    /// per-cluster token-bucket-refill-period scalar (equivalently the
4679    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4680    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4681    /// consumer that reads the token-bucket refill period keys off
4682    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
4683    /// canonical-window gate that keys off
4684    /// [`is_canonical_rate_limit_window`], the
4685    /// [`rate_limit_codec::render`] `Duration → unit` projection that
4686    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
4687    /// [`rate_limit_window_unit`] and non-canonical fallback via
4688    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
4689    /// reconciler materialization pass, the future per-`:contratos`-
4690    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
4691    /// roadmap acknowledges).
4692    ///
4693    /// Prior to this lift the `.window` field was accessed inline at
4694    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
4695    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
4696    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
4697    /// error-payload construction on refusal, and the two
4698    /// [`rate_limit_codec::render`] arms
4699    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
4700    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
4701    /// open-coded field-accesses that expressed no compile-time link
4702    /// back to the typed sub-struct axis. A future extension of the
4703    /// `:window` axis to a richer author surface — a per-`:contratos`-
4704    /// edge window override the operator pins through a future
4705    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
4706    /// acknowledges, a per-cluster window-default overlay the M4 CR
4707    /// materializer resolves per-CR, a promotion of the plain
4708    /// `Duration` refill period to a richer
4709    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
4710    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4711    /// axis comes into scope, an addition of a `"d"` day suffix once
4712    /// Envoy's `rate_limit_action` grows daily-bucket support — would
4713    /// have had to be threaded through every open-coded copy in
4714    /// lockstep or the validate gate, the codec's render path, and
4715    /// the future M4 emit path would silently disagree on which
4716    /// refill period a given [`RateLimit`] resolves to (an author's
4717    /// `:rate-limit "100/s"` would satisfy validate while the render
4718    /// / emit paths silently read a drifted other value, or vice
4719    /// versa: a validated typed slot would land at the emit boundary
4720    /// as a limiter whose refill period is structurally so long that
4721    /// no realistic per-edge traffic shape stays inside the token
4722    /// budget). Lifting the resolution to a typed method on the
4723    /// substrate primitive means every downstream consumer of the
4724    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
4725    /// reaches for exactly one typed dispatch — the resolver's
4726    /// accept-set migrates as a unit on any future axis addition.
4727    ///
4728    /// Second sub-struct scalar accessor on the `RateLimit` axis —
4729    /// sibling in shape to the just-landed [`RateLimit::rate`]
4730    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
4731    /// required-axis, extended onto the per-sub-struct
4732    /// required-`Duration` axis; closes the last unlifted
4733    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
4734    /// per-sub-struct accessor coverage is now complete across both
4735    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
4736    /// the substrate primitive, thin projections at each consumer"
4737    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
4738    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
4739    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
4740    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4741    /// [`Membro::nome`] (4a32abf),
4742    /// [`Membro::versao_requirement`] (a40b0e3),
4743    /// [`Entrada::destination`] (6db982c) accessors carry on their
4744    /// respective per-mesh-slot-atom scalar-value axes. Named
4745    /// `window()` to match the storage field's name; the accessor's
4746    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4747    /// vocabulary the slot's docstring already carries.
4748    #[must_use]
4749    pub const fn window(&self) -> Duration {
4750        self.window
4751    }
4752
4753    /// Recognize this rate-limit's `:window` as a canonical
4754    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4755    /// exactly matches one of the three closed-set arm-Durations
4756    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4757    /// non-canonical magnitude the codec's round-trip would break on
4758    /// (sub-second residue, or a second-magnitude outside the set
4759    /// [`RateLimitUnit::ALL`] enumerates).
4760    ///
4761    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4762    /// returns `Some` here — the validate gate's
4763    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4764    /// rejects every window this accessor returns `None` on. Downstream
4765    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4766    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4767    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4768    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4769    /// acknowledges) that read the typed unit off a validated slot can
4770    /// pattern-match on the returned `Some` without re-checking
4771    /// canonicality at the consumer layer — the typed enum surface is
4772    /// the load-bearing carrier of the canonicality invariant.
4773    ///
4774    /// Preferred over the free [`is_canonical_rate_limit_window`]
4775    /// module-private helper at any call site that has the typed
4776    /// [`RateLimit`] in hand (the codec's `render` arm at
4777    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4778    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4779    /// per-`:contratos` edge-override overlay resolver): those consumers
4780    /// reach for the typed enum without going through the
4781    /// `.window()` scalar-projection layer, and get the enum value
4782    /// directly (which the codec's render arm can then format via
4783    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4784    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4785    /// primitive" discipline the sibling [`RateLimit::rate`] and
4786    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4787    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4788    /// projection axis (the third scalar accessor on the [`RateLimit`]
4789    /// axis, first typed-enum-return projection).
4790    ///
4791    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4792    /// the canonical [`RateLimitUnit`] arm now carries the same
4793    /// `const`-eval-surface posture the sibling `pub const fn`
4794    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4795    /// this typed sub-struct already carry, composing through the
4796    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4797    /// reverse-resolver in `const` context. Any downstream substrate-
4798    /// side `const`-context consumer of the typed unit (a module-scope
4799    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4800    /// invariant pin on a typed fixture, a future M4 admission-webhook
4801    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4802    /// resolver over a typed [`RateLimit`], any future `const fn`
4803    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4804    /// the substrate primitive) now reaches the same typed dispatch on
4805    /// the substrate primitive at const-eval time as at runtime.
4806    ///
4807    /// Pinned load-bearing at the substrate-primitive level by
4808    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4809    /// eval-surface pin via `const fn` wrapper).
4810    #[must_use]
4811    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4812        RateLimitUnit::from_window(self.window)
4813    }
4814}
4815
4816/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4817/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4818/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4819///
4820/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4821/// the `:politicas :rate-limit` unit surface reads from
4822/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4823/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4824/// [`is_canonical_rate_limit_window`] predicate the
4825/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4826/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4827/// projection) now lives inside this typed enum's `match self` arms — a
4828/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4829/// `rate_limit_action` grows daily-bucket support) is one new variant
4830/// plus the exhaustiveness arms on the four methods, so every consumer
4831/// picks it up by compile-time construction rather than a runtime
4832/// table-scan miss.
4833///
4834/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4835/// scanned via `find_map` at every projection call — an untyped runtime
4836/// walk that carried no compile-time link between the parse arm's
4837/// accepted suffixes, the render arm's emitted suffixes, and the
4838/// validate gate's accepted windows. A future rate-limit-unit addition
4839/// that landed one row without threading through the other consumers
4840/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4841/// silently split the accepted-set across the three consumers — the
4842/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4843/// for a 24h window that parse can't round-trip, the validate gate
4844/// misses one canonical window. Lifting the pairs onto a typed
4845/// closed-set enum with exhaustive `match` arms makes any such
4846/// half-landed extension a caixa-core build error (the compiler enforces
4847/// arm coverage on every method), not a silent per-consumer drift
4848/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4849/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4850/// [`crate::supervisor::RestartStrategy`],
4851/// [`crate::supervisor::RestartPolicy`],
4852/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4853/// closed-set typed enums carry on their respective closed-set axes —
4854/// extended onto the seventh closed-set typed-enum discriminator axis
4855/// on the caixa typed surface (the `:politicas :rate-limit :window`
4856/// canonical-unit axis).
4857#[derive(
4858    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4859)]
4860pub enum RateLimitUnit {
4861    /// 1-second window — canonical author-surface suffix `"s"`
4862    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4863    /// with a 1s magnitude.
4864    Second,
4865    /// 1-minute window — canonical author-surface suffix `"m"`
4866    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4867    /// with a 60s magnitude.
4868    Minute,
4869    /// 1-hour window — canonical author-surface suffix `"h"`
4870    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4871    /// with a 3600s magnitude.
4872    Hour,
4873}
4874
4875impl RateLimitUnit {
4876    /// Exhaustive iteration surface for every consumer that reads the
4877    /// full canonical-unit set (the byte-parity witness against the
4878    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4879    /// webhook's accepted-suffix listing in its rejection body, any
4880    /// future round-trip fuzz harness). A future variant addition to
4881    /// [`RateLimitUnit`] extends this slice as a single edit and every
4882    /// consumer picks up the new entry by construction — the compiler-
4883    /// checked exhaustiveness on the sibling method `match` arms is the
4884    /// build-time guarantee that no arm forgets to grow.
4885    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4886
4887    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4888    /// string every `<n>/<unit>` rate-limit shape carries after its
4889    /// `/` separator. The single source of truth the codec's parse and
4890    /// render arms both dispatch on: the parse arm matches an incoming
4891    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4892    /// output; the render arm emits the entry's `as_suffix` verbatim
4893    /// after the rate magnitude.
4894    #[must_use]
4895    pub const fn as_suffix(self) -> &'static str {
4896        match self {
4897            Self::Second => "s",
4898            Self::Minute => "m",
4899            Self::Hour => "h",
4900        }
4901    }
4902
4903    /// Canonical `Duration` for this unit — the token-bucket refill
4904    /// period the [`RateLimit::window`] axis carries when the surrounding
4905    /// slot's `:rate-limit` author surface named this unit.
4906    #[must_use]
4907    pub const fn window(self) -> Duration {
4908        Duration::from_secs(match self {
4909            Self::Second => 1,
4910            Self::Minute => 60,
4911            Self::Hour => 3_600,
4912        })
4913    }
4914
4915    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4916    /// `None` when `suffix` is outside the closed-set arm-string set
4917    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4918    /// [`rate_limit_codec::parse`] consumes.
4919    #[must_use]
4920    pub fn from_suffix(suffix: &str) -> Option<Self> {
4921        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4922    }
4923
4924    /// Recognize a canonical rate-limit `Duration` as one of the three
4925    /// arms, or `None` when `window` carries sub-second residue or a
4926    /// second-magnitude outside the closed-set arm-window set
4927    /// [`Self::window`] emits. The single `Duration → Self` projection
4928    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4929    /// both consume.
4930    ///
4931    /// `pub const fn` — the reverse `Duration → Self` projection now
4932    /// carries the same `const`-eval-surface posture the sibling
4933    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4934    /// projection accessors on this closed-set typed enum already
4935    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4936    /// typed-`RateLimit`-projection sibling composes through in `const`
4937    /// context. Routes byte-for-byte through the peer `pub const fn`
4938    /// [`Self::window`] canonical-`Duration` projection so any future
4939    /// arm-magnitude edit on the sibling accessor reaches this reverse
4940    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4941    /// per-arm probes each dispatch through one `pub const fn` on the
4942    /// substrate primitive rather than a hand-authored per-arm second-
4943    /// magnitude literal that would silently drift on any future
4944    /// [`Self::window`] arm-magnitude edit.
4945    ///
4946    /// Prior to the `const` lift the body dispatched through
4947    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4948    /// iterator-driven linear scan whose iterator methods
4949    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4950    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4951    /// Rust 1.94, so any downstream substrate-side `const`-context
4952    /// consumer of the reverse resolver (a module-scope
4953    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4954    /// invariant pin on a typed fixture, a future M4
4955    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4956    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4957    /// typed [`RateLimit`] scalar, any future `const fn`
4958    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4959    /// the substrate primitive that wants to fan on the canonical unit
4960    /// at compile time) surfaced as a downstream E0015 far from the
4961    /// resolver's own declaration. The `pub const fn` posture closes
4962    /// the drift structurally at caixa-core build time.
4963    ///
4964    /// Pinned load-bearing at the substrate-primitive level by
4965    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4966    /// eval-surface pin via `const fn` wrapper) and
4967    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4968    /// (composition-witness pin against the peer `Self::window` scalar
4969    /// dispatch).
4970    #[must_use]
4971    pub const fn from_window(window: Duration) -> Option<Self> {
4972        if window.subsec_nanos() != 0 {
4973            return None;
4974        }
4975        // Route through the peer `pub const fn` [`Self::window`]
4976        // canonical-`Duration` projection so any future arm-magnitude
4977        // edit on the sibling accessor reaches this reverse resolver by
4978        // construction — the per-arm `secs` comparison keys off
4979        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4980        // per-arm second-magnitude literal that would silently drift.
4981        let secs = window.as_secs();
4982        if secs == Self::Second.window().as_secs() {
4983            Some(Self::Second)
4984        } else if secs == Self::Minute.window().as_secs() {
4985            Some(Self::Minute)
4986        } else if secs == Self::Hour.window().as_secs() {
4987            Some(Self::Hour)
4988        } else {
4989            None
4990        }
4991    }
4992
4993    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4994    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4995    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4996    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4997    /// consumes.
4998    ///
4999    /// The peer `Duration → &'static str` axis folded onto the substrate
5000    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
5001    /// production consumers ([`rate_limit_codec::render`] and
5002    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
5003    /// migrated (61421a6): the free helper's `Duration → &str` projection
5004    /// is now the two-step composition
5005    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
5006    /// reads through the typed accessor. This lift closes the peer
5007    /// `&str → Duration` axis by folding the vestigial module-private
5008    /// `rate_limit_window_from_unit` delegate onto this associated method
5009    /// — the codec's parse arm and every future wire-side consumer of the
5010    /// `&str → Duration` projection (a future admission-webhook that
5011    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
5012    /// before it's promoted to a validated typed slot, a future
5013    /// `feira lint` shape-probe that reads the author-surface bytes
5014    /// verbatim) now reach for exactly one typed dispatch on the
5015    /// substrate primitive.
5016    ///
5017    /// Same "closed-set typed-enum discriminator with canonical
5018    /// projections per axis" discipline the sibling [`Self::as_suffix`]
5019    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
5020    /// methods carry — this associated method closes the fifth (and last
5021    /// unlifted) projection axis on the arm-table, so the closed-set enum
5022    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
5023    /// consumer of the `:politicas :rate-limit :window` axis reaches
5024    /// through. A future rate-limit-unit addition (a `"d"` day suffix
5025    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
5026    /// `"ms"` sub-second window once high-throughput per-edge policies
5027    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
5028    /// variant plus one arm per method — the compiler enforces
5029    /// exhaustiveness on every consumer's `match self` arms and picks
5030    /// the new unit up by construction across all five projections.
5031    #[must_use]
5032    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
5033        Self::from_suffix(suffix).map(Self::window)
5034    }
5035}
5036
5037/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
5038/// every consumer that formats a canonical rate-limit unit as user-
5039/// facing text (future M4 admission-webhook rejection bodies naming
5040/// the accepted-suffix set, future `feira app graph` per-`:politicas`
5041/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
5042/// codec's parse arm accepts and the render arm emits. Same
5043/// as_str-through-Display convergence discipline the sibling
5044/// [`PlacementStrategy`], [`crate::CaixaKind`],
5045/// [`crate::supervisor::RestartStrategy`], and
5046/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
5047impl std::fmt::Display for RateLimitUnit {
5048    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5049        f.write_str(self.as_suffix())
5050    }
5051}
5052
5053/// Substrate-canonical [`AsRef<str>`] projection on the M3
5054/// `:politicas :rate-limit` closed-set typed unit-suffix enum —
5055/// routes through the same [`RateLimitUnit::as_suffix`] `pub const fn`
5056/// scalar accessor the paired [`std::fmt::Display`] impl already
5057/// delegates through, so any future consumer that binds a
5058/// [`RateLimitUnit`] through the standard-library `impl AsRef<str>`
5059/// bound (a [`std::process::Command::arg`] shell-out that composes the
5060/// canonical suffix into an Envoy sidecar config-CLI's per-`:politicas`
5061/// `--rate-limit-unit <s|m|h>` arg on the future
5062/// `CiliumClusterwideEnvoyConfig` overlay MESH-COMPOSITION §III.2 #3
5063/// names, a `tracing::field::Value::Str`-arm structured-log recorder
5064/// on the future `app-operator`'s per-`:politicas :rate-limit`
5065/// reconcile step, a [`std::collections::HashMap`] lookup keyed on
5066/// the canonical suffix through `map.get::<str>(unit.as_ref())` on a
5067/// future per-unit token-bucket-refill dispatch table the future M4
5068/// admission-webhook rejection body composes) reaches the paired
5069/// `"s"` / `"m"` / `"h"` byte-string through one substrate-primitive
5070/// dispatch rather than an open-coded `.as_suffix()` re-inlining at
5071/// every wire-up.
5072///
5073/// Deliberately routes through the canonical suffix axis, not the
5074/// second-magnitude [`RateLimitUnit::window`] axis — `AsRef<str>` and
5075/// [`fmt::Display`] land on the same author-surface-canonical byte-
5076/// string the codec's parse and render arms both dispatch on, while
5077/// the token-bucket-refill period stays reachable only through the
5078/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
5079/// paths.
5080///
5081/// Same "route the trait impl through the substrate-primitive
5082/// accessor" discipline the sibling [`crate::CaixaVersion`]
5083/// [`AsRef<str>`] impl (16d5c7e), the paired M2
5084/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
5085/// (63eb1a4), the paired M2 [`crate::supervisor::RestartPolicy`]
5086/// [`AsRef<str>`] impl (419ea81), the M3
5087/// [`PlacementStrategy`] [`AsRef<str>`] impl (d86edd2), and the
5088/// top-level [`crate::CaixaKind`] [`AsRef<str>`] impl (cd2091f) carry
5089/// — closes the substrate primitive's [`AsRef<str>`] projection axis
5090/// onto the last remaining closed-set typed enum with a
5091/// [`fmt::Display`] surface, so every closed-set typed enum / newtype
5092/// on the caixa surface (top-level `:kind`, both M2
5093/// `:supervisor`-slot per-child and sibling-restart typed enums, the
5094/// M3 `:placement :estrategia` typed enum, the M3
5095/// `:politicas :rate-limit` unit-suffix typed enum, and the `:versao`
5096/// typed newtype) now carries the paired [`AsRef<str>`] +
5097/// [`fmt::Display`] + `as_*` triple through one lifted-const family.
5098///
5099/// Pinned load-bearing by
5100/// [`tests::rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`]
5101/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5102/// three-arm closed set) and
5103/// [`tests::rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`]
5104/// (three-path convergence: `AsRef<str>` + `Display` + `as_suffix`
5105/// all resolve to the same byte-string per arm) — any future silent
5106/// detour that routes the impl through a divergent projection (a
5107/// per-arm inline `match self { … }` re-inlining that opens a compile-
5108/// time link to the un-lifted arm-literal, a swap onto the
5109/// second-magnitude [`RateLimitUnit::window`] axis that would collide
5110/// the canonical-suffix / token-bucket-refill two-axis split) trips at
5111/// caixa-core test time under `assert_eq!` rather than at a downstream
5112/// `impl AsRef<str>`-bound consumer's silent split.
5113impl AsRef<str> for RateLimitUnit {
5114    fn as_ref(&self) -> &str {
5115        self.as_suffix()
5116    }
5117}
5118
5119/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
5120/// [`RateLimitUnit`] closed-set typed enum — routes byte-for-byte through
5121/// the paired substrate-primitive [`RateLimitUnit::from_suffix`]
5122/// `Option<Self>` accessor so every future consumer that binds a
5123/// canonical `:politicas :rate-limit` unit-suffix byte-string through the
5124/// standard-library `.try_into()` / [`TryFrom`] axis (a future
5125/// `feira app policy --rate-limit-unit <s|m|h>` CLI arg-parse that
5126/// composes into `let unit: RateLimitUnit = s.try_into()?`, a future
5127/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that folds a
5128/// `spec.politicas.rateLimit.unit: String` field through
5129/// `RateLimitUnit::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-bound
5130/// loader over any of the substrate's closed-set typed enums) reaches
5131/// the same three-arm accept-set the sibling
5132/// [`RateLimitUnit::from_suffix`] resolver parses through and the sibling
5133/// [`RateLimitUnit::as_suffix`] emits, rather than an open-coded per-arm
5134/// `match s { "s" => …, "m" => …, "h" => …, _ => … }` cascade whose
5135/// arm-set has no compile-time link back to the substrate primitive.
5136///
5137/// Complements the pre-existing forward-projection triple
5138/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`])
5139/// with the paired trait-idiomatic reverse-projection axis: Rust-side
5140/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
5141/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so
5142/// a caller who can project *out to* a `&str` can also project *in
5143/// from* one. The [`TryFrom<&str>`] axis is deliberately chosen over
5144/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
5145/// lint the sibling method-named [`RateLimitUnit::from_suffix`] would
5146/// trigger under a `FromStr` impl (the same design tradeoff the peer
5147/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
5148/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
5149/// (5b828ed), [`crate::supervisor::RestartPolicy`] (6fdd0d9), and
5150/// [`WitShape`] (5472902) blocks note) — this impl closes the trait-
5151/// idiomatic reverse axis without disturbing the method-named
5152/// `from_suffix` shape the peer closed-set typed enums already carry.
5153///
5154/// `type Error = ()` matches the sibling [`RateLimitUnit::from_suffix`]'s
5155/// `Option<Self>` return-shape's deliberate deferral of error typing:
5156/// the caller picks the diagnostic form appropriate for its use site (a
5157/// future `feira app policy --rate-limit-unit` arg-parse composes its
5158/// own per-verb "unknown rate-limit unit: <arg> — accepted: {…}"
5159/// message enumerating [`RateLimitUnit::ALL`], a future M4 admission-
5160/// webhook rejection body wraps the `Err(())` outcome with the accepted-
5161/// set enumeration for operator diagnostics, a `Result::map_err` at the
5162/// call site lifts the unit-error to a per-verb error type). Same shape
5163/// the peer sibling reverse-projection axes carry.
5164///
5165/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
5166/// set the [`RateLimitUnit::from_suffix`] resolver dispatches through,
5167/// so any future arm addition (a `"d"` day suffix once Envoy's
5168/// `rate_limit_action` grows daily-bucket support, a `"ms"` sub-second
5169/// window once high-throughput per-edge policies come into scope per
5170/// MESH-COMPOSITION §III.2 #3 — both trajectory items the sibling
5171/// [`RateLimitUnit::window_from_suffix`] doc block already names) grows
5172/// the trait-idiomatic axis by construction — one caixa-core edit on
5173/// [`RateLimitUnit::from_suffix`] extends both the method-named reverse
5174/// projection every existing consumer keys off and the trait-idiomatic
5175/// reverse projection this impl exposes, without a coordinated rewrite
5176/// across every future `TryFrom<&str>`-bound consumer's arm-set.
5177///
5178/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
5179/// projection family ([`crate::CaixaKind`] via 3c83606,
5180/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
5181/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
5182/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9, [`WitShape`] via
5183/// 5472902) onto the third M3-mesh-primitive-defining slot enum on the
5184/// caixa surface — the `:politicas :rate-limit` unit-suffix closed set
5185/// the caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5186/// `local_rate_limit.token_bucket.fill_interval` overlay emission, and
5187/// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-
5188/// webhook's per-`:politicas` accept-set validation.
5189///
5190/// Pinned load-bearing by
5191/// [`tests::rate_limit_unit_try_from_str_routes_through_from_suffix_accessor`]
5192/// (byte-parity pin against [`RateLimitUnit::from_suffix`] across the
5193/// three-arm accept-set) and
5194/// [`tests::rate_limit_unit_try_from_str_rejects_unknown_byte_strings`]
5195/// (rejection witness against silent accept-set widening).
5196impl TryFrom<&str> for RateLimitUnit {
5197    type Error = ();
5198
5199    fn try_from(s: &str) -> Result<Self, Self::Error> {
5200        Self::from_suffix(s).ok_or(())
5201    }
5202}
5203
5204/// Standard-library trait-idiomatic forward projection on the
5205/// [`RateLimitUnit`] closed-set typed enum. Routes byte-for-byte through
5206/// the paired substrate-primitive [`RateLimitUnit::as_suffix`]
5207/// `pub const fn` accessor so `<&'static str>::from(unit)` /
5208/// `unit.into::<&'static str>()` reaches the same three-arm `"s"` /
5209/// `"m"` / `"h"` canonical-suffix emit-set the sibling method-named
5210/// accessor dispatches through and the sibling
5211/// [`std::fmt::Display for RateLimitUnit`] / [`AsRef<str> for RateLimitUnit`]
5212/// impls also route through.
5213///
5214/// Extends the substrate-wide closed-set-enum trait-idiomatic
5215/// forward-projection family
5216/// ([`crate::supervisor::RestartStrategy`] via 523157d,
5217/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
5218/// [`crate::CaixaKind`] via edb827b,
5219/// [`crate::CaixaDialeto`] via c189a6f,
5220/// [`PlacementStrategy`] via afa3562,
5221/// [`WitShape`] via 56998ec) onto the third
5222/// M3-mesh-primitive-defining slot enum on the caixa surface — the
5223/// `:politicas :rate-limit` canonical-unit-suffix closed set the
5224/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5225/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
5226/// Pairs with the sibling [`TryFrom<&str> for RateLimitUnit`] impl
5227/// (bf78400) to close the two-way `Self ↔ &'static str` round-trip on
5228/// the trait-idiomatic axis pair, mirroring the pre-existing
5229/// method-named [`RateLimitUnit::as_suffix`] +
5230/// [`RateLimitUnit::from_suffix`] pair on the substrate-primitive axis
5231/// pair.
5232///
5233/// Return type is `&'static str` by construction — every
5234/// [`RateLimitUnit::as_suffix`] arm resolves to an inline
5235/// `"s"` / `"m"` / `"h"` `&'static str` literal, so the trait's
5236/// return-type promise is upheld structurally without a
5237/// [`String::leak`] cast or a per-arm inline literal outside the paired
5238/// [`RateLimitUnit::as_suffix`] dispatch.
5239///
5240/// Deliberately routes through the canonical-suffix axis, not the
5241/// second-magnitude [`RateLimitUnit::window`] axis — every closed-set
5242/// forward-projection path on the caixa surface lands on the same
5243/// author-surface-canonical byte-string the codec's parse and render
5244/// arms both dispatch on, while the token-bucket-refill period stays
5245/// reachable only through the explicit [`RateLimitUnit::window`] /
5246/// [`RateLimitUnit::from_window`] paths.
5247///
5248/// The paired [`RateLimitUnit::as_suffix`] accessor's three-arm emit-set
5249/// is the single source of truth — every future arm addition (a `"d"`
5250/// day suffix once Envoy's `rate_limit_action` grows daily-bucket
5251/// support, a `"ms"` sub-second window once high-throughput per-edge
5252/// policies come into scope per MESH-COMPOSITION §III.2 #3 — both
5253/// trajectory items the sibling [`RateLimitUnit::window_from_suffix`]
5254/// doc block already names) grows the trait-idiomatic forward axis by
5255/// construction: one caixa-core edit on [`RateLimitUnit::as_suffix`]
5256/// extends every one of the sibling forward-projection paths
5257/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`]
5258/// itself, and this [`From<Self> for &'static str`]) without a
5259/// coordinated rewrite across every future `Into<&'static str>`-bound
5260/// consumer's arm-set.
5261///
5262/// Pinned load-bearing by
5263/// [`tests::rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor`]
5264/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5265/// three-arm emit-set, plus a `const`-context materialization witness
5266/// for the `&'static str` lifetime promise routed through the paired
5267/// [`RateLimitUnit::as_suffix`] `pub const fn` accessor, plus a paired
5268/// `.into()` shape assertion covering the blanket-derived
5269/// `Into<&'static str>` shape) and
5270/// [`tests::rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set`]
5271/// (partition pin asserting `<&'static str as
5272/// From<RateLimitUnit>>::from` and [`RateLimitUnit::as_suffix`] agree on
5273/// every arm, plus a two-way direct round-trip witness through the
5274/// paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
5275/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic axis
5276/// pair — the emit-side [`RateLimitUnit::as_suffix`] and the parse-side
5277/// [`RateLimitUnit::from_suffix`] dispatch on the same three inline
5278/// canonical-suffix byte-strings by construction, so round-tripping
5279/// composes the two trait impls directly).
5280impl From<RateLimitUnit> for &'static str {
5281    fn from(unit: RateLimitUnit) -> &'static str {
5282        unit.as_suffix()
5283    }
5284}
5285
5286/// Trait-idiomatic *forward* projection on [`RateLimitUnit`] from a
5287/// *borrowed* input onto the `&'static str` axis — the borrowed-input
5288/// companion to the paired owned-input [`From<RateLimitUnit> for &'static
5289/// str`] impl immediately above. Routes byte-for-byte through the same
5290/// substrate-primitive [`RateLimitUnit::as_suffix`] `pub const fn`
5291/// accessor so every consumer that binds a `&RateLimitUnit` through the
5292/// standard-library `.into()` / [`From<&Self> for &'static str`] axis (a
5293/// `RateLimitUnit::ALL.iter().map(<&'static str>::from).collect::<Vec<_>>()`
5294/// per-arm accept-set materializer — whose iterator over
5295/// `&'static [RateLimitUnit]` yields `&RateLimitUnit`, not
5296/// `RateLimitUnit`, so the owned-input [`From<RateLimitUnit>`] axis alone
5297/// forces every call site through an explicit `.copied()` / dereference /
5298/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
5299/// projection; a future generic `<T: Copy + for<'a> Into<&'static str>>`-
5300/// bound diagnostic column over the substrate-wide closed-set typed-enum
5301/// family that walks the `iter().map(Into::into)` shape verbatim; the
5302/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
5303/// rejection body that composes the accepted-`:politicas :rate-limit`
5304/// canonical-suffix enumeration from an iterated
5305/// `RateLimitUnit::ALL.iter().map(|u| u.into())` pipe rather than a per-
5306/// arm `match u { … }` cascade; a future
5307/// `HashMap::<&'static str, RateLimitUnit>::from_iter(
5308///   RateLimitUnit::ALL.iter().map(|u| (u.into(), *u)))`-style per-unit
5309/// reverse-lookup table the sibling [`TryFrom<&str>`] impl cannot compose
5310/// without this borrowed-input axis in place) reaches the same three-arm
5311/// `"s"` / `"m"` / `"h"` canonical-suffix emit-set the paired owned-input
5312/// [`From<RateLimitUnit> for &'static str`], the sibling
5313/// [`std::fmt::Display`], [`AsRef<str>`], and [`RateLimitUnit::as_suffix`]
5314/// surfaces already return.
5315///
5316/// Eighth peer on the substrate-wide trait-idiomatic *borrowed-input*
5317/// forward-projection family opened on [`crate::dep::DepList`] (64aa742)
5318/// and extended onto [`crate::CaixaKind`] (5ab993a),
5319/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
5320/// [`crate::supervisor::RestartStrategy`] (e941836) and
5321/// [`crate::supervisor::RestartPolicy`] (842c7f3), and the M3
5322/// mesh-primitive slot enums [`PlacementStrategy`] (4d941d8) and
5323/// [`WitShape`] (3187bd0). Rust's `From` trait does not auto-derive the
5324/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
5325/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not exist
5326/// in `core`), so every closed-set typed enum that carries the owned-
5327/// input axis but not the borrowed-input axis forces every borrowed-input
5328/// call site through a `.copied()` / `<&'static str>::from(*unit)` /
5329/// `unit.as_suffix()` detour whose type bounds have no compile-time link
5330/// to the substrate primitive. [`RateLimitUnit`] is the *third* (and
5331/// last) M3-mesh-primitive-defining closed-set typed enum to converge
5332/// onto the substrate-wide borrowed-input campaign — the
5333/// [`PlacementStrategy`] first-mover (4d941d8) opened the M3-slot arm on
5334/// the `:placement :estrategia` axis, the [`WitShape`] follow-on
5335/// (3187bd0) closed the `:contratos :wit` census-label axis, and this
5336/// lift closes the `:politicas :rate-limit` canonical-suffix axis the
5337/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5338/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
5339///
5340/// Same three-path convergence discipline as the paired owned-input impl
5341/// (this borrowed-input axis, the paired owned-input
5342/// [`From<RateLimitUnit> for &'static str`], and
5343/// [`RateLimitUnit::as_suffix`] all route through the same three-arm
5344/// inline canonical-suffix byte-strings), so a future variant rename or
5345/// per-arm serde-attribute drift reaches every one of the six sibling
5346/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
5347/// [`Self::as_suffix`], [`From<Self> for &'static str`], this
5348/// [`From<&Self> for &'static str`], and the un-`rename`d
5349/// [`serde::Serialize`] derive that also emits [`Self::as_suffix`]'s
5350/// bytes) through exactly one caixa-core edit.
5351///
5352/// Deliberately routes through the canonical-suffix axis, not the
5353/// second-magnitude [`RateLimitUnit::window`] axis — the borrowed-input
5354/// `From` lands on the same author-surface-canonical byte-string the
5355/// codec's parse and render arms both dispatch on, while the token-
5356/// bucket-refill period stays reachable only through the explicit
5357/// [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`] paths, so
5358/// the canonical-suffix / token-bucket-refill two-axis split the sibling
5359/// [`AsRef<str>`] impl already carries reaches the borrowed-input axis
5360/// by construction.
5361///
5362/// The [`RateLimitUnit::as_suffix`] emit and
5363/// [`RateLimitUnit::from_suffix`] parse share the same three inline
5364/// canonical-suffix byte-strings by construction — so the borrowed-input
5365/// forward axis and the reverse [`TryFrom<&str>`] axis compose directly
5366/// without the intermediate wire-vocab hop the peer [`crate::CaixaKind`]
5367/// axis pair requires. The round-trip witness pin below locks this
5368/// direct composition on the M3 slot enum's trait-idiomatic axis pair.
5369///
5370/// Pinned load-bearing by
5371/// [`tests::rate_limit_unit_from_borrowed_into_static_str_routes_through_as_suffix_accessor`]
5372/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5373/// three-arm emit-set via a borrowed input, plus a `const`-context
5374/// materialization witness for the `&'static str` lifetime promise, plus
5375/// a blanket `.into()` shape) and
5376/// [`tests::rate_limit_unit_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
5377/// (cross-axis partition pin against the paired owned-input
5378/// [`From<RateLimitUnit> for &'static str`] impl, plus a
5379/// `.iter().map(Into::into)` pipe witness over [`RateLimitUnit::ALL`],
5380/// plus a direct round-trip witness through [`TryFrom<&str>`] that closes
5381/// the two-way `&Self → &'static str → Self` round-trip on the M3 slot
5382/// enum's trait-idiomatic axis pair without the wire-vocab intermediate
5383/// the peer [`crate::CaixaKind`] axis pair requires).
5384impl From<&RateLimitUnit> for &'static str {
5385    fn from(unit: &RateLimitUnit) -> &'static str {
5386        unit.as_suffix()
5387    }
5388}
5389
5390/// Upper-bound ceiling on the `:politicas :timeout` axis — every
5391/// validated [`MeshPolicy::timeout`] past
5392/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
5393/// (inclusive on both ends, integer-millisecond magnitudes by the
5394/// canonical-form gate immediately preceding).
5395///
5396/// The typed field is `Option<Duration>` (the zero-floor arm
5397/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
5398/// `Duration::ZERO`, and the canonical-form arm
5399/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
5400/// sub-millisecond residue), so a programmatic struct literal
5401/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
5402/// 24h) and the equivalent author-surface form
5403/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
5404/// integer-hour magnitude) both round-trip cleanly through serde — a
5405/// structurally unbounded `Duration` ceiling. A `:timeout` value far
5406/// above the documented production-playbook band (Envoy default `15s`,
5407/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
5408/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
5409/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
5410/// at `~3600s`) silently degenerates the mesh-policy contract: the
5411/// per-call deadline is structurally so long that no realistic
5412/// synchronous-`:contratos` traversal can reach it, so the typed slot
5413/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
5414/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
5415/// blocking" degenerates to a nominal-only contract on the
5416/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
5417/// the sibling `:politicas :retries` axis and the
5418/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
5419/// `:politicas :circuit-breaker :max-failures` axis — all three close
5420/// the "structurally unbounded ceiling on a typed `:politicas` axis"
5421/// footgun the prior zero-floor-and-canonical-form-only checks left
5422/// open.
5423///
5424/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
5425/// shared duration codec emits (`"<n>h"` for any integer-hour
5426/// magnitude) — every value in the canonical authoring form's
5427/// `<integer><unit>` grammar at or below this cap renders to a clean
5428/// canonical string. The cap sits an order of magnitude above every
5429/// documented production-playbook recommendation band (Envoy default
5430/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
5431/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
5432/// configured maximum (`proxy_read_timeout` typical max `3600s`),
5433/// below the clearly-pathological "effectively no timeout" floor
5434/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
5435/// want for a long-running synchronous workflow, but a hard wall above
5436/// which the mesh-level deadline is structurally a non-deadline.
5437/// Lifted as a typed `pub const` so the bound has exactly one source
5438/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5439/// materializer's admission webhook and the caixa-mesh-side
5440/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5441/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
5442/// other typed upper bound in this crate carries
5443/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
5444/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5445/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5446/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5447pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
5448
5449/// Upper-bound ceiling on the `:politicas :retries` axis — every
5450/// validated [`MeshPolicy::retries`] past
5451/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
5452///
5453/// The typed slot is `Option<u32>` (`None` = no retries on transient
5454/// failure; `Some(0)` already rejected by the
5455/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
5456/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
5457/// .. }`) and the equivalent author-surface form
5458/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
5459/// serde / the codec — a structurally unbounded `u32` ceiling. The
5460/// runtime substrate that consumes the value (Envoy's
5461/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
5462/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
5463/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
5464/// admission cap is 10) translates a four-billion-retry policy into a
5465/// thundering-herd amplification vector on transient failure — the
5466/// caller's one request fans out to `retries` server-side calls per
5467/// edge per traversal, multiplying load by `(retries+1)^depth` across
5468/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
5469/// invariant "no infinite blocking" pairs with a no-runaway-amplification
5470/// invariant on the retry axis; both belong at the typed-slot layer.
5471///
5472/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
5473/// upstream mesh-policy schema that documents one) and sits above the
5474/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
5475/// every documented production playbook): a value the author can
5476/// plausibly want, but a hard wall above which the policy is
5477/// structurally a footgun. Lifted as a typed `pub const` so the bound
5478/// has exactly one source of truth — a future axis reaching for the
5479/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5480/// materializer's admission webhook, the caixa-mesh-side
5481/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
5482/// one place. Same shape every other typed upper bound in this crate
5483/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5484/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5485/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
5486/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5487pub const POLICY_RETRIES_MAX: u32 = 10;
5488
5489/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
5490/// axis — every validated [`CircuitBreaker::max_failures`] past
5491/// [`AplicacaoSpec::validate_politicas`] lies in
5492/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
5493///
5494/// The typed field is `u32` (the zero-floor arm
5495/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
5496/// `0` — a breaker that trips on the first call), so a programmatic
5497/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
5498/// and the equivalent author-surface form
5499/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
5500/// cleanly through serde — a structurally unbounded `u32` ceiling. A
5501/// `max_failures` value far above the documented production-playbook
5502/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
5503/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
5504/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
5505/// typical 5–50) silently disables the breaker's protection role:
5506/// the threshold is structurally so high that no realistic
5507/// failures-per-`:window` traffic shape can reach it, so the breaker
5508/// never trips and the typed slot becomes a no-op carried on every
5509/// emitted Envoy / Cilium L7 overlay. Pairs with the
5510/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
5511/// axis — both close the "structurally unbounded `u32` ceiling on a
5512/// typed policy axis" footgun the prior zero-floor-only checks left
5513/// open.
5514///
5515/// The `1000` ceiling sits an order of magnitude above every
5516/// documented upstream production-playbook recommendation band (the
5517/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
5518/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
5519/// the clearly-pathological "effectively no protection"
5520/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
5521/// plausibly want at hyperscale, but a hard wall above which the
5522/// policy is structurally a no-op. Lifted as a typed `pub const` so
5523/// the bound has exactly one source of truth — the future M4
5524/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
5525/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
5526/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
5527/// one place. Same shape every other typed upper bound in this crate
5528/// carries ([`POLICY_RETRIES_MAX`],
5529/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5530/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5531/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5532pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
5533
5534/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
5535/// every validated [`CircuitBreaker::window`] past
5536/// [`AplicacaoSpec::validate_politicas`] lies in
5537/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
5538/// integer-millisecond magnitudes by the canonical-form gate
5539/// immediately preceding).
5540///
5541/// The typed field is `Duration` (the zero-floor arm
5542/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
5543/// `Duration::ZERO`, and the canonical-form arm
5544/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
5545/// sub-millisecond residue), so a programmatic struct literal
5546/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
5547/// and the equivalent author-surface form
5548/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
5549/// integer-hour magnitude) both round-trip cleanly through serde — a
5550/// structurally unbounded `Duration` ceiling. A `:window` value far
5551/// above the documented production-playbook band (Hystrix
5552/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
5553/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
5554/// Istio `outlierDetection.interval` default `10s`, Envoy
5555/// `outlier_detection.interval` default `10s`, AWS App Mesh
5556/// circuit-breaker time-window typical `30s..=300s`) degenerates the
5557/// breaker's role: a rolling-window failure counter whose window is
5558/// hours long is operationally a lifetime counter, the breaker's
5559/// "recent failures" memory is structurally so long that transient
5560/// failures are never forgotten, and the typed slot becomes a no-op
5561/// trigger that trips once and stays tripped for the lifetime of the
5562/// component carried on every emitted Envoy / Cilium L7 overlay.
5563///
5564/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
5565/// shared duration codec emits (`"<n>h"` for any integer-hour
5566/// magnitude) — every value in the canonical authoring form's
5567/// `<integer><unit>` grammar at or below this cap renders to a clean
5568/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
5569/// cap on the first typed-`Duration` `:politicas` axis: the two
5570/// duration-typed `:politicas` axes now share a single uniform top
5571/// edge so the next typed-slot wiring (the future caixa-mesh
5572/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
5573/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
5574/// admission webhook) reaches for either field knowing the value is
5575/// in `1ms..=1h` without re-validating at the renderer layer. The cap
5576/// sits two orders of magnitude above every documented upstream
5577/// production-playbook recommendation band (Hystrix / resilience4j /
5578/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
5579/// and below the clearly-pathological "rolling window degenerates to
5580/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
5581/// author can plausibly want for a very-low-traffic long-tail
5582/// failure-detection window, but a hard wall above which the breaker's
5583/// rolling-window contract is structurally a lifetime-counter contract.
5584/// Lifted as a typed `pub const` so the bound has exactly one source
5585/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5586/// materializer's admission webhook and the caixa-mesh-side
5587/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5588/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
5589/// other typed upper bound in this crate carries
5590/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5591/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
5592/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5593/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5594/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5595pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
5596
5597/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
5598/// every validated [`RateLimit::rate`] past
5599/// [`AplicacaoSpec::validate_politicas`] lies in
5600/// `1..=POLICY_RATE_LIMIT_MAX`.
5601///
5602/// The typed field is `u32` (the zero-floor arm
5603/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
5604/// zero-rate limit denies every request, the canonical "I forgot
5605/// that 0 means deny-everything" footgun), so a programmatic struct
5606/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
5607/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
5608/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
5609/// round-trip cleanly through serde — a structurally unbounded `u32`
5610/// ceiling. The runtime substrate consuming the value (Envoy's
5611/// `local_rate_limit.token_bucket.max_tokens`, the future
5612/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5613/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
5614/// rate-limit into a no-op rate-limiter: the bucket capacity is
5615/// structurally so high no realistic per-edge traffic shape can
5616/// drain it, the limiter never trips, and the typed slot becomes a
5617/// "rate-limit declared, no enforcement" footgun — the canonical
5618/// declared-but-inert shape every other `:politicas` cap arm
5619/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
5620/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
5621///
5622/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
5623/// above every documented upstream production-playbook recommendation
5624/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
5625/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
5626/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
5627/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
5628/// `limit_req_zone` typical `1..=1_000` RPS) and below the
5629/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
5630/// `u32::MAX`): a value the author can plausibly want at hyperscale
5631/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
5632/// /h-window arm), but a hard wall above which the policy is
5633/// structurally a no-op carried verbatim on every emitted Envoy /
5634/// Cilium L7 overlay. The cap brackets all three canonical windows
5635/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
5636/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
5637/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
5638/// per-endpoint API band). Lifted as a typed `pub const` so the bound
5639/// has exactly one source of truth — the future M4
5640/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
5641/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
5642/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
5643/// one place. Same shape every other typed upper bound in this crate
5644/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5645/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5646/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5647/// [`crate::LIMITS_WALL_CLOCK_MAX`],
5648/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5649/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5650pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
5651
5652// `:entrada :host` total-length and per-label cap axes route through
5653// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
5654// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
5655// pair of aplicacao-private aliases the previous `validate_entrada_host`
5656// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
5657// = 63`) were structurally the same K8s Gateway API v1 Hostname
5658// admission-schema bounds — the total-length cap on the OpenAPI
5659// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
5660// same regex — that the peer axes at the caixa-core::render level pin,
5661// so hoisting both readers onto the shared lifted constants closes the
5662// third-occurrence duplication threshold structurally: the M4
5663// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
5664// label validator, the future per-`Certificate` SAN emitter, and every
5665// other per-Gateway-API-Hostname landing site reach the same one place
5666// as the `:entrada :host` gate does — no per-axis alias drift surface
5667// between them, by construction.
5668
5669/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
5670/// extractor expression — the upper bound `validate_placement_shard_key`
5671/// enforces on every well-shaped shard-key past validate. The realistic
5672/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
5673/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
5674/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
5675/// `:placement :affinity` / `:placement :clusters` identifier-shaped
5676/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
5677/// in `:shard-key`" footgun at validate time rather than at the future
5678/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
5679const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
5680
5681/// Reject `:membros :caixa` values the K8s apiserver would refuse at
5682/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
5683/// that maps the shared parser-shaped reason into the
5684/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
5685/// is self-locating (the offending `caixa:` is named verbatim) and
5686/// the author can grep their caixa.lisp for `:caixa "<name>"` and
5687/// fix it in one edit. Same diagnostic shape as
5688/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
5689/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
5690fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
5691    // Empty is already gated by `MembroCaixaEmpty` at the call site;
5692    // re-checking here keeps the predicate usable from any future
5693    // call site (the M4 CR materializer) without an empty-check
5694    // footgun. The shared
5695    // [`crate::render::require_valid_dns_1123_label`] helper brackets
5696    // the empty-first + shape cascade every peer name axis
5697    // (`:placement :clusters`, `:placement :affinity`, `:contratos
5698    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
5699    // `:upgrade-from :module`) routes through, so drift between the
5700    // eight axes' accepted DNS-1123-label sets is structurally
5701    // impossible.
5702    crate::render::require_valid_dns_1123_label(
5703        caixa,
5704        || AplicacaoError::MembroCaixaEmpty,
5705        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
5706    )
5707}
5708
5709/// Reject `:placement :clusters` entries the K8s apiserver would refuse
5710/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
5711/// that maps the shared parser-shaped reason into the
5712/// [`AplicacaoError::PlacementClusterInvalid`] variant.
5713///
5714/// Cluster names land in DNS-1123-label territory across every consumer:
5715/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
5716/// the `lareira-fleet-programs` aggregator applies to scope programs to
5717/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
5718/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
5719/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
5720/// cluster identity the M4 CR materializer round-trips. Each apiserver-
5721/// side schema enforces the DNS-1123 label rule on admission; a
5722/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
5723/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
5724/// mistaken-identity slug) silently passes the prior empty-/duplicate-
5725/// only gate and the failure surfaces as a no-match at filter time —
5726/// the workload doesn't land in the named cluster, with no diagnostic
5727/// naming the offending `:clusters` entry. Lifting the gate to caixa-
5728/// build time mirrors the `:membros :caixa` value-shape trajectory
5729/// (3f9d7a0) on the peer name axis.
5730///
5731/// The diagnostic carries the offending `cluster:` verbatim plus a
5732/// parser-shaped `reason:` naming the specific violation, so the
5733/// author can grep their caixa.lisp for `:clusters` and fix it in
5734/// one edit. Same diagnostic shape as
5735/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
5736fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
5737    // Empty is already gated by `PlacementClusterEmpty` at the call
5738    // site; re-checking here keeps the predicate usable from any
5739    // future call site (the M4 CR materializer's per-cluster validator)
5740    // without an empty-check footgun. Routes through the shared
5741    // [`crate::render::require_valid_dns_1123_label`] gate the peer
5742    // name axes each land on.
5743    crate::render::require_valid_dns_1123_label(
5744        cluster,
5745        || AplicacaoError::PlacementClusterEmpty,
5746        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
5747    )
5748}
5749
5750/// Reject `:placement :affinity` hints whose shape can never legitimately
5751/// land in any downstream selector or label-keyed routing axis. Thin
5752/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5753/// shared parser-shaped reason into the
5754/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
5755/// diagnostic is self-locating (the offending `:affinity` is named
5756/// verbatim) and the author can grep their caixa.lisp for
5757/// `:affinity "<hint>"` and fix it in one edit.
5758///
5759/// The `:affinity` slot carries a placement-engine hint — canonical
5760/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
5761/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
5762/// compression overlay and the future M4 placement-engine's per-hint
5763/// routing axis. Each downstream consumer (caixa-mesh's
5764/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
5765/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5766/// `spec.placement.affinity` admission rule, the future M4 per-hint
5767/// node-affinity / pod-affinity rule generator keying off the same
5768/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
5769/// selector) requires the value to be a DNS-1123 label — K8s label
5770/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
5771/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
5772/// admission rule the apiserver enforces.
5773///
5774/// Until this gate landed an `:affinity "DataLocality"` (the canonical
5775/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
5776/// Python-module-name leak), `:affinity "data.locality"` (the
5777/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
5778/// `:affinity "data-locality-"` (boundary-hyphen violation),
5779/// `:affinity "data locality"` (paste-from-doc whitespace),
5780/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
5781/// 64-byte over-cap slug silently passed the empty-only check and the
5782/// failure surfaced as a no-match at the M3 Adaptive compression
5783/// overlay's filter time (`placement.affinity` carried a malformed
5784/// value, no node matched, the workload landed on the default
5785/// heuristic) — the canonical "declared-but-inert" footgun mirroring
5786/// the empty-:affinity / empty-shard-key / zero-:politicas /
5787/// empty-:contratos-target gates already close on every other
5788/// declare-but-no-opinion axis. Lifting the rejection to a build-time
5789/// gate closes the fifth typed slot on the Aplicacao surface to land
5790/// on the canonical DNS-1123 label floor (after the four Servico-name
5791/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
5792/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
5793/// b0e8748).
5794///
5795/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
5796/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
5797/// validated values are guaranteed-accepted by the apiserver without
5798/// re-validation at any downstream renderer or admission layer.
5799fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
5800    // Empty is gated separately at the call site for a self-locating
5801    // diagnostic; re-checking here keeps the predicate usable from any
5802    // future call site (the M4 CR materializer's per-affinity
5803    // validator) without an empty-check footgun. Routes through the
5804    // shared [`crate::render::require_valid_dns_1123_label`] gate the
5805    // peer name axes each land on.
5806    crate::render::require_valid_dns_1123_label(
5807        affinity,
5808        || AplicacaoError::PlacementAffinityEmpty,
5809        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
5810    )
5811}
5812
5813/// Reject `:placement :shard-key` extractor expressions whose shape can
5814/// never legitimately drive the future M4 Akka-style cluster-sharding
5815/// reconciler's hash-extractor pass. Maps the per-byte / length checks
5816/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
5817/// diagnostic is self-locating (the offending `:shard-key` value is
5818/// named verbatim alongside the parser-shaped reason) and the author can
5819/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
5820/// edit.
5821///
5822/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
5823/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
5824/// expression naming the message property to hash on. The realistic
5825/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
5826/// property name; `$tenantId` — Akka entity-id placeholder;
5827/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
5828/// `${tenant}` — interpolation-style template) all sit in the printable
5829/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
5830/// multi-line blob landing in `:shard-key`, an embedded space from a
5831/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
5832/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
5833/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
5834/// check and the failure surfaces at the future M4 reconciler's hash
5835/// pass as a runtime extractor-evaluation error far from the source
5836/// `caixa.lisp`, with no field naming which member's `:shard-key`
5837/// carried the offending value.
5838///
5839/// The contract — the printable ASCII single-token intersection-floor
5840/// every Akka-style entity-id extractor implementation admits:
5841///
5842///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
5843///     peer DNS-1123-label-shaped `:placement :affinity` /
5844///     `:placement :clusters` identifier axes; realistic shard-keys sit
5845///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
5846///     blob footguns at validate time;
5847///   - every byte in the printable ASCII range `0x21..=0x7E` —
5848///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
5849///     `"$tenantId\n"` from paste-from-aligned-doc /
5850///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
5851///     `\x7F` — the canonical "embedded null from a copy-paste-binary
5852///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
5853///     un-Punycode-encoded IDN that round-trips inconsistently across
5854///     NFC/NFD normalization).
5855///
5856/// The accepted set is broader than the DNS-1123 label floor the peer
5857/// `:placement :clusters` / `:placement :affinity` axes use because the
5858/// `:shard-key` value is not a K8s `metadata.name` / label-selector
5859/// landing site; it's an extractor expression the future Akka-style
5860/// reconciler reads as a property reference. The realistic forms
5861/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
5862/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
5863/// but every Akka-style entity-id extractor parses. The
5864/// printable-ASCII-token floor accepts every shape any such extractor
5865/// would accept while rejecting the cross-implementation footguns
5866/// (whitespace breaks token boundaries; non-ASCII round-trips
5867/// inconsistently across YAML emitters and NFC/NFD normalization;
5868/// control characters silently corrupt the next read).
5869///
5870/// Until this gate landed `validate_placement` only refused the
5871/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
5872/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
5873/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
5874/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
5875/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
5876/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
5877/// control character from paste-from-binary, the 64-byte over-cap
5878/// paste-from-doc multi-line slug) silently passed validate. The future
5879/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
5880/// would then surface the malformed value either as a runtime
5881/// extractor-evaluation error (whitespace breaks the extractor's token
5882/// boundary, no match) or as a silently-different shard assignment
5883/// across YAML emitters (non-ASCII normalizes differently between the
5884/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
5885/// parser, the same entity ID maps to two distinct shards on a
5886/// re-render). Lifting the shape gate to caixa-build time makes the
5887/// extractor-floor invariant a structural property of every validated
5888/// `Placement`: every `Sharded` placement past `validate_placement` has
5889/// a `:shard-key` the future M4 reconciler can hash without
5890/// re-validating at the runtime layer.
5891///
5892/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
5893/// [`AplicacaoError::ContratoSubjectInvalid`] /
5894/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
5895/// on the peer `:contratos` payload axes — each lifts the
5896/// runtime-side parser's intersection-floor to a caixa-build-time gate,
5897/// closing the canonical "this passed validate but the runtime parser
5898/// rejected it" surprise.
5899fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
5900    // Empty is gated separately at the call site via the more
5901    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
5902    // re-checking here keeps the predicate usable from any future call
5903    // site (the M4 CR materializer's per-shard-key validator) without
5904    // an empty-check footgun.
5905    if key.is_empty() {
5906        return Err(AplicacaoError::ShardedKeyEmpty);
5907    }
5908    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
5909        return Err(AplicacaoError::shard_key_invalid(
5910            key,
5911            format!(
5912                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
5913                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
5914                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
5915                 well under 32 bytes, this length suggests a paste-from-doc \
5916                 multi-line blob landed in `:shard-key` instead of a single-token \
5917                 extractor expression)",
5918                key.len()
5919            ),
5920        ));
5921    }
5922    for &b in key.as_bytes() {
5923        if (0x21..=0x7E).contains(&b) {
5924            continue;
5925        }
5926        let reason = if b == b' ' {
5927            "contains a space (Akka-style entity-id extractor expressions are \
5928             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
5929             whitespace breaks the extractor's token boundary at the runtime layer, \
5930             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
5931             a multi-token blob in one `:shard-key` slot)"
5932                .to_string()
5933        } else if b == b'\t' {
5934            "contains a tab character (paste-from-aligned-doc footgun; the \
5935             Akka-style entity-id extractor reads `:shard-key` as a single-token \
5936             reference, embedded whitespace breaks the token boundary at the \
5937             runtime hash-extractor pass)"
5938                .to_string()
5939        } else if b == b'\n' || b == b'\r' {
5940            format!(
5941                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
5942                 paste-from-multiline-doc footgun; the Akka-style entity-id \
5943                 extractor reads `:shard-key` as a single-token reference, embedded \
5944                 newlines either truncate the value at the YAML emitter layer or \
5945                 break the token boundary at the runtime hash-extractor pass)"
5946            )
5947        } else if b < 0x20 || b == 0x7F {
5948            format!(
5949                "contains control character 0x{b:02x} (the canonical \
5950                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
5951                 control characters silently corrupt round-trip serialization \
5952                 across YAML emitters and break the runtime hash-extractor's \
5953                 single-token parser)"
5954            )
5955        } else {
5956            format!(
5957                "contains non-ASCII byte 0x{b:02x} (the canonical \
5958                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
5959                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
5960                 across YAML emitter implementations — the same entity ID can \
5961                 silently map to two distinct shards on a re-render. Use a \
5962                 printable-ASCII extractor expression like `tenantId`, \
5963                 `$tenantId`, or `metadata.tenantId`)"
5964            )
5965        };
5966        return Err(AplicacaoError::shard_key_invalid(key, reason));
5967    }
5968    Ok(())
5969}
5970
5971/// Reject `:contratos :de` / `:contratos :para` values whose shape
5972/// can never legitimately match a validated `:membros :caixa`. Thin
5973/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5974/// shared parser-shaped reason into the
5975/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
5976/// diagnostic is self-locating (which slot — `:de` or `:para` — and
5977/// the offending value verbatim) and the author can grep their
5978/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
5979/// one edit.
5980///
5981/// Until this gate landed an empty or DNS-1123-malformed `:de` /
5982/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
5983/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
5984/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
5985/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
5986/// un-Punycode-encoded IDN) silently passed the per-axis check and
5987/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
5988/// membership lookup — diagnostic-framed as "this caixa is not in
5989/// `:membros`" when the root cause is "this `:de` value is not a
5990/// well-shaped Servico-name identifier and could never legitimately
5991/// match any validated member". Because every `:membros :caixa` is
5992/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
5993/// `names` HashSet structurally never contains an empty / malformed
5994/// string, so the membership lookup arm misframes every empty /
5995/// malformed input. Lifting the shape arm ahead of the lookup
5996/// preserves the legitimate `ContratoMemberMissing` arm (a
5997/// well-shaped `:de` that simply isn't in `:membros` — a phantom
5998/// reference) while routing every structurally-impossible-to-match
5999/// input through the narrower self-locating shape diagnostic.
6000///
6001/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
6002/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
6003/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
6004/// to land on the canonical [`crate::render::is_dns_1123_label`]
6005/// floor. The `slot: &'static str` field carries the kebab-case
6006/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
6007/// per-callback-slot diagnostic shape and the
6008/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
6009/// (85f102c) cross-list-tag pattern.
6010fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
6011    // Routes through the shared
6012    // [`crate::render::require_valid_dns_1123_label`] gate the peer
6013    // name axes each land on. The `slot: &'static str` field flows
6014    // through both error variants so the diagnostic names which
6015    // per-edge axis (`:de` vs `:para`) the offending value came from.
6016    crate::render::require_valid_dns_1123_label(
6017        caixa,
6018        || AplicacaoError::contrato_caixa_empty(slot),
6019        |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
6020    )
6021}
6022
6023/// Reject `:entrada :para` values whose shape can never legitimately
6024/// match a validated `:membros :caixa`. Thin wrapper around
6025/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
6026/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
6027/// variant, so the diagnostic is self-locating (the offending
6028/// `:entrada :para` value is named verbatim) and the author can grep
6029/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
6030///
6031/// Until this gate landed an empty or DNS-1123-malformed `:entrada
6032/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
6033/// ADR typo, `:para "my_cart"` the Python-module-name leak,
6034/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
6035/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
6036/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
6037/// silently passed the per-axis check and surfaced as
6038/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
6039/// — diagnostic-framed as "this caixa is not in `:membros`" when the
6040/// root cause is "this `:entrada :para` value is not a well-shaped
6041/// Servico-name identifier and could never legitimately match any
6042/// validated member". Because every `:membros :caixa` is shape-
6043/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
6044/// `HashSet` structurally never contains an empty / malformed string,
6045/// so the membership lookup arm misframes every empty / malformed
6046/// input. Lifting the shape arm ahead of the lookup preserves the
6047/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
6048/// simply isn't in `:membros` — a phantom reference) while routing
6049/// every structurally-impossible-to-match input through the narrower
6050/// self-locating shape diagnostic.
6051///
6052/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
6053/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
6054/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
6055/// fourth and last Aplicacao-level Servico-name reference axis to
6056/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
6057/// No `slot: &'static str` field because there is only one axis
6058/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
6059/// the simpler shape mirrors [`validate_membro_caixa`] and
6060/// [`validate_placement_cluster`].
6061fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
6062    // Empty is gated separately at the call site for a self-locating
6063    // diagnostic; re-checking here keeps the predicate usable from any
6064    // future call site (the M4 CR materializer's per-`:entrada`
6065    // validator) without an empty-check footgun. Routes through the
6066    // shared [`crate::render::require_valid_dns_1123_label`] gate the
6067    // peer name axes each land on.
6068    crate::render::require_valid_dns_1123_label(
6069        para,
6070        || AplicacaoError::EntradaParaEmpty,
6071        |reason| AplicacaoError::entrada_para_invalid(para, reason),
6072    )
6073}
6074
6075/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
6076/// would refuse at admission time. The contract — exactly the regex
6077/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
6078/// and `HTTPRoute.spec.hostnames[]`,
6079/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
6080/// (max length 253; per-label max length 63):
6081///
6082///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
6083///     uppercase, no underscore, no Unicode/IDN — IDN must be
6084///     pre-encoded as Punycode `xn--…` by the author);
6085///   - exactly one optional leading wildcard label (`*.`); a wildcard
6086///     in any non-leading label position is rejected;
6087///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
6088///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
6089///   - total length 1..=253 bytes;
6090///   - no IPv4 literal (Gateway API forbids IP literals);
6091///   - no scheme (`https://`, `http://`), no port (`:8080`), no
6092///     whitespace, no path (`/`).
6093///
6094/// Lifted as a typed gate (rather than an inline cascade in
6095/// `validate()`) so the contract lives in one place — every future
6096/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6097/// materializer's host validator, the future per-`:entrada` SAN
6098/// emission for cert-manager Certificates, the multi-`:entrada`
6099/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
6100/// for the same predicate, not its own. Same compounding shape as
6101/// `is_canonical_rate_limit_window` (808017c) and
6102/// [`WitTarget::label`] (previously the free `contrato_target_label`
6103/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
6104/// per-variant label match is compiler-checked-exhaustive).
6105///
6106/// The diagnostic carries the offending `host:` verbatim plus a
6107/// parser-shaped `reason:` naming the specific violation, so the
6108/// author can grep their caixa.lisp for `:host "<host>"` and fix it
6109/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
6110/// (9888b13).
6111fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
6112    // Empty is already gated by `EmptyEntradaHost` at the call site;
6113    // re-checking here keeps the predicate usable from any future
6114    // call site (M4 CR materializer) without an empty-check footgun.
6115    if host.is_empty() {
6116        return Err(AplicacaoError::EmptyEntradaHost);
6117    }
6118    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
6119        return Err(AplicacaoError::entrada_host_invalid(
6120            host,
6121            format!(
6122                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
6123                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
6124                host.len(),
6125                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
6126            ),
6127        ));
6128    }
6129    if host.contains("://") {
6130        return Err(AplicacaoError::entrada_host_invalid(
6131            host,
6132            "must not carry a scheme (drop the `https://` or `http://` prefix; \
6133             Gateway API takes the bare hostname)",
6134        ));
6135    }
6136    if host.contains('/') {
6137        return Err(AplicacaoError::entrada_host_invalid(
6138            host,
6139            "must not carry a path (drop the `/…` suffix; Gateway API path \
6140             matching is in `:entrada :paths`)",
6141        ));
6142    }
6143    // After the `://` scheme-prefix and `/` path arms have ruled out the
6144    // two `:`-bearing shapes the Gateway API actively rejects with
6145    // location-shaped diagnostics, any remaining `:` in the host body is
6146    // either the canonical "I put the port in the `:host` slot"
6147    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
6148    // slot lives one axis away on the same `:entrada` block) or an
6149    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
6150    // Hostname forbids identically to the IPv4-literal arm below. Both
6151    // shapes silently fell through the `://` and `/` arms before this
6152    // lift and surfaced as a deep `label "<rest>:<port>" contains
6153    // invalid character ':'` diagnostic from the per-byte loop near the
6154    // bottom of this predicate, which named the offending byte but not
6155    // the canonical authoring fix — for the port case the author has to
6156    // know the `:entrada` block carries a separate `:port u16` slot
6157    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
6158    // move the value over; for the IPv6 case the author has to know
6159    // Gateway API v1 forbids IP literals across the board. The contract
6160    // doc-comment above already promises "no port (`:8080`)" verbatim
6161    // in the rejected-shape enumeration but the predicate's
6162    // implementation refused the `:` only as a side-effect of the
6163    // per-label `[a-z0-9-]` character-class loop; this arm brings the
6164    // implementation in line with the documented contract by surfacing
6165    // the canonical fix at the top-level shape gate, peer with how the
6166    // `://` arm names the scheme prefix and the `/` arm names the
6167    // `:entrada :paths` axis. Same compounding trajectory the recent
6168    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
6169    // — the typed slot's rejected set matches the apiserver's rejected
6170    // set, structurally, with a self-locating diagnostic at the
6171    // offending axis instead of a deep parser-shape leak.
6172    if host.contains(':') {
6173        return Err(AplicacaoError::entrada_host_invalid(
6174            host,
6175            "must not contain `:` (the port belongs in the `:entrada :port` \
6176             slot — a separate `u16` axis on the same `:entrada` block, \
6177             defaulting to 8080 — not in the host body; drop the `:<port>` \
6178             suffix and author the bare hostname. If you intended an IPv6 \
6179             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
6180             Hostname forbids IP literals identically to the IPv4-literal \
6181             arm — use a DNS name)",
6182        ));
6183    }
6184    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
6185    // predicate — the same single source of truth every peer
6186    // ASCII-whitespace scan in caixa-core flows through: the four
6187    // typed-magnitude codec sites (`limits::parse_byte_size` backing
6188    // `:limits :memory`, `limits::parse_duration` backing `:limits
6189    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
6190    // `aplicacao::rate_limit_codec::parse` backing `:politicas
6191    // :rate-limit`) and the shared duration codec
6192    // (`supervisor::duration_codec::parse`) backing `:supervisor
6193    // :restart-window` / `:politicas :timeout` / `:politicas
6194    // :circuit-breaker :window`. This landing closes the last string-typed
6195    // slot in caixa-core still calling `.bytes().any(|b|
6196    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
6197    // across every typed slot now shares one predicate, so a future
6198    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
6199    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
6200    // deliberately excluded from the peer non-ASCII predicate) can
6201    // extend at this shared site in one edit rather than seven
6202    // independent scans diverging over time. Naming the offending byte
6203    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
6204    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
6205    // the offending byte verbatim" discipline every peer codec site
6206    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
6207    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
6208    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
6209        return Err(AplicacaoError::entrada_host_invalid(
6210            host,
6211            format!(
6212                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
6213                 Hostname is a single-token DNS name — leading, trailing, \
6214                 or embedded whitespace breaks the K8s apiserver's Hostname \
6215                 regex at admission time; the paste-from-aligned-doc / \
6216                 paste-from-shell-history / paste-from-CSV footgun silently \
6217                 lands a multi-token blob in `:entrada :host`. Strip every \
6218                 whitespace byte and author the bare hostname — space \
6219                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
6220                 refuse identically)"
6221            ),
6222        ));
6223    }
6224    // Peer of the ASCII-whitespace scan above: route the non-ASCII
6225    // subset of Unicode `White_Space` through the shared
6226    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
6227    // single source of truth every peer non-ASCII-whitespace scan in
6228    // caixa-core flows through: `limits::parse_byte_size` (`:limits
6229    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
6230    // `limits::parse_millicores` (`:limits :cpu`),
6231    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
6232    // and `supervisor::duration_codec::parse` (`:supervisor
6233    // :restart-window` / `:politicas :timeout` / `:politicas
6234    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
6235    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
6236    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
6237    // paste-from-web-doc), or an EM-SPACE-split host
6238    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
6239    // survived this predicate's ASCII byte-scan (none of the UTF-8
6240    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
6241    // `u8::is_ascii_whitespace`), then landed on the per-label
6242    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
6243    // predicate with the generic `label "…" must start and end with an
6244    // alphanumeric` diagnostic — a "far from source at build-time"
6245    // leak that names the label-shape violation but not the
6246    // paste-from-typography origin the author actually needs to fix.
6247    // Peer with the four codec sites the 1b75b38 landing pinned: the
6248    // typed slot's diagnostic axis names the offending codepoint
6249    // (`U+XXXX`) verbatim rather than laundering the value through a
6250    // downstream label-shape arm, so the author can grep their
6251    // caixa.lisp for the invisible codepoint at the surfaced position
6252    // rather than eyeball a multi-byte host for embedded NBSP / LINE
6253    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
6254    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
6255    // drift between any two typed-slot sites' non-ASCII-whitespace
6256    // rejection set becomes a single-edit fix at the shared predicate
6257    // rather than N independent inline scans diverging over time, and
6258    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
6259    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
6260    // `char::is_whitespace`" class the peer non-ASCII predicate's
6261    // doc-comment names as the follow-up trajectory) extends at the
6262    // shared predicate in one edit rather than seven.
6263    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
6264        return Err(AplicacaoError::entrada_host_invalid(
6265            host,
6266            format!(
6267                "contains non-ASCII Unicode whitespace character {ch:?} \
6268                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
6269                 single-token DNS name limited to `[a-z0-9-]` labels; \
6270                 the paste-from-typography footgun silently lands an \
6271                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
6272                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
6273                 `U+3000`, and every other member of the Unicode \
6274                 `White_Space` property outside the ASCII byte range) \
6275                 in `:entrada :host`, which the K8s apiserver's \
6276                 Hostname regex refuses at admission time far from the \
6277                 caixa.lisp source line. Strip every non-ASCII \
6278                 whitespace character and author the bare hostname \
6279                 with only ASCII bytes (write \"checkout.quero.cloud\" \
6280                 verbatim)",
6281                codepoint = ch as u32,
6282            ),
6283        ));
6284    }
6285
6286    // Strip the optional single leading wildcard label *before* the
6287    // trailing-dot check so the bare `"*."` form surfaces the more
6288    // self-locating "wildcard without domain" diagnostic instead of
6289    // the generic "trailing dot" one.
6290    let (had_wildcard, rest) = match host.strip_prefix("*.") {
6291        Some(r) => (true, r),
6292        None => (false, host),
6293    };
6294    if had_wildcard && rest.is_empty() {
6295        return Err(AplicacaoError::entrada_host_invalid(
6296            host,
6297            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
6298        ));
6299    }
6300    if rest.contains('*') {
6301        return Err(AplicacaoError::entrada_host_invalid(
6302            host,
6303            "wildcard `*` is allowed only as the first label (`*.example.com`); \
6304             no inner or trailing `*` labels",
6305        ));
6306    }
6307    if rest.ends_with('.') {
6308        return Err(AplicacaoError::entrada_host_invalid(
6309            host,
6310            "must not have a trailing `.` (Gateway API hostnames are not \
6311             fully-qualified with a root dot; the apiserver regex rejects \
6312             trailing dots)",
6313        ));
6314    }
6315
6316    // Reject pure IPv4 literals: four dot-separated labels, every
6317    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
6318    // literals as Hostnames.
6319    let labels: Vec<&str> = rest.split('.').collect();
6320    if labels.len() == 4
6321        && labels
6322            .iter()
6323            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
6324    {
6325        return Err(AplicacaoError::entrada_host_invalid(
6326            host,
6327            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
6328             literals; use a DNS name)",
6329        ));
6330    }
6331
6332    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
6333    // hyphen, with non-hyphen at both boundaries.
6334    for label in &labels {
6335        if label.is_empty() {
6336            return Err(AplicacaoError::entrada_host_invalid(
6337                host,
6338                "has an empty label (consecutive `..` or a leading `.`)",
6339            ));
6340        }
6341        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
6342            return Err(AplicacaoError::entrada_host_invalid(
6343                host,
6344                format!(
6345                    "label {label:?} exceeds DNS-1123 label max length of \
6346                     {cap} bytes (got {} bytes)",
6347                    label.len(),
6348                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
6349                ),
6350            ));
6351        }
6352        let bytes = label.as_bytes();
6353        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
6354            return Err(AplicacaoError::entrada_host_invalid(
6355                host,
6356                format!(
6357                    "label {label:?} must start and end with an alphanumeric \
6358                     (no leading or trailing `-`)"
6359                ),
6360            ));
6361        }
6362        for &b in bytes {
6363            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
6364            if !valid {
6365                let msg = if b.is_ascii_uppercase() {
6366                    format!(
6367                        "label {label:?} contains uppercase character {ch:?} \
6368                         (Gateway API hostnames are lowercase-only; use {lower:?})",
6369                        ch = b as char,
6370                        lower = label.to_ascii_lowercase()
6371                    )
6372                } else if b == b'_' {
6373                    format!(
6374                        "label {label:?} contains `_` (Gateway API hostnames \
6375                         allow only `[a-z0-9-]`; use `-` instead)"
6376                    )
6377                } else {
6378                    format!(
6379                        "label {label:?} contains invalid character {ch:?} \
6380                         (Gateway API hostnames allow only `[a-z0-9-]`)",
6381                        ch = b as char
6382                    )
6383                };
6384                return Err(AplicacaoError::entrada_host_invalid(host, msg));
6385            }
6386        }
6387    }
6388    Ok(())
6389}
6390
6391/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
6392/// would refuse at admission time. Thin wrapper around
6393/// [`crate::render::is_gateway_api_http_path`] that maps the shared
6394/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
6395/// variant, preserving the more self-locating
6396/// [`AplicacaoError::EntradaPathEmpty`] /
6397/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
6398/// path fails those narrower invariants first.
6399///
6400/// The contract is the canonical HTTP-path grammar — `1..=
6401/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
6402/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
6403/// whitespace/control/non-ASCII bytes — shared with the
6404/// `:contratos :endpoint` axis through the lifted predicate so drift
6405/// between either landing site and the K8s apiserver-side
6406/// HTTPPathMatch.value OpenAPI schema is a build error visible at
6407/// the predicate, not a per-renderer "this passed validate but failed
6408/// admission" surprise. The diagnostic carries the offending `path:`
6409/// verbatim plus a parser-shaped `reason:` naming the specific
6410/// violation, so the author can grep their caixa.lisp for `:paths`
6411/// and fix it in one edit. Same diagnostic shape as
6412/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
6413/// axis.
6414fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
6415    // Empty and missing-leading-`/` are already gated at the call
6416    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
6417    // checking here keeps the per-axis narrower diagnostics in force
6418    // when the predicate is reached directly (and `is_gateway_api_http_path`
6419    // itself defends against `bytes[0]`-style indexing on empty
6420    // input).
6421    if path.is_empty() {
6422        return Err(AplicacaoError::EntradaPathEmpty);
6423    }
6424    if !path.starts_with('/') {
6425        return Err(AplicacaoError::entrada_path_not_absolute(path));
6426    }
6427    crate::render::is_gateway_api_http_path(path)
6428        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
6429}
6430
6431mod rate_limit_codec {
6432    // `Duration` is no longer named here — the codec routes through
6433    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
6434    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
6435    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
6436    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
6437    // closed-set enum's arm-table rather than through vestigial free-helper
6438    // delegates.
6439    use super::{RateLimit, RateLimitUnit};
6440    use serde::{Deserializer, Serializer};
6441
6442    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
6443        // Route through the canonical [`crate::render::serialize_option_via_str`]
6444        // — the substrate-side single-owner primitive for the forward
6445        // arm of the typed-magnitude codec family. See its docstring
6446        // for the full sibling roster.
6447        crate::render::serialize_option_via_str(v, s, render)
6448    }
6449
6450    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
6451        // Route through the canonical [`crate::render::deserialize_option_via_str`]
6452        // — the substrate-side single-owner primitive for the reverse
6453        // arm of the typed-magnitude codec family. See its docstring
6454        // for the full sibling roster.
6455        crate::render::deserialize_option_via_str(d, parse)
6456    }
6457
6458    fn parse(s: &str) -> Result<RateLimit, String> {
6459        // Paired whitespace-rejection arm — same canonical-form
6460        // render-determinism discipline as the peer
6461        // `limits::parse_byte_size` / `limits::parse_duration` /
6462        // `limits::parse_millicores` /
6463        // `supervisor::duration_codec::parse` sites: the ASCII
6464        // byte-scan closes the WhatWG-conformant whitespace bytes
6465        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
6466        // `char::is_whitespace` scan closes the strictly-complementary
6467        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
6468        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
6469        // codepoints) that `str::trim` at parse entry silently strips.
6470        // Either drift class would round-trip through `render` to a
6471        // *different* canonical form on next emit — breaking the
6472        // THEORY.md Part V render-determinism contract on
6473        // `:politicas :rate-limit`.
6474        //
6475        // Routed through the lifted [`crate::render::reject_whitespace`]
6476        // primitive — the substrate-side single-owner paired-arm gate
6477        // every typed-magnitude codec in caixa-core shares.
6478        crate::render::reject_whitespace::<String, _, _>(
6479            s,
6480            |b| {
6481                format!(
6482                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
6483                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
6484                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
6485                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
6486                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
6487                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
6488                 on first serialize — breaking the THEORY.md Part V render-determinism \
6489                 contract every typed slot carries. Strip every whitespace byte (write \
6490                 `\"100/s\"` verbatim)"
6491                )
6492            },
6493            |ch| {
6494                format!(
6495                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
6496                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
6497                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
6498                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
6499                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
6500                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
6501                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
6502                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
6503                 silently strips it at parse entry, and the value round-trips through \
6504                 `render` to a *different* canonical form (`\"100/s\"`) on first \
6505                 serialize — breaking the THEORY.md Part V render-determinism contract \
6506                 every typed slot carries. Strip every non-ASCII whitespace character \
6507                 (write `\"100/s\"` verbatim with only ASCII bytes)",
6508                    cp = ch as u32
6509                )
6510            },
6511        )?;
6512        let s = s.trim();
6513        let (rate_str, unit) = s
6514            .split_once('/')
6515            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
6516        let rate_trim = rate_str.trim();
6517        // The canonical authoring form for `:politicas :rate-limit` is
6518        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
6519        // non-negative integer with no decimal point and no leading
6520        // sign, so the parser's accepted set must match for
6521        // serialize/deserialize to round-trip without canonical-form
6522        // drift. Until this gate landed the parser accepted any
6523        // `u32::from_str`-shaped magnitude — and current Rust
6524        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
6525        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
6526        // serde silently round-tripped to `"100/s"` on the next emit
6527        // (a *different* canonical string) — breaking the THEORY.md
6528        // Part V render-determinism contract on the fifth typed-codec
6529        // surface in caixa-core (peer with the four duration codecs the
6530        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
6531        // already covered: `supervisor::duration_codec` backing three
6532        // typed-duration slots, `limits::parse_duration` backing
6533        // `:limits :wall-clock`, `limits::parse_byte_size` backing
6534        // `:limits :memory`). The fractional / decimal-shaped sibling
6535        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
6536        // existing rejection arm, but the diagnostic is value-laundered
6537        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
6538        // doesn't name the canonical-form remediation or the round-trip
6539        // drift the next emit would produce); this gate lifts the
6540        // fractional arm onto the same canonical-form diagnostic the
6541        // peer codecs carry.
6542        //
6543        // Strict canonical form: every byte of the magnitude is an
6544        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
6545        // inputs the gate distinguishes "non-canonical-but-numeric"
6546        // (parses as f64 or i64 — surfaced with a self-locating
6547        // diagnostic naming the canonical authoring form and the
6548        // round-trip drift the rejected shape would produce on first
6549        // serialize) from "garbage" (parses as neither — surfaced with
6550        // the existing narrower `"not a u32"` wording so its
6551        // diagnostic shape remains stable for the parser-shape footgun
6552        // case).
6553        //
6554        // Routed through the lifted
6555        // [`crate::render::is_digit_only_magnitude`] predicate — the
6556        // same source of truth the four peer typed-magnitude codec
6557        // sites share.
6558        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
6559        if !digit_only {
6560            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
6561            if numeric {
6562                return Err(format!(
6563                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
6564                     canonical authoring form for `:politicas :rate-limit` is \
6565                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
6566                     with no decimal point and no leading `+` / `-` sign. A fractional / \
6567                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
6568                     through `render` to a *different* canonical form (`\"1/s\"`, \
6569                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
6570                     THEORY.md Part V render-determinism contract every typed slot \
6571                     carries. Pick an integer rate that fits the desired window \
6572                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
6573                ));
6574            }
6575            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
6576        }
6577        // Leading-zero arm — peer with the prior `"+100/s"` arm above
6578        // (4eeae98's predecessor) on the same canonical-form
6579        // render-determinism axis. The digit-only gate accepts
6580        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
6581        // them losslessly (= 100, 0, 7), but `render` emits the
6582        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
6583        // a *different* canonical string on the next emit, breaking
6584        // the THEORY.md Part V render-determinism contract the same
6585        // way `"+100/s"` did before the leading-`+` arm landed. The
6586        // single-byte magnitude `"0"` itself round-trips losslessly
6587        // through `render` (`render(0)` emits `"0/s"`) — the
6588        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
6589        // what refuses rate-zero authoring, so `"0/s"` stays in the
6590        // accepted set at this codec layer and the diagnostic
6591        // partitioning between canonical-form drift (this arm) and
6592        // semantic-zero (the downstream gate) remains stable.
6593        // Peer with the future leading-zero arms on the three peer
6594        // typed-magnitude codecs the trajectory acknowledges:
6595        // `supervisor::duration_codec`, `limits::parse_duration`,
6596        // `limits::parse_byte_size` — each carries the same
6597        // canonical-form-drift class today; this gate lands the
6598        // discipline on the fourth typed-magnitude codec in
6599        // caixa-core first because the peer `"+100/s"` arm above is
6600        // the closest predecessor on the trajectory.
6601        //
6602        // Routed through the lifted
6603        // [`crate::render::is_leading_zero_padded_magnitude`]
6604        // predicate — the same source of truth the four peer
6605        // typed-magnitude codec sites share.
6606        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
6607            return Err(format!(
6608                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
6609                 canonical authoring form for `:politicas :rate-limit` is \
6610                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
6611                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
6612                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
6613                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
6614                 first serialize — breaking the THEORY.md Part V render-determinism \
6615                 contract every typed slot carries. Strip the leading zeros (write \
6616                 `\"100/s\"` instead of `\"0100/s\"`)"
6617            ));
6618        }
6619        // The digit-only gate guarantees every byte is `[0-9]`, and
6620        // the leading-zero arm above guarantees the magnitude is
6621        // either the single byte `"0"` or starts with `[1-9]`, so
6622        // the only way `u32::from_str` can fail here is overflow
6623        // (the magnitude exceeds `u32::MAX`). Surface that with an
6624        // overflow-shaped wording so the diagnostic names the
6625        // offending magnitude verbatim rather than collapsing onto
6626        // the non-canonical arm. Same shape
6627        // `supervisor::duration_codec` (1c55a2a) carries on the peer
6628        // duration-codec axis.
6629        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
6630            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
6631        })?;
6632        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
6633        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
6634        // arm reads the `&str → Duration` projection through the
6635        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
6636        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
6637        // with [`super::RateLimitUnit::window`]) rather than the vestigial
6638        // module-private `rate_limit_window_from_unit` free helper the
6639        // predecessor 61421a6 left as the last unlifted delegate on this
6640        // axis. One typed dispatch on the substrate primitive instead of
6641        // one runtime call through the free-helper delegate; the sole
6642        // production consumer of the `&str → Duration` axis (this parse
6643        // arm) now reaches for exactly one typed method on the closed-set
6644        // enum, sibling to the codec's render arm's
6645        // [`super::RateLimit::canonical_unit`] dispatch on the paired
6646        // `Duration → RateLimitUnit` axis and to the validate gate's
6647        // [`super::RateLimit::canonical_unit`] shape-probe on the
6648        // canonical-window axis. A future rate-limit-unit addition (a
6649        // `"d"` day suffix once Envoy's `rate_limit_action` grows
6650        // daily-bucket support, a `"ms"` sub-second window once
6651        // high-throughput per-edge policies come into scope per
6652        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
6653        // on the closed-set enum, and the compiler enforces exhaustiveness
6654        // on every consumer's `match self` arms — this parse arm's
6655        // accepted-suffix set, the render arm's emitted-suffix set, the
6656        // validate gate's canonical-window set, and every future
6657        // per-`:contratos`-edge rate-limit-override overlay all pick it up
6658        // by construction.
6659        let unit = unit.trim();
6660        let window = RateLimitUnit::window_from_suffix(unit)
6661            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
6662        Ok(RateLimit { rate, window })
6663    }
6664
6665    fn render(rl: RateLimit) -> String {
6666        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
6667        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
6668        // this render arm reads the `Duration → RateLimitUnit` projection
6669        // through the substrate primitive [`super::RateLimit::canonical_unit`]
6670        // (returns `None` on every non-canonical window — the sub-second /
6671        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
6672        // formats the returned typed enum through its
6673        // [`std::fmt::Display`] impl (which routes through
6674        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
6675        // the substrate primitive instead of one runtime `find_map`
6676        // walk through the free-helper delegate chain
6677        // [`super::rate_limit_window_unit`] (the vestigial free helper's
6678        // sole production consumer was this arm; every other consumer of
6679        // the `Duration → unit` axis — the validate gate below and the
6680        // future M4 per-Aplicacao Envoy config reconciler — now reads
6681        // the same typed method).
6682        //
6683        // A future rate-limit-unit addition (a `"d"` day suffix once
6684        // Envoy's `rate_limit_action` grows daily-bucket support) is
6685        // one variant + one arm per method on the closed-set enum, and
6686        // the compiler enforces exhaustiveness on every consumer's
6687        // `match self` arms — the codec's `parse` accepted-suffix set,
6688        // this render arm's emitted-suffix set, the validate gate's
6689        // canonical-window set, and every future per-`:contratos`-edge
6690        // rate-limit-override overlay all pick it up by construction.
6691        if let Some(unit) = rl.canonical_unit() {
6692            format!("{}/{unit}", rl.rate())
6693        } else {
6694            // Defensive fallback for non-canonical windows. Note:
6695            // [`AplicacaoSpec::validate_politicas`] rejects any
6696            // non-canonical `:rate-limit :window` via
6697            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
6698            // a validated `RateLimit` never reaches this branch. The
6699            // emitted `<n>/<k>s` form is *not* round-trippable through
6700            // [`parse`] (which accepts only the closed-set
6701            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
6702            // explicit count) — the validate gate is what makes the
6703            // round-trip a structural property; this branch exists only
6704            // so a programmatic non-validated serialize doesn't panic.
6705            format!("{}/{}s", rl.rate(), rl.window().as_secs())
6706        }
6707    }
6708}
6709
6710// ── placement strategy ───────────────────────────────────────────────
6711
6712/// How the Aplicacao distributes across clusters. Three options:
6713///
6714/// - `SingleNode` — one cluster runs the app at a time; takeover on
6715///   death (Erlang/OTP distributed-app semantics).
6716/// - `Replicated` — every named cluster runs an instance (active-active).
6717/// - `Sharded` — entities distribute by hash key across clusters
6718///   (Akka cluster sharding).
6719#[derive(
6720    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
6721)]
6722pub enum PlacementStrategy {
6723    SingleNode,
6724    Replicated,
6725    Sharded,
6726}
6727
6728/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
6729/// distribution-strategy default for the `:placement :estrategia` axis —
6730/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
6731/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
6732/// so every substrate-side consumer that resolves "what
6733/// [`PlacementStrategy`] variant does an author-omitted `:placement
6734/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
6735/// primitive [`PlacementStrategy`].
6736///
6737/// The `:placement :estrategia` default axis has three production
6738/// consumers on the substrate side today: the [`Default for
6739/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
6740/// impl's struct-literal `estrategia` field, and the serde-side
6741/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
6742/// author-omitted `:placement :estrategia` scalar through the [`Default
6743/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
6744/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
6745/// impl and implicit `PlacementStrategy::default()` routes at the sibling
6746/// consumers, with no compile-time link back to the paired
6747/// [`crate::manifest::Caixa::aplicacao_view`] fold's
6748/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
6749/// production consumer that resolves an author-omitted `:placement` slot
6750/// (entirely omitted, not just the `:estrategia` scalar within a declared
6751/// `:placement` block) through [`Placement::default`] which then routes
6752/// through this same discriminator. A future coherent rebrand of the
6753/// `:placement :estrategia` default (a widening to `Sharded` once the
6754/// substrate discovers hash-keyed distribution as the more common
6755/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
6756/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
6757/// names, a per-cluster overlay the operator pins through a future
6758/// `:placement-overrides` slot) would have had to migrate a lifted
6759/// discriminator on one path and open-coded discriminators on the peers
6760/// in lockstep or the four consumers would silently drift out of
6761/// pairing. Lifting the resolution rule to a typed `pub const` on the
6762/// substrate primitive means the M3-mesh-canonical `:placement
6763/// :estrategia` default migrates as one unit on any future axis change.
6764///
6765/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
6766/// §II.2's active-active-across-every-named-cluster arm — the closest
6767/// canonical M3 production reference the substrate carries, matching the
6768/// caixa-mesh default axis every M3 renderer already keys off (a
6769/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
6770/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
6771/// under the substrate's fleet-programs aggregator without an explicit
6772/// `:placement :estrategia` override). The two alternatives the closed
6773/// [`PlacementStrategy::ALL`] accept-set carries
6774/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
6775/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
6776/// Akka-style hash-keyed distribution across clusters,
6777/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
6778/// postures an author declares explicitly, never a posture an omitted
6779/// slot should silently assume.
6780///
6781/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
6782/// exactly one source of truth on the `:placement :estrategia` axis, on
6783/// the same substrate-primitive lift discipline the sibling M2
6784/// per-supervisor default set carries
6785/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
6786/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
6787/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
6788/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
6789/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
6790/// ([`crate::render::DEFAULT_NAMESPACE`],
6791/// [`crate::render::DEFAULT_LIBRARY_NAME`],
6792/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
6793/// the M3 mesh-primitive-defining slot family to converge onto the
6794/// substrate-primitive-lift discipline the M2 supervisor-slot family
6795/// already carries end-to-end.
6796pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
6797
6798impl Default for PlacementStrategy {
6799    fn default() -> Self {
6800        // Route the [`Default for PlacementStrategy`] impl through the
6801        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
6802        // `pub const` rather than a raw `Self::Replicated` arm — one
6803        // source of truth for the M3-mesh-canonical active-active-
6804        // across-every-named-cluster `:placement :estrategia` default
6805        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
6806        // lift discipline the sibling M2 per-supervisor default set
6807        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
6808        // paired halves) carries end-to-end. Pinned by
6809        // `placement_strategy_default_routes_through_lifted_default`.
6810        PLACEMENT_ESTRATEGIA_DEFAULT
6811    }
6812}
6813
6814impl PlacementStrategy {
6815    /// Exhaustive iteration surface for every consumer that reads the
6816    /// full closed-set (the future M4 admission-webhook's accepted-
6817    /// strategy listing in its rejection body, a future `feira app
6818    /// placement --list` CLI-side surfacing of the accepted arm-set,
6819    /// any future round-trip fuzz harness). A future variant addition
6820    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
6821    /// names as a trajectory item) extends this slice as a single edit
6822    /// and every consumer picks up the new entry by construction — the
6823    /// compiler-checked exhaustiveness on the sibling method `match`
6824    /// arms is the build-time guarantee that no arm forgets to grow.
6825    /// Same shape as the sibling closed-set typed enums'
6826    /// [`RateLimitUnit::ALL`] (6bce03d) and
6827    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6828    /// surfaces — the third closed-set typed enum on the caixa surface
6829    /// to converge onto the same discipline.
6830    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
6831
6832    /// Canonical camelCase-schema discriminator scalar this variant
6833    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
6834    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
6835    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6836    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
6837    /// every substrate consumer that dispatches on the strategy (the
6838    /// `lareira-fleet-programs` aggregator, the future `app-operator`
6839    /// reconciler, the M3 Adaptive compression pass) reads the same
6840    /// byte-string the `Serialize` derive emits — the pin test in
6841    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
6842    /// asserts the two paths agree.
6843    #[must_use]
6844    pub const fn as_str(self) -> &'static str {
6845        match self {
6846            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
6847            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
6848            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
6849        }
6850    }
6851
6852    /// Substrate-canonical reverse projection on the `:placement
6853    /// :estrategia` closed-set axis — parses the camelCase-schema
6854    /// discriminator scalar back to the typed variant, or `None` when
6855    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
6856    /// emits. Dispatches on the same lifted
6857    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6858    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6859    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
6860    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
6861    /// the round-trip migrate through one caixa-core edit on any future
6862    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
6863    /// §II.5 hint names as a trajectory item lands one variant + one
6864    /// arm per method and the compiler enforces exhaustiveness on every
6865    /// consumer's `match self` arms).
6866    ///
6867    /// Prior to this lift the substrate carried only the forward
6868    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
6869    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
6870    /// derive that emits the same byte-string under
6871    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
6872    /// consumer that wanted to parse a wire-form strategy scalar had to
6873    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
6874    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
6875    /// compile-time link back to the typed variant's canonical lifted
6876    /// constant. A future variant rename or a per-arm serde-attribute
6877    /// drift would silently split the wire byte-string one non-serde
6878    /// consumer parsed from the one the emitter wrote, with the
6879    /// failure surfacing at parse time far from the rebrand commit.
6880    ///
6881    /// Same closed-set-reverse-projection discipline the sibling
6882    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
6883    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
6884    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
6885    /// defining `:placement :estrategia` closed-set axis, the third
6886    /// substrate-side closed-set typed enum to converge on the two-way
6887    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
6888    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
6889    /// and side-step the [`std::str::FromStr`]-collision clippy
6890    /// (`clippy::should_implement_trait`) the plain `from_str` name
6891    /// carries; a future explicit [`std::str::FromStr`] impl can layer
6892    /// on top by delegating to this canonical arm-dispatch method.
6893    ///
6894    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
6895    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
6896    /// picks the diagnostic form appropriate for its use site — a
6897    /// future `feira app placement --set` CLI-side arg-parse that wants
6898    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
6899    /// Sharded)"` diagnostic builds one on top by iterating
6900    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
6901    /// path folds `None` onto its per-CR structured refusal body.
6902    #[must_use]
6903    pub fn from_wire(s: &str) -> Option<Self> {
6904        match s {
6905            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
6906            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
6907            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
6908            _ => None,
6909        }
6910    }
6911
6912    /// Substrate-canonical per-arm predicate naming the cross-slot
6913    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
6914    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
6915    /// consumes the paired [`Placement::shard_key`] axis (and therefore
6916    /// requires — and is the only strategy that permits — a non-empty
6917    /// `:shard-key` on the paired slot). Today the accept-set is the
6918    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
6919    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
6920    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
6921    /// distributed-app takeover — §II.1) and `Replicated` (active-active
6922    /// across every named cluster) have no hash-keyed routing axis to
6923    /// consume the slot and refuse a declared-but-inert `:shard-key`
6924    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
6925    ///
6926    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
6927    /// satisfies `placement.shard_key().is_some() ==
6928    /// placement.estrategia().requires_shard_key()` by construction — the
6929    /// cross-slot partition the pin
6930    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
6931    /// locks load-bearing, so every downstream consumer that reaches for
6932    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6933    /// CR materializer's per-CR shard-key resolver, the future
6934    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
6935    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
6936    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
6937    /// shard-key requirement probe, a future author-facing tatara-lisp
6938    /// linter that flags `(:placement (:estrategia Replicated :shard-key
6939    /// "tenantId"))` shapes before `feira lint` reaches
6940    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
6941    /// the substrate primitive — the predicate names *the cross-slot
6942    /// invariant*, not the arm identity.
6943    ///
6944    /// Prior to this lift the "does this strategy consume `:shard-key`"
6945    /// classification lived under the `gen_platform::IsVariant`-derived
6946    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
6947    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
6948    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
6949    /// } else { None }` cascade, the
6950    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
6951    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
6952    /// "tenantId".to_string())` cascade, and the
6953    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
6954    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
6955    /// cascade). Each site conflated two semantically distinct questions:
6956    /// "is the variant `Sharded`?" (arm-identity, what
6957    /// [`Self::is_sharded`] answers) and "does the variant consume
6958    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
6959    /// The two questions land on the same three-way answer under today's
6960    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
6961    /// future arm addition that consumed `:shard-key` under a different
6962    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
6963    /// §II.5 roadmap-hint names that hash-partitions across the cluster
6964    /// pool by client-IP hash rather than an author-declared extractor
6965    /// expression, a hypothetical `WeightedShard` variant that carries a
6966    /// shard-key + per-cluster weight table under a promoted M5
6967    /// adaptive-placement engine) or an addition that did *not* consume
6968    /// `:shard-key` on a semantically Sharded-shaped arm would silently
6969    /// split the two questions. Any consumer that read
6970    /// `.is_sharded().then(…)` for the shard-key requirement gate would
6971    /// silently misclassify the new arm as non-consuming — a fixture
6972    /// builder would omit `:shard-key` where the new arm required one and
6973    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
6974    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
6975    /// commit, a future M4 CR materializer would fall through the
6976    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
6977    /// silently emit an empty extractor at the Akka reconciler layer.
6978    ///
6979    /// Lifting the classification as a substrate-primitive method on the
6980    /// closed-set typed enum names the cross-slot invariant on the
6981    /// primitive that owns the partition: every future arm addition
6982    /// declares its `:shard-key` consumption in one place (this predicate's
6983    /// `match self` arm-set), and every downstream consumer that reaches
6984    /// for the paired shape reads through one typed dispatch. Same
6985    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
6986    /// per-arm predicate on the pre-projection WIT-shape axis and the
6987    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
6988    /// paired predicate on the post-projection typed-view axis — a
6989    /// per-arm semantic-classification predicate paired with the
6990    /// arm-identity predicate the derive already emits, closing the drift
6991    /// footgun on the cross-slot invariant axis.
6992    ///
6993    /// Method-named `requires_shard_key` (not `has_shard_key`, not
6994    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
6995    /// invariant reads as "this strategy *requires* the paired
6996    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
6997    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
6998    /// merely omit it. The `has_*` framing would read as an accessor
6999    /// (returning the presence of an already-carried value) rather than a
7000    /// requirement (naming the invariant the paired slot must satisfy).
7001    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
7002    /// shape as the sibling [`WitContract::is_capability`] /
7003    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
7004    /// arm-family, so every consumer reaches for `.requires_shard_key()`
7005    /// as a drop-in replacement for the `.is_sharded()` conflated read
7006    /// without a return-shape migration.
7007    #[must_use]
7008    pub const fn requires_shard_key(self) -> bool {
7009        match self {
7010            Self::Sharded => true,
7011            Self::SingleNode | Self::Replicated => false,
7012        }
7013    }
7014}
7015
7016// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
7017// cross-slot-invariant per-arm predicate: the module-scope const-eval
7018// assertions below trip at caixa-core build time (not test time) if a
7019// future edit rewires the predicate's arm-set away from the singleton
7020// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
7021// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
7022// runtime pin covers the same truth-table with a more descriptive
7023// diagnostic on failure; these const-eval items add a build-time failure
7024// surface strictly stronger than the runtime pin (a downstream renderer's
7025// `const`-context reader that composed against a rebound predicate would
7026// still surface here before the test suite even ran) and side-step the
7027// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
7028// would otherwise accumulate on the caixa-core module baseline.
7029const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
7030const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
7031const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
7032
7033/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
7034/// the pretty-printed byte-string every consumer that formats the strategy
7035/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
7036/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
7037/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
7038/// per-Aplicacao strategy line, the future M4 CR materializer's per-
7039/// admission-webhook rejection body) reaches for the same lifted
7040/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7041/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7042/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
7043/// `Serialize` derive already emits under
7044/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
7045/// [`PlacementStrategy::as_str`] helper already returns.
7046///
7047/// Until this lift landed the sibling OTP-shape typed enums —
7048/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
7049/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
7050/// so [`std::fmt::Display`] routes through the same discriminant string
7051/// the wire format emits) — carried a stable [`std::fmt::Display`]
7052/// surface but [`PlacementStrategy`] did not; every consumer reaching
7053/// for a strategy byte-string past the wire format had to pick between
7054/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
7055/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
7056/// derive), any two of which a future variant rename or
7057/// `#[serde(rename_all = "kebab-case")]` attribute would silently
7058/// desynchronize — with the failure surfacing as a downstream renderer /
7059/// operator's per-strategy dispatch reading one spelling while the wire
7060/// format emitted another, far from the source rebrand commit and with
7061/// no field naming the drift. Routing `Display` through
7062/// [`PlacementStrategy::as_str`] makes the three paths
7063/// (`Debug` for structural inspection, `Display` for user-facing text,
7064/// `Serialize` for the wire format) converge on the same lifted
7065/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
7066/// the diagnostic byte-string, and the pretty-printed byte-string move
7067/// as a single unit through one canonical declaration each, by
7068/// construction. Same trajectory as [`PlacementStrategy::as_str`]
7069/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
7070/// closes the third path.
7071///
7072/// Pin tests
7073/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
7074/// and
7075/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
7076/// assert the three paths agree byte-for-byte on every variant, so a
7077/// future variant rename or per-arm serde attribute drift is a build
7078/// error visible at caixa-core test time, not a silent per-consumer
7079/// dispatch miss at apply / reconcile time.
7080impl std::fmt::Display for PlacementStrategy {
7081    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7082        f.write_str(self.as_str())
7083    }
7084}
7085
7086/// Substrate-canonical [`AsRef<str>`] projection on the M3
7087/// per-Aplicacao distribution-strategy [`PlacementStrategy`] closed-set
7088/// typed enum — routes through the same [`PlacementStrategy::as_str`]
7089/// `pub const fn` scalar accessor the paired [`std::fmt::Display`] impl
7090/// and the un-`rename`d [`serde::Serialize`] derive already key off, so
7091/// any future consumer that binds a [`PlacementStrategy`] through the
7092/// standard-library `impl AsRef<str>` bound (a future `feira app
7093/// placement --set <arm>` verb that composes the emitted
7094/// `PascalCase`/camelCase wire scalar into a
7095/// [`std::process::Command::arg`] shell-out of the future
7096/// `lareira-fleet-programs` aggregator's per-Aplicacao gate, a
7097/// per-Aplicacao structured-log recorder on the future `app-operator`'s
7098/// hierarchical reconciliation surface that accepts `impl AsRef<str>`
7099/// at the `tracing::field::Value` `Str`-arm, a
7100/// [`std::collections::HashMap`] lookup keyed on the strategy wire byte
7101/// through `map.get::<str>(strategy.as_ref())` on a future
7102/// per-strategy dispatch table the M5 adaptive-placement engine
7103/// composes) reaches the paired
7104/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7105/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7106/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted-const
7107/// through one substrate-primitive dispatch rather than an open-coded
7108/// `.as_str()` projection at every wire-up.
7109///
7110/// Peer of the sibling [`std::fmt::Display`] impl on the same
7111/// primitive — both delegate to the shared
7112/// [`PlacementStrategy::as_str`] `pub const fn` accessor, so
7113/// [`format!("{v}")`], `v.as_str()`, and `<PlacementStrategy as
7114/// AsRef<str>>::as_ref(&v)` resolve to the same byte-string per
7115/// instance by construction. A future variant rename or `#[serde(rename_all
7116/// = "kebab-case")]` attribute-drift on the enum reaches every one of
7117/// the three paths (plus the wire-format `Serialize` derive that
7118/// already routes through the same lifted const) through exactly one
7119/// caixa-core edit.
7120///
7121/// Same "route the trait impl through the substrate-primitive
7122/// accessor" discipline the sibling [`crate::CaixaVersion`]
7123/// [`AsRef<str>`] impl (16d5c7e), the paired M2
7124/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
7125/// (63eb1a4), and the paired M2 [`crate::supervisor::RestartPolicy`]
7126/// [`AsRef<str>`] impl (419ea81) carry — closes the M2/M3
7127/// closed-set-typed-enum family's standard-library [`AsRef<str>`]
7128/// projection axis onto the last remaining M3 mesh-primitive-defining
7129/// slot, so every OTP/mesh-shape closed-set typed enum on the caixa
7130/// surface now carries the paired [`AsRef<str>`] + [`fmt::Display`] +
7131/// `as_str` triple through one lifted `M3_PLACEMENT_ESTRATEGIA_*` /
7132/// `SUPERVISOR_*` const. Rust-side newtype/typed-enum convention pairs
7133/// [`AsRef<str>`] and [`fmt::Display`] on the same primitive so a
7134/// caller who has one has both; before this lift,
7135/// [`PlacementStrategy`] carried [`fmt::Display`] but not the paired
7136/// [`AsRef<str>`] impl the convention names.
7137///
7138/// Pinned load-bearing by
7139/// [`tests::placement_strategy_as_ref_str_routes_through_as_str_accessor`]
7140/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
7141/// three-arm closed set) and
7142/// [`tests::placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`]
7143/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
7144/// resolve to the same lifted `M3_PLACEMENT_ESTRATEGIA_*` const per
7145/// arm) — any future silent detour that routes the impl through a
7146/// divergent projection (a per-arm inline `match self { … }`
7147/// re-inlining that opens a compile-time link to the un-lifted
7148/// arm-literal, a swap onto the kebab-case
7149/// [`gen_platform::Discriminant`] catalog identity that would collide
7150/// the wire axis with the dispatcher-catalog axis) trips at
7151/// caixa-core test time under `assert_eq!` rather than at a downstream
7152/// `impl AsRef<str>`-bound consumer's silent split.
7153impl AsRef<str> for PlacementStrategy {
7154    fn as_ref(&self) -> &str {
7155        self.as_str()
7156    }
7157}
7158
7159/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
7160/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
7161/// through the paired substrate-primitive [`PlacementStrategy::from_wire`]
7162/// `Option<Self>` accessor so every future consumer that binds a
7163/// camelCase-schema `:placement :estrategia` wire byte-string through the
7164/// standard-library `.try_into()` / [`TryFrom`] axis (a future `feira app
7165/// placement --set <SingleNode|Replicated|Sharded>` CLI arg-parse that
7166/// composes into `let estrategia: PlacementStrategy = s.try_into()?`, a
7167/// future `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that
7168/// folds a `spec.placement.estrategia: String` field through
7169/// `PlacementStrategy::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-
7170/// bound loader over any of the substrate's closed-set typed enums)
7171/// reaches the same three-arm accept-set the sibling
7172/// [`PlacementStrategy::from_wire`] resolver parses through and the
7173/// sibling [`PlacementStrategy::as_str`] emits, rather than an open-coded
7174/// per-arm `match s { "SingleNode" => …, "Replicated" => …, "Sharded" =>
7175/// …, _ => … }` cascade whose arm-set has no compile-time link back to
7176/// the substrate primitive.
7177///
7178/// Complements the pre-existing forward-projection triple
7179/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
7180/// with the paired trait-idiomatic reverse-projection axis: Rust-side
7181/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
7182/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
7183/// caller who can project *out to* a `&str` can also project *in from*
7184/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
7185/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
7186/// lint the sibling method-named [`PlacementStrategy::from_wire`] would
7187/// trigger under a `FromStr` impl (the same design tradeoff the peer
7188/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
7189/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks note)
7190/// — this impl closes the trait-idiomatic reverse axis without
7191/// disturbing the method-named `from_wire` shape every sibling closed-set
7192/// typed enum on the substrate already carries.
7193///
7194/// `type Error = ()` matches the sibling [`PlacementStrategy::from_wire`]'s
7195/// `Option<Self>` return-shape's deliberate deferral of error typing:
7196/// the caller picks the diagnostic form appropriate for its use site (a
7197/// future `feira app placement --set` arg-parse composes its own per-verb
7198/// "unknown strategy: <arg> — accepted: {…}" message enumerating
7199/// [`PlacementStrategy::ALL`], a future M4 admission-webhook rejection
7200/// body wraps the `Err(())` outcome with the accepted-set enumeration for
7201/// operator diagnostics, a `Result::map_err` at the call site lifts the
7202/// unit-error to a per-verb error type).
7203///
7204/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
7205/// set the [`PlacementStrategy::from_wire`] resolver dispatches through,
7206/// so any future arm addition (an `Anycast` mesh-anycast arm the
7207/// MESH-COMPOSITION §II.5 hint names as a trajectory item) grows the
7208/// trait-idiomatic axis by construction — one caixa-core edit on
7209/// [`PlacementStrategy::from_wire`] extends both the method-named reverse
7210/// projection every existing consumer keys off and the trait-idiomatic
7211/// reverse projection this impl exposes, without a coordinated rewrite
7212/// across every future `TryFrom<&str>`-bound consumer's arm-set.
7213///
7214/// Extends the substrate-wide closed-set-enum reverse-projection family
7215/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
7216/// bf33136) onto the first M3-mesh-primitive-defining slot enum on the
7217/// caixa surface — the `:placement :estrategia` closed set the
7218/// caixa-mesh renderer keys off end-to-end.
7219///
7220/// Pinned load-bearing by
7221/// [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7222/// (byte-parity pin against [`PlacementStrategy::from_wire`] across the
7223/// three-arm accept-set) and
7224/// [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7225/// (rejection witness against silent accept-set widening).
7226impl TryFrom<&str> for PlacementStrategy {
7227    type Error = ();
7228
7229    fn try_from(s: &str) -> Result<Self, Self::Error> {
7230        Self::from_wire(s).ok_or(())
7231    }
7232}
7233
7234/// Trait-idiomatic forward projection on the M3-mesh-primitive-defining
7235/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
7236/// through the paired substrate-primitive [`PlacementStrategy::as_str`]
7237/// `pub const fn` accessor via `strategy.as_str()`. Return type is
7238/// `&'static str` by construction — every [`PlacementStrategy::as_str`]
7239/// arm resolves to a paired lifted
7240/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7241/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7242/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] `pub const &str`
7243/// with static lifetime, so the trait's return-type promise is upheld
7244/// structurally without a `String::leak()` cast or a per-arm inline
7245/// literal.
7246///
7247/// Complements the pre-existing forward-projection triple
7248/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
7249/// with the trait-idiomatic forward-projection axis: Rust-side
7250/// newtype/typed-enum convention pairs [`TryFrom<&str>`] with the mirror-
7251/// image [`From<Self> for &'static str`] on the same primitive so a
7252/// caller who can project *in from* a `&str` via the trait axis can also
7253/// project *out to* one under a `'static`-lifetime bound. The
7254/// [`AsRef<str>`] impl already carries the same emit-set on the borrowed
7255/// return path; this impl closes the trait-idiomatic axis pair with the
7256/// stricter `&'static str` lifetime the sibling [`AsRef<str>`] cannot
7257/// promise (its return borrows from `&self`, not from the
7258/// [`PlacementStrategy::as_str`] `pub const fn`'s static-string result).
7259///
7260/// Same "route the trait impl through the substrate-primitive accessor"
7261/// discipline the sibling [`crate::supervisor::RestartStrategy`]
7262/// `From<Self> for &'static str` impl (523157d — first-mover on this
7263/// forward-projection family), [`crate::supervisor::RestartPolicy`]
7264/// `From<Self> for &'static str` impl (9fb37d0 — second peer, closing
7265/// the M2 OTP-shape sibling pair), [`crate::CaixaKind`]
7266/// `From<Self> for &'static str` impl (edb827b — third peer, opening
7267/// the campaign onto the top-level caixa surface), and
7268/// [`crate::CaixaDialeto`] `From<Self> for &'static str` impl (c189a6f
7269/// — fourth peer, extending onto the dialect-classification axis)
7270/// carry — extends the substrate primitive's trait-idiomatic forward-
7271/// projection axis onto the fifth closed-set fieldless typed enum on
7272/// the caixa surface: the M3-mesh-primitive-defining `:placement
7273/// :estrategia` closed-set axis the caixa-mesh renderer keys off end-
7274/// to-end, previously carrying the paired [`std::fmt::Display`] /
7275/// [`AsRef<str>`] / [`PlacementStrategy::as_str`] / [`TryFrom<&str>`] /
7276/// [`PlacementStrategy::from_wire`] forward+reverse projections but not
7277/// yet the trait-idiomatic forward projection with the `&'static str`
7278/// lifetime bound.
7279///
7280/// Same shape as the sibling [`crate::CaixaDialeto`] axis pair:
7281/// [`PlacementStrategy::as_str`] output and
7282/// [`PlacementStrategy::from_wire`] input share the same camelCase-
7283/// schema `PascalCase` vocabulary by construction (the same three
7284/// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
7285/// dispatch on both halves) — the trait-idiomatic axis pair
7286/// ([`From<Self> for &'static str`] + [`TryFrom<&str> for Self`])
7287/// therefore round-trips directly, without an intermediate wire-vocab
7288/// hop the peer [`crate::CaixaKind`] axis pair requires. This lift
7289/// extends the "direct round-trip" precedent
7290/// [`crate::CaixaDialeto`] (c189a6f) established onto the first M3-
7291/// mesh-primitive-defining slot enum.
7292///
7293/// The paired [`PlacementStrategy::as_str`] accessor's three-arm emit-
7294/// set is the single source of truth — every future arm addition (an
7295/// `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint names as
7296/// a trajectory item, a hypothetical `WeightedShard` variant that
7297/// carries a shard-key + per-cluster weight table under a promoted M5
7298/// adaptive-placement engine) grows the trait-idiomatic forward axis
7299/// by construction: one caixa-core edit on
7300/// [`PlacementStrategy::as_str`] extends every one of the sibling
7301/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
7302/// [`PlacementStrategy::as_str`] itself, and this [`From<Self> for
7303/// &'static str`]) without a coordinated rewrite across every future
7304/// `Into<&'static str>`-bound consumer's arm-set. This lift closes the
7305/// fifth peer on the trait-idiomatic forward-projection campaign the
7306/// recently-landed peer commits opened; the remaining nine closed-set
7307/// typed enums on the caixa substrate surface (`WitShape`,
7308/// `RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
7309/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
7310/// `FerriteRuntime`) are the future targets of this campaign.
7311///
7312/// Pinned load-bearing by
7313/// [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
7314/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
7315/// three-arm emit-set, plus a `const`-context materialization witness
7316/// for the `&'static str` lifetime promise routed through the paired
7317/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants, plus
7318/// a paired `.into()` shape assertion covering the blanket-derived
7319/// `Into<&'static str>` shape) and
7320/// [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7321/// (partition pin asserting `<&'static str as
7322/// From<PlacementStrategy>>::from` and [`PlacementStrategy::as_str`]
7323/// agree on every arm, plus a two-way direct round-trip witness through
7324/// the paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
7325/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
7326/// axis pair without the wire-vocab intermediate the peer
7327/// [`crate::CaixaKind`] axis pair requires — the emit-side
7328/// [`PlacementStrategy::as_str`] and the parse-side
7329/// [`PlacementStrategy::from_wire`] dispatch on the same three lifted
7330/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants by
7331/// construction, so round-tripping composes the two trait impls
7332/// directly).
7333impl From<PlacementStrategy> for &'static str {
7334    fn from(strategy: PlacementStrategy) -> &'static str {
7335        strategy.as_str()
7336    }
7337}
7338
7339/// Trait-idiomatic *forward* projection on [`PlacementStrategy`] from a
7340/// *borrowed* input onto the `&'static str` axis — the borrowed-input
7341/// companion to the paired owned-input [`From<PlacementStrategy> for
7342/// &'static str`] impl immediately above. Routes byte-for-byte through
7343/// the same substrate-primitive [`PlacementStrategy::as_str`] `pub const
7344/// fn` accessor so every consumer that binds a `&PlacementStrategy`
7345/// through the standard-library `.into()` / [`From<&Self> for &'static
7346/// str`] axis (a `PlacementStrategy::ALL.iter().map(<&'static
7347/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
7348/// whose iterator over `&'static [PlacementStrategy]` yields
7349/// `&PlacementStrategy`, not `PlacementStrategy`, so the owned-input
7350/// [`From<PlacementStrategy>`] axis alone forces every call site through
7351/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
7352/// rather than the direct trait-idiomatic projection; a future generic
7353/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column over
7354/// the substrate-wide closed-set typed-enum family that walks the
7355/// `iter().map(Into::into)` shape verbatim; the future M4
7356/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook rejection
7357/// body that composes the accepted-`:placement :estrategia` enumeration
7358/// from an iterated `PlacementStrategy::ALL.iter().map(|s| s.into())`
7359/// pipe rather than a per-arm `match s { … }` cascade; a future
7360/// `HashMap::<&'static str, PlacementStrategy>::from_iter(
7361///     PlacementStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7362/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`] impl
7363/// cannot compose without this borrowed-input axis in place) reaches
7364/// the same three-arm lifted
7365/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7366/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7367/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the paired
7368/// owned-input [`From<PlacementStrategy> for &'static str`], the sibling
7369/// [`std::fmt::Display`], [`AsRef<str>`], and [`PlacementStrategy::as_str`]
7370/// surfaces already return.
7371///
7372/// Sixth peer on the substrate-wide trait-idiomatic *borrowed-input*
7373/// forward-projection family opened on [`crate::dep::DepList`]
7374/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
7375/// [`crate::CaixaDialeto`] (807b0b5), the paired M2 OTP-shape
7376/// [`crate::supervisor::RestartStrategy`] (e941836), and
7377/// [`crate::supervisor::RestartPolicy`] (842c7f3). Rust's `From` trait
7378/// does not auto-derive the `From<&Self>` sibling from a `From<Self>`
7379/// impl (the blanket `impl<T, U> From<&T> for U where T: Copy, U:
7380/// From<T>` does not exist in `core`), so every closed-set typed enum
7381/// that carries the owned-input axis but not the borrowed-input axis
7382/// forces every borrowed-input call site through a `.copied()` /
7383/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
7384/// type bounds have no compile-time link to the substrate primitive.
7385/// [`PlacementStrategy`] is the first M3-mesh-primitive-defining
7386/// closed-set typed enum to converge onto this borrowed-input campaign
7387/// — first-mover on the M3 mesh-slot family the caixa-mesh renderer
7388/// keys off end-to-end, ahead of the sibling
7389/// [`crate::aplicacao::WitShape`] `:contratos :wit` census-label axis
7390/// (56998ec) and [`crate::aplicacao::RateLimitUnit`]
7391/// `:politicas :rate-limit` canonical-suffix axis (7fdfbf4) whose owned-
7392/// input forward-projection axes landed earlier in the substrate-wide
7393/// campaign but await the paired borrowed-input closure.
7394///
7395/// Same three-path convergence discipline as the paired owned-input
7396/// impl (this borrowed-input axis, the paired owned-input
7397/// [`From<PlacementStrategy> for &'static str`], and
7398/// [`PlacementStrategy::as_str`] all route through the same lifted
7399/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] const), so a future
7400/// variant rename or per-arm serde-attribute drift reaches every one
7401/// of the six sibling forward-projection paths
7402/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
7403/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
7404/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
7405/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
7406/// edit.
7407///
7408/// The [`PlacementStrategy::as_str`] emit and
7409/// [`PlacementStrategy::from_wire`] parse share the same `PascalCase`
7410/// vocabulary by construction — the same three lifted
7411/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants dispatch on
7412/// both halves — so the borrowed-input forward axis and the reverse
7413/// axis compose directly without the intermediate wire-vocab hop the
7414/// peer [`crate::CaixaKind`] axis pair requires. The round-trip
7415/// witness pin below locks this direct composition on the M3 slot
7416/// enum's trait-idiomatic axis pair.
7417///
7418/// Pinned load-bearing by
7419/// [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
7420/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
7421/// three-arm emit-set via a borrowed input, plus a `const`-context
7422/// materialization witness for the `&'static str` lifetime promise,
7423/// plus a blanket `.into()` shape) and
7424/// [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7425/// (cross-axis partition pin against the paired owned-input
7426/// [`From<PlacementStrategy> for &'static str`] impl, plus a
7427/// `.iter().map(Into::into)` pipe witness over
7428/// [`PlacementStrategy::ALL`], plus a direct round-trip witness through
7429/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
7430/// Self` round-trip on the M3 slot enum's trait-idiomatic axis pair
7431/// without the wire-vocab intermediate the peer [`crate::CaixaKind`]
7432/// axis pair requires).
7433impl From<&PlacementStrategy> for &'static str {
7434    fn from(strategy: &PlacementStrategy) -> &'static str {
7435        strategy.as_str()
7436    }
7437}
7438
7439/// Where the Aplicacao runs.
7440#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7441#[serde(rename_all = "camelCase")]
7442pub struct Placement {
7443    /// Distribution strategy.
7444    #[serde(default)]
7445    pub estrategia: PlacementStrategy,
7446
7447    /// Named clusters that host this Aplicacao. Required for
7448    /// `Replicated` and `SingleNode`; for `Sharded` declares the
7449    /// shard pool.
7450    #[serde(default)]
7451    pub clusters: Vec<String>,
7452
7453    /// Optional hint to the placement engine: `"data-locality"`,
7454    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
7455    #[serde(default, skip_serializing_if = "Option::is_none")]
7456    pub affinity: Option<String>,
7457
7458    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
7459    #[serde(default, skip_serializing_if = "Option::is_none")]
7460    pub shard_key: Option<String>,
7461}
7462
7463impl Placement {
7464    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
7465    /// `:shard-key` extractor-expression scalar accessor every consumer
7466    /// of the Aplicacao's hash-keyed distribution routing keys off —
7467    /// returns the author-declared `:placement :shard-key` byte-string
7468    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
7469    /// own `Option<String>` storage; `None` when the slot is absent
7470    /// (the canonical shape under `:estrategia Replicated` /
7471    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
7472    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
7473    /// partition — `validate` refuses any `Placement` past this call
7474    /// that lands `Some` on a non-`Sharded` strategy or `None` on
7475    /// `Sharded`).
7476    ///
7477    /// The `:placement :shard-key` slot carries the Akka-style
7478    /// cluster-sharding entity-id extractor expression
7479    /// (MESH-COMPOSITION §II.4) — validated by
7480    /// [`validate_placement_shard_key`] to be a non-empty printable-
7481    /// ASCII single-token reference (`tenantId`, `$tenantId`,
7482    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
7483    /// future M4 Akka-style cluster-sharding reconciler hashes without
7484    /// re-validating at the runtime layer), and every downstream
7485    /// consumer that reads the key keys off this scalar (the
7486    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
7487    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
7488    /// declared-but-inert refusal diagnostic, the caixa-mesh
7489    /// per-Aplicacao `placement.shardKey` emit path the substrate
7490    /// operator's per-entity hash-routing reader consumes, the future
7491    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7492    /// per-shard-key resolver).
7493    ///
7494    /// Prior to this lift the `.shard_key` field was accessed inline at
7495    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
7496    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
7497    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
7498    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
7499    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
7500    /// — two open-coded field-accesses that expressed no compile-time
7501    /// link back to the typed slot. A future extension of the
7502    /// `:placement :shard-key` axis to a richer author surface — a
7503    /// per-cluster override the operator pins through a future
7504    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
7505    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
7506    /// alias table the M4 CR materializer resolves per-CR, a
7507    /// per-Aplicacao dynamic `:shard-key` derivation the future
7508    /// adaptive placement engine computes from `:affinity` weights —
7509    /// would have had to be threaded through both open-coded copies in
7510    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
7511    /// arm refusal would silently disagree on which extractor
7512    /// expression a given Placement resolves to. Lifting the resolution
7513    /// rule to a typed method on the substrate primitive means every
7514    /// downstream consumer of the Aplicacao's per-`:placement`
7515    /// hash-key surface reaches for exactly one typed dispatch — the
7516    /// resolver's accept-set migrates as a unit on any future axis
7517    /// addition.
7518    ///
7519    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
7520    /// [`WitContract::destination`] / [`WitContract::world_ref`]
7521    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
7522    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
7523    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
7524    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
7525    /// typed dispatch on the substrate primitive, thin projections at
7526    /// each consumer" discipline extended onto the per-`:placement`
7527    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
7528    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
7529    /// — opens the "optional per-slot scalar" projection pattern the
7530    /// sibling per-`:placement` `:affinity`, per-`:politicas`
7531    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
7532    /// match the storage field's name; the accessor's identity name
7533    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
7534    /// slot's docstring already carries.
7535    #[must_use]
7536    pub const fn shard_key(&self) -> Option<&str> {
7537        match &self.shard_key {
7538            Some(s) => Some(s.as_str()),
7539            None => None,
7540        }
7541    }
7542
7543    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
7544    /// compression-hint scalar accessor every weighting-consumer of the
7545    /// Aplicacao's per-hint routing surface keys off — returns the
7546    /// author-declared `:placement :affinity` byte-string verbatim as
7547    /// an `Option<&str>`, borrowed from the typed slot's own
7548    /// `Option<String>` storage; `None` when the slot is absent (the
7549    /// canonical shape of an Aplicacao that leaves the compression
7550    /// weighting up to the placement engine's cluster-default arm — no
7551    /// author-authored `data-locality` / `low-latency` / etc. hint
7552    /// biases the routing).
7553    ///
7554    /// The `:placement :affinity` slot carries the M3 Adaptive-
7555    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
7556    /// by [`validate_placement_affinity`] to be a DNS-1123 label
7557    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
7558    /// K8s-conformant label-selector shape every apiserver-side pod-
7559    /// affinity / node-affinity materializer already gates on
7560    /// admission), and every downstream consumer that reads the hint
7561    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
7562    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
7563    /// `placement.affinity` overlay emit path the substrate operator's
7564    /// per-hint weighting-consumer reads, the future M4
7565    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
7566    /// pod-affinity / node-affinity selector resolver).
7567    ///
7568    /// Prior to this lift the `.affinity` field was accessed inline at
7569    /// the sole caixa-core site — the
7570    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
7571    /// `if let Some(a) = &self.placement.affinity { …
7572    /// validate_placement_affinity(a)? … }` cascade — one open-coded
7573    /// field-access that expressed no compile-time link back to the
7574    /// typed slot. A future extension of the `:placement :affinity`
7575    /// axis to a richer author surface — a per-cluster override the
7576    /// operator pins through a future `:placement :affinity-overrides`
7577    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
7578    /// tenant hint alias table the M4 CR materializer resolves per-CR,
7579    /// a per-Aplicacao dynamic `:affinity` derivation the future
7580    /// adaptive placement engine computes from `:clusters` topology —
7581    /// would have had to be threaded through the open-coded copy in
7582    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
7583    /// materializer reader that landed on the axis, or the per-hint
7584    /// value-shape gate and its downstream weighting consumers would
7585    /// silently disagree on which hint a given Placement resolves to.
7586    /// Lifting the resolution rule to a typed method on the substrate
7587    /// primitive means every downstream consumer of the Aplicacao's
7588    /// per-`:placement` compression-hint surface reaches for exactly
7589    /// one typed dispatch — the resolver's accept-set migrates as a
7590    /// unit on any future axis addition.
7591    ///
7592    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
7593    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
7594    /// optional-scalar axis — same "one typed dispatch on the substrate
7595    /// primitive, thin projections at each consumer" discipline extended
7596    /// onto the per-`:placement` M3-Adaptive-compression-hint
7597    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
7598    /// return accessor on the M3 mesh-slot family; closes the last
7599    /// un-lifted per-`:placement` `Option<String>` axis. Named
7600    /// `affinity()` to match the storage field's name; the accessor's
7601    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
7602    /// vocabulary the slot's docstring already carries.
7603    #[must_use]
7604    pub const fn affinity(&self) -> Option<&str> {
7605        match &self.affinity {
7606            Some(s) => Some(s.as_str()),
7607            None => None,
7608        }
7609    }
7610
7611    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
7612    /// strategy scalar accessor every consumer that dispatches on the
7613    /// Aplicacao's per-cluster distribution shape keys off — returns the
7614    /// author-declared `:placement :estrategia` variant verbatim as a
7615    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
7616    /// `PlacementStrategy` storage.
7617    ///
7618    /// The `:placement :estrategia` slot carries the closed-set
7619    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
7620    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
7621    /// `Replicated` — active-active across every named cluster; `Sharded`
7622    /// — Akka-style hash-keyed entity distribution across the cluster pool
7623    /// per §II.4) that every downstream consumer of the Aplicacao's
7624    /// per-cluster fan-out shape keys off. Validated by
7625    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
7626    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
7627    /// matches!(estrategia, Sharded)` — the cross-slot partition the
7628    /// [`Placement::shard_key`] accessor's docstring pins), and every
7629    /// downstream consumer that reads the strategy keys off this scalar
7630    /// (the [`AplicacaoSpec::validate_placement`]
7631    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
7632    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
7633    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
7634    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
7635    /// declared-but-inert refusal's
7636    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
7637    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
7638    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
7639    /// emit path the substrate operator's per-strategy fan-out reader
7640    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7641    /// materializer's per-strategy admission-webhook resolver).
7642    ///
7643    /// Prior to this lift the `.estrategia` field was accessed inline at
7644    /// four sites — the [`AplicacaoSpec::validate_placement`]
7645    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
7646    /// `estrategia: self.placement.estrategia`, the same method's
7647    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
7648    /// partition dispatch, the non-`Sharded`-arm
7649    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
7650    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
7651    /// per-Aplicacao strategy print line at
7652    /// `println!("… {} …", spec.placement.estrategia, …)`
7653    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
7654    /// expressed no compile-time link back to the typed slot. A future
7655    /// extension of the `:placement :estrategia` axis to a richer author
7656    /// surface (a per-cluster override the operator pins through a future
7657    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
7658    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
7659    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
7660    /// derivation the future adaptive placement engine computes from
7661    /// `:affinity` + `:clusters` topology) would have had to be threaded
7662    /// through every open-coded copy in lockstep — one consumer reading
7663    /// the raw variant while a peer read the operator-resolved variant
7664    /// would silently split the `PlacementWithoutClusters` /
7665    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
7666    /// partition-dispatch input, a two-consumer split at the validator
7667    /// far from the source `caixa.lisp` with no field naming the
7668    /// strategy-drift root cause. Lifting the resolution rule to a typed
7669    /// method on the substrate primitive means every downstream consumer
7670    /// of the Aplicacao's per-`:placement` distribution-strategy surface
7671    /// reaches for exactly one typed dispatch — the resolver's accept-set
7672    /// migrates as a unit on any future axis addition.
7673    ///
7674    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
7675    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
7676    /// same "one typed dispatch on the substrate primitive, thin
7677    /// projections at each consumer" discipline extended onto the
7678    /// per-`:placement` distribution-strategy `Copy`-composite-enum
7679    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
7680    /// family; first `Copy`-return accessor on the M3 mesh-slot
7681    /// `Placement` type — companion to the sibling per-`:placement`
7682    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
7683    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
7684    /// optional-scalar axes, closing the last unlifted per-`:placement`
7685    /// scalar-value axis (the closed-set `PlacementStrategy`
7686    /// distribution-strategy discriminator) so every downstream
7687    /// per-`:placement` reader now routes through a typed dispatch on
7688    /// the substrate primitive. Named `estrategia()` to match the storage
7689    /// field's name; the accessor's identity name maps onto the
7690    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
7691    /// already carries. Declared `pub const fn` (matching the peer M3
7692    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
7693    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
7694    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
7695    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
7696    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
7697    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
7698    /// [`RateLimit`] — every one a `pub const fn`) so every future
7699    /// substrate-side `const`-context consumer of the resolved
7700    /// distribution-strategy variant (a `const _: () = assert!(…)`
7701    /// module-scope invariant pin on a per-fixture typed [`Placement`],
7702    /// a future M4 admission-webhook `const fn` resolver over a typed
7703    /// [`Placement`], any `const fn` composer that fans on the strategy
7704    /// at compile time) reaches through the same typed dispatch on the
7705    /// substrate primitive at const-eval time as at runtime. Pinned by
7706    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
7707    /// const-eval posture at module scope via `const _:() = …` items so
7708    /// any future accidental downgrade to non-`const` trips at caixa-core
7709    /// build time.
7710    #[must_use]
7711    pub const fn estrategia(&self) -> PlacementStrategy {
7712        self.estrategia
7713    }
7714
7715    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
7716    /// per-cluster distribution-target slice accessor every consumer that
7717    /// walks the Aplicacao's declared cluster-pool keys off — returns the
7718    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
7719    /// `&[String]` slice-view, borrowed from the typed slot's own
7720    /// `Vec<String>` storage (a zero-copy slice-view over the same
7721    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
7722    /// through). Non-optional: the empty slice is the load-bearing
7723    /// pre-validation sentinel every downstream consumer of the paired
7724    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
7725    /// off — every strategy in the closed
7726    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
7727    /// requires a non-empty list (`SingleNode` / `Replicated` use the
7728    /// list as hosting / takeover candidates per Erlang/OTP distributed-
7729    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
7730    /// shard pool per Akka cluster-sharding convention, §II.4), so the
7731    /// `.is_empty()` probe is the shared pre-condition every
7732    /// [`AplicacaoSpec::validate_placement`] arm heads on.
7733    ///
7734    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
7735    /// 1123-label per-cluster distribution-target list — the same
7736    /// set-not-multiset shape the sibling `:membros :caixa` /
7737    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
7738    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
7739    /// pins the shape). Every downstream consumer that fans on the list
7740    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
7741    /// pre-flight `.is_empty()` probe that trips
7742    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
7743    /// per-cluster value-shape + duplicate-detection fan-out loop, the
7744    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
7745    /// that materializes the list verbatim onto every
7746    /// programs.yaml entry the substrate operator's per-cluster
7747    /// `placement.clusters | contains .Values.cluster` filter reads,
7748    /// the `feira app graph` per-Aplicacao cluster print line, the
7749    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7750    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
7751    /// placement engine's cluster-topology reader).
7752    ///
7753    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
7754    /// inline at three production sites — the
7755    /// [`AplicacaoSpec::validate_placement`] pre-flight
7756    /// `self.placement.clusters.is_empty()` refusal probe, the same
7757    /// method's per-cluster validate loop's
7758    /// `for c in &self.placement.clusters` traversal head, and the
7759    /// `feira app graph` per-Aplicacao print line's
7760    /// `spec.placement.clusters` `{:?}` formatter argument
7761    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
7762    /// that expressed no compile-time link back to the typed slot. A
7763    /// future extension of the `:placement :clusters` axis to a richer
7764    /// author surface (a per-tenant cluster-pool overlay the operator
7765    /// pins through a future `:placement :clusters-overrides` slot the
7766    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
7767    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
7768    /// the future M5 adaptive-placement engine computes from
7769    /// `:affinity` weights + live cluster-topology probes, a promotion
7770    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
7771    /// partition once the substrate operator's cluster-membership
7772    /// reconciler comes into typed scope) would have had to be threaded
7773    /// through all three open-coded copies in lockstep or one consumer
7774    /// would silently disagree with the peers on which cluster-pool a
7775    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
7776    /// reading the raw slot while the peer per-cluster validate loop
7777    /// read an operator-resolved slot would silently split the paired
7778    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
7779    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
7780    /// input from the pre-flight input, a three-consumer split at the
7781    /// validator and formatter far from the source `caixa.lisp` with
7782    /// no field naming the cluster-pool-drift root cause. Lifting the
7783    /// resolution rule to a typed method on the substrate primitive
7784    /// means every downstream consumer of the Aplicacao's
7785    /// per-`:placement` cluster-pool surface reaches for exactly one
7786    /// typed dispatch — the resolver's accept-set migrates as a unit
7787    /// on any future axis addition.
7788    ///
7789    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
7790    /// slot — sibling to the seed M2
7791    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
7792    /// slice-return accessor on the peer per-`:supervisor` static-
7793    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
7794    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
7795    /// primitive, thin projections at each consumer" discipline. The
7796    /// three peer `Vec`-carry axes still unlifted at the time of this
7797    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
7798    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
7799    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
7800    /// [`crate::UpgradeFromEntry::instructions`]
7801    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7802    /// — inherit this accessor's discipline as future compounding runs
7803    /// migrate their consumers onto the shared slice-return shape.
7804    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
7805    /// type, sibling to the two `Option<&str>`-return
7806    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
7807    /// (74ec2d3) accessors and the `Copy`-return
7808    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
7809    /// unlifted per-`:placement` field axis (the `Vec<String>`
7810    /// distribution-target-list carrier) so every downstream
7811    /// per-`:placement` reader now routes through a typed dispatch on
7812    /// the substrate primitive. Named `clusters()` to match the storage
7813    /// field's name verbatim and the tatara-lisp author-surface term
7814    /// (`:clusters`) the field's own docstring already carries; the
7815    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7816    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
7817    /// for. Returns `&[String]` (not `&Vec<String>`) because every
7818    /// downstream consumer of the cluster list treats it as a read-only
7819    /// sequence — the slice-view is the narrowest borrow that supports
7820    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
7821    /// `.len()`) without leaking the backing `Vec`'s
7822    /// grow/push/reserve surface that no consumer of the typed view
7823    /// reaches for (the storage-side `Vec` remains reachable through
7824    /// the `pub clusters` field for the mutation-carrying serde
7825    /// round-trip and per-test fixture-mutation paths).
7826    #[must_use]
7827    pub const fn clusters(&self) -> &[String] {
7828        self.clusters.as_slice()
7829    }
7830}
7831
7832impl Default for Placement {
7833    fn default() -> Self {
7834        Self {
7835            // Route the struct-literal `estrategia` default arm through
7836            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
7837            // typed `pub const` rather than the transitively-derived
7838            // [`PlacementStrategy::default`] route — one source of truth
7839            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
7840            // active-active-across-every-named-cluster arm
7841            // (MESH-COMPOSITION §II.2) that both this struct-literal
7842            // altitude and the sibling [`Default for PlacementStrategy`]
7843            // impl already key off through the same substrate primitive.
7844            // Pinned by
7845            // `placement_default_estrategia_routes_through_lifted_default`.
7846            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
7847            clusters: Vec::new(),
7848            affinity: None,
7849            shard_key: None,
7850        }
7851    }
7852}
7853
7854// ── external entry point ─────────────────────────────────────────────
7855
7856/// External entry point — what an outside caller sees. Renders to a
7857/// Gateway / Ingress + a route to the named member Servico.
7858#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7859#[serde(rename_all = "camelCase")]
7860pub struct Entrada {
7861    /// Public hostname (e.g. `"checkout.quero.cloud"`).
7862    pub host: String,
7863
7864    /// Member Servico the gateway routes to. Must be in `:membros`.
7865    pub para: String,
7866
7867    /// Optional path filter — if set, only matching paths route to
7868    /// this Aplicacao (the rest fall through to other route rules).
7869    #[serde(default)]
7870    pub paths: Vec<String>,
7871
7872    /// Default port on the destination Servico (the trigger.service.port).
7873    #[serde(default = "default_port")]
7874    pub port: u16,
7875}
7876
7877impl Entrada {
7878    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
7879    /// every HTTPRoute-aware renderer keys off — returns the author-
7880    /// declared `:entrada :paths` list verbatim when non-empty, and the
7881    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
7882    /// all fallback otherwise (so an Aplicacao author who declares an
7883    /// external `:entrada` block but no per-path rule surface still
7884    /// gets a route whose sole `HTTPPathMatch` matches every incoming
7885    /// request under the paired
7886    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
7887    ///
7888    /// Prior to this lift the "if `:entrada :paths` is empty use the
7889    /// substrate catch-all; else return each declared path verbatim"
7890    /// cascade lived inline at
7891    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
7892    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
7893    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
7894    /// substrate ships today, with no typed method on the substrate
7895    /// primitive that named the rule. A future path-resolution axis
7896    /// addition — a per-cluster `:entrada :default-path` override the
7897    /// operator pins through a future `:placement`-scoped slot, an
7898    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7899    /// admission-webhook floor that materializes the catch-all before
7900    /// the CR lands, a future per-`:entrada :paths` overlay from a
7901    /// per-cluster policy the future `feira app deploy` pipeline
7902    /// consumes — would have to be threaded through every renderer's
7903    /// inline copy of the cascade in lockstep or one consumer would
7904    /// silently disagree with the peers on which path list a given
7905    /// `:entrada` block resolves to. Lifting the rule to a typed
7906    /// method on the substrate primitive means every downstream
7907    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
7908    /// per-cluster overlay resolver, every future per-Aplicacao
7909    /// snapshot renderer) reaches for exactly one typed dispatch —
7910    /// the resolver's accept-set moves as a unit on any future axis
7911    /// addition.
7912    ///
7913    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
7914    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
7915    /// per-`:entrada` scalar-value axes — extends the "one typed
7916    /// dispatch on the substrate primitive, thin projections at each
7917    /// consumer" discipline onto the per-`:entrada` path-list
7918    /// resolution axis every HTTPRoute-aware renderer consumes. Same
7919    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
7920    /// sibling `:politicas` primitive — one typed method on the
7921    /// substrate primitive that names the cascade every renderer
7922    /// otherwise re-inlines.
7923    #[must_use]
7924    pub fn resolved_paths(&self) -> Vec<&str> {
7925        // Route the internal cascade-head + per-entry projection reads
7926        // through the lifted [`Self::paths`] slice accessor rather than
7927        // the raw `self.paths` field access — the substrate-primitive
7928        // per-`:entrada` path-list resolver's two internal reads now
7929        // key off the canonical raw-slot surface every downstream
7930        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
7931        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
7932        // entrada summary line's `{:?}` Debug print) routes through, so
7933        // any future rebrand on the typed slot's raw-slot reader lands
7934        // at exactly one place. Same two-consumer coherence discipline
7935        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
7936        // the peer M3 mesh-slot `Vec<String>`-carry axis.
7937        if self.paths().is_empty() {
7938            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
7939        } else {
7940            self.paths().iter().map(String::as_str).collect()
7941        }
7942    }
7943
7944    /// Substrate-canonical per-`:entrada` DNS-hostname singular
7945    /// accessor every Gateway-API `Listener.hostname` reader keys off
7946    /// — returns the author-declared `:entrada :host` byte-string
7947    /// verbatim as a `&str`, borrowed from the typed slot's own
7948    /// [`String`] storage.
7949    ///
7950    /// Named the "singular" half of the DNS-hostname resolver pair on
7951    /// the substrate primitive: the parent-Gateway per-listener
7952    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
7953    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
7954    /// hostname per listener), and this accessor is the typed dispatch
7955    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
7956    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
7957    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
7958    /// per-Aplicacao ingress-hostname surface projects onto.
7959    ///
7960    /// Prior to this lift the `entrada.host.clone()` byte-string was
7961    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
7962    /// per-listener singular `hostname:` axis
7963    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
7964    /// per-HTTPRoute plural `spec.hostnames[]` axis
7965    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
7966    /// consumers read the same `entrada.host` field but the two-site
7967    /// duplication expressed no compile-time contract that the singular
7968    /// Gateway-listener filter and the plural `HTTPRoute` filter list
7969    /// stay in lockstep on future extensions of the `:entrada` slot to
7970    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
7971    /// overlay, a per-cluster SNI fan-out the operator pins through a
7972    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
7973    /// Aplicacao` CR materializer's per-listener virtual-host filter
7974    /// admission-webhook overlay). Any such extension would have to be
7975    /// threaded through every renderer's inline copy of the resolution
7976    /// in lockstep or the Gateway listener's `hostname:` filter would
7977    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
7978    /// — a Gateway-API-conformance divergence whose apply-time symptom
7979    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
7980    /// `NoMatchingParent` — the API server rejects the route because
7981    /// its `hostnames[]` filter doesn't intersect the parent listener's
7982    /// `hostname` filter) is far from the source `caixa.lisp` and never
7983    /// surfaces in the emitted YAML. Lifting the singular and plural
7984    /// resolvers to typed methods on the substrate primitive means
7985    /// every consumer of the Aplicacao's ingress-hostname surface
7986    /// reaches for exactly one typed dispatch, and the pair-invariant
7987    /// `hostnames() == vec![hostname()]` pinned by the sibling
7988    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
7989    /// keeps the two axes in lockstep by construction.
7990    ///
7991    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
7992    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
7993    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
7994    /// the substrate primitive, thin projections at each consumer"
7995    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
7996    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
7997    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
7998    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
7999    /// `:entrada` scalar-value + list-value axes.
8000    #[must_use]
8001    pub const fn hostname(&self) -> &str {
8002        self.host.as_str()
8003    }
8004
8005    /// Substrate-canonical per-`:entrada` DNS-hostname plural
8006    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
8007    /// keys off — returns the singleton `[hostname()]` list under
8008    /// today's single-hostname-per-Aplicacao author surface, and the
8009    /// authoritative multi-hostname list under a future
8010    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
8011    ///
8012    /// Plural half of the DNS-hostname resolver pair — see the
8013    /// companion [`Entrada::hostname`] docstring for the two-consumer
8014    /// lift + pair-invariant discipline (`hostnames() ==
8015    /// vec![hostname()]`, pinned load-bearing by the sibling
8016    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
8017    /// test).
8018    ///
8019    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
8020    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
8021    /// per-rule path-list axis — same `Vec<&str>` shape, same
8022    /// substrate-primitive-owns-the-resolver discipline extended to
8023    /// the per-HTTPRoute virtual-host filter-list axis.
8024    #[must_use]
8025    pub fn hostnames(&self) -> Vec<&str> {
8026        vec![self.hostname()]
8027    }
8028
8029    /// Substrate-canonical per-`:entrada` destination-Servico scalar
8030    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
8031    /// the author-declared `:entrada :para` byte-string verbatim as a
8032    /// `&str`, borrowed from the typed slot's own [`String`] storage.
8033    ///
8034    /// The `:entrada :para` slot names the single member Servico the
8035    /// external Gateway routes to (validated by
8036    /// [`AplicacaoSpec::validate`] to be a
8037    /// [`Membro::caixa`] the Aplicacao declares — a stray
8038    /// `:para` that doesn't name a member is
8039    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
8040    /// backend-attachment miss at cluster-apply time). Under today's
8041    /// single-destination author surface `:entrada :para` is the ingress
8042    /// apex Servico's canonical identity; under a hypothetical
8043    /// future multi-backend author surface (a `:entrada
8044    /// :split :backends` weighted-fan-out overlay for canary /
8045    /// blue-green traffic-split rollouts, per-path override for
8046    /// path-based per-Servico routing beyond the single-apex model,
8047    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8048    /// per-CR admission-webhook that promotes the scalar to a
8049    /// weighted list) this accessor is the substrate primitive's typed
8050    /// dispatch every downstream `HTTPRoute`-aware consumer routes
8051    /// through, so the resolution shape migrates as a unit on one
8052    /// caixa-core edit rather than a coordinated rewrite across every
8053    /// renderer's inline field-access.
8054    ///
8055    /// Prior to this lift the `entrada.para` byte-string was accessed
8056    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
8057    /// `metadata.name` composer's per-destination discriminator arg
8058    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
8059    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
8060    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
8061    /// (`entrada.para.clone()`,
8062    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
8063    /// consumers read the same `entrada.para` field but the two-site
8064    /// duplication expressed no compile-time contract that the HTTPRoute
8065    /// name-discriminator and the per-rule backend name stay in
8066    /// lockstep on future extensions of the `:entrada` slot to a
8067    /// multi-destination author surface. Any such extension would have
8068    /// to be threaded through every renderer's inline copy of the
8069    /// destination projection in lockstep or the HTTPRoute
8070    /// `metadata.name` would silently reference a different destination
8071    /// than its own `backendRefs[]` — an operator-side
8072    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
8073    /// grep-by-name lookup would land on a route whose `backendRefs[]`
8074    /// silently point at a peer Servico, dropping every external
8075    /// `:entrada` flow at the gateway with the destination-drift root
8076    /// cause invisible in the emitted YAML.
8077    ///
8078    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
8079    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
8080    /// the per-listener singular / per-HTTPRoute plural filter axes and
8081    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
8082    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
8083    /// typed dispatch on the substrate primitive, thin projections at
8084    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
8085    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
8086    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
8087    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
8088    /// sibling per-`:entrada` scalar-value + list-value axes — this
8089    /// accessor closes the last unlifted per-`:entrada` scalar axis
8090    /// (the destination-Servico byte-string) so every downstream
8091    /// per-`:entrada` reader now routes through a typed dispatch on
8092    /// the substrate primitive.
8093    #[must_use]
8094    pub const fn destination(&self) -> &str {
8095        self.para.as_str()
8096    }
8097
8098    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
8099    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
8100    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
8101    /// reader keys off — returns the author-declared `:entrada :port`
8102    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
8103    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
8104    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
8105    /// [`AplicacaoError::EntradaPortZero`], not a silent
8106    /// admission-webhook rejection at cluster-apply time).
8107    ///
8108    /// The `:entrada :port` slot carries the destination Servico's
8109    /// canonical in-cluster L4 listener port (`trigger.service.port` on
8110    /// the `pleme-computeunit` library chart), and every downstream
8111    /// consumer that reads the port keys off this scalar (the
8112    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
8113    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
8114    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
8115    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
8116    /// CR materializer's per-Aplicacao gateway port resolver).
8117    ///
8118    /// Prior to this lift the `.port` field was accessed inline at two
8119    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
8120    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
8121    /// the [`AplicacaoSpec::port_for_destination`] resolver's
8122    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
8123    /// open-coded field-accesses that expressed no compile-time link
8124    /// back to the typed slot. A future extension of the `:entrada :port`
8125    /// axis to a richer author surface — a per-cluster override the
8126    /// operator pins through a future `:placement :default-port` slot the
8127    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
8128    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
8129    /// heterogeneous listener ports, an M4
8130    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
8131    /// admission-webhook floor that promotes the scalar to a
8132    /// per-destination map — would have had to be threaded through both
8133    /// open-coded copies in lockstep or the structural-floor validator
8134    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
8135    /// silently disagree on which port a given [`Entrada`] resolves to.
8136    /// Lifting the resolution rule to a typed method on the substrate
8137    /// primitive means every downstream consumer of the Aplicacao's
8138    /// per-`:entrada` L4-port surface reaches for exactly one typed
8139    /// dispatch — the resolver's accept-set migrates as a unit on any
8140    /// future axis addition.
8141    ///
8142    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
8143    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
8144    /// accessors on the per-`:entrada` scalar-value axis — same "one
8145    /// typed dispatch on the substrate primitive, thin projections at
8146    /// each consumer" discipline extended onto the per-`:entrada`
8147    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
8148    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
8149    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
8150    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
8151    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
8152    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
8153    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
8154    /// storage field's name; the accessor's identity name maps onto the
8155    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
8156    /// already carries. Declared `pub const fn` (matching the peer M3
8157    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
8158    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
8159    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
8160    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
8161    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
8162    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
8163    /// [`RateLimit`], and the sibling per-`:placement`
8164    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
8165    /// enum scalar axis — every one a `pub const fn`) so every future
8166    /// substrate-side `const`-context consumer of the resolved
8167    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
8168    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
8169    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
8170    /// admission-webhook `const fn` per-CR gateway-port floor over a
8171    /// typed [`Entrada`], any `const fn` composer that fans on the port
8172    /// at compile time) reaches through the same typed dispatch on the
8173    /// substrate primitive at const-eval time as at runtime. Pinned by
8174    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
8175    /// const-eval posture at module scope via `const _:() = …` items so
8176    /// any future accidental downgrade to non-`const` trips at caixa-core
8177    /// build time.
8178    #[must_use]
8179    pub const fn port(&self) -> u16 {
8180        self.port
8181    }
8182
8183    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
8184    /// slice accessor every HTTPRoute-aware renderer keys off when it
8185    /// wants the raw author-declared path-list (not the fallback-
8186    /// applied projection [`Self::resolved_paths`] returns) — returns
8187    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
8188    /// borrowed from the typed slot's own [`Vec<String>`] storage.
8189    ///
8190    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
8191    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
8192    /// (1449891) closes the fallback-applying arm every per-Aplicacao
8193    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
8194    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
8195    /// catch-all; non-empty slot → per-entry verbatim projection); this
8196    /// accessor closes the raw-slot arm every consumer that must see the
8197    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
8198    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
8199    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
8200    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
8201    /// external-gateway summary line's `{:?}` Debug print — which must
8202    /// name the author's declaration, not the substrate's fallback, so
8203    /// an author reading their graph output can grep their caixa.lisp
8204    /// for the exact list they authored) routes through.
8205    ///
8206    /// Prior to this lift the `.paths` field was accessed inline at four
8207    /// production sites: the two internal reads in [`Self::resolved_paths`]
8208    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
8209    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
8210    /// value-shape gate's `for p in &e.paths` traversal head, and the
8211    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
8212    /// Debug print — four open-coded field-accesses that expressed no
8213    /// compile-time link back to the typed slot. A future extension of
8214    /// the `:entrada :paths` axis to a richer author surface — a
8215    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
8216    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
8217    /// spec supports through `matches[].method`), a per-path per-header
8218    /// filter overlay (`matches[].headers[]`), a per-cluster override
8219    /// the operator pins through a future `:placement :path-overlay`
8220    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8221    /// per-CR admission-webhook that normalized the list at admission
8222    /// time — would have had to be threaded through every open-coded
8223    /// copy in lockstep or the validator's per-entry gate would silently
8224    /// disagree with the renderer's per-entry emit on which list a given
8225    /// `:entrada` block resolves to. Lifting the resolution to a typed
8226    /// method on the substrate primitive means every downstream consumer
8227    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
8228    /// exactly one typed dispatch — the resolver's accept-set migrates
8229    /// as a unit on any future axis addition.
8230    ///
8231    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
8232    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
8233    /// carry axis — same "one typed dispatch on the substrate primitive,
8234    /// thin projections at each consumer" discipline extended onto the
8235    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
8236    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
8237    /// carrier) so every downstream per-`:entrada` reader now routes
8238    /// through a typed dispatch on the substrate primitive. Returns
8239    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
8240    /// treats the list as a read-only sequence — the slice-view is the
8241    /// narrowest borrow that supports every present + roadmapped consumer
8242    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
8243    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
8244    /// view reaches for (the storage-side `Vec` remains reachable through
8245    /// the `pub paths` field for the mutation-carrying serde round-trip
8246    /// and per-test fixture-mutation paths).
8247    #[must_use]
8248    pub const fn paths(&self) -> &[String] {
8249        self.paths.as_slice()
8250    }
8251}
8252
8253/// Canonical default L4 port every typed Servico exposes on its
8254/// in-cluster K8s Service (the `trigger.service.port` axis the
8255/// `pleme-computeunit` library chart emits, the `:entrada :port` author
8256/// surface defaults to when the author omits the slot, and the
8257/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
8258/// `:entrada` block matches the per-`:contratos` destination Servico).
8259/// The single source of truth all three typed-port consumers reach for:
8260///
8261///   - [`Entrada::port`]'s serde default (via the
8262///     [`default_port`] helper this constant feeds); the author surface
8263///     `(:entrada (:host … :para …))` without an explicit `:port` slot
8264///     reads back as a typed [`Entrada`] carrying this exact value;
8265///   - the
8266///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
8267///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
8268///     fallback, fired when the typed `:entrada` block doesn't name
8269///     the per-`:contratos` destination Servico — the typed
8270///     `:contratos` graph carries no per-destination port axis (the
8271///     destination port is the destination Servico's
8272///     `lareira-<nome>` chart's `trigger.service.port`, which the
8273///     Aplicacao-level renderer has no visibility into without a
8274///     resolver round-trip), so the renderer falls back to the
8275///     substrate's canonical Servico-port assumption — by
8276///     construction the same value the destination's own
8277///     `pleme-computeunit` chart emits, the same value the
8278///     destination's own typed `:entrada :port` slot defaults to;
8279///   - every future per-Servico renderer the absorption-roadmap
8280///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
8281///     CR materializer's per-edge port resolver, the future
8282///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
8283///     emitter's per-route bucket key, the future caixa-otel
8284///     collector-pipeline emitter's per-Servico scrape port).
8285///
8286/// Until this lift landed the value `8080` lived at two production-code
8287/// call-sites: the [`default_port`] helper at
8288/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
8289/// and the `.unwrap_or(8080)` literal at
8290/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
8291/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
8292/// resolver). A future Servico-port rebrand — the substrate moving the
8293/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
8294/// gateway grows direct `:80` listeners, to `8443` once the substrate
8295/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
8296/// override the operator pins through a future
8297/// `:placement :default-port` slot — without a coordinated edit on
8298/// both sides would silently emit Servicos listening on one port and
8299/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
8300/// The CNP's apply-time symptom (the policy is admitted but every L4
8301/// flow on the destination Servico's actual port silently drops because
8302/// it doesn't match the whitelisted port) is far from the rebrand
8303/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
8304/// in hubble traces, not in `kubectl describe`. Lifting the literal to
8305/// a shared constant closes the drift footgun structurally — both
8306/// consumers read from the same `u16`, so any rebrand reaches both
8307/// sites by construction.
8308///
8309/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
8310/// per-renderer canonical-K8s-axis constant — the namespace string
8311/// and the canonical Servico port both lived as duplicated literals
8312/// across caixa-core / caixa-mesh / caixa-flux before their respective
8313/// lifts. Same "the typed constant lives in one place" discipline the
8314/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
8315/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
8316/// shared-string axes.
8317///
8318/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
8319pub const DEFAULT_SERVICO_PORT: u16 = 8080;
8320
8321/// Structural floor for the typed `:entrada :port` axis — every
8322/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
8323/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
8324///
8325/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
8326/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
8327/// interprets as "let the kernel pick a free port at bind time", not a
8328/// well-defined destination the substrate's per-`:entrada` Gateway API
8329/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
8330/// carrying `port: 0` degenerates to a nominal-only routing target: the
8331/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
8332/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
8333/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
8334/// at build time rather than at `kubectl apply` time), and the
8335/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
8336/// (caixa-mesh/src/lib.rs:2657 through
8337/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
8338/// [`Entrada::port`] typed value — silently emits a policy whose
8339/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
8340/// actual listener, dropping every L4 flow at the eBPF data plane far
8341/// from the source caixa.lisp with no field naming the port-zero-drift
8342/// root cause.
8343///
8344/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
8345/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
8346/// on the top edge (unlike the peer capped-`u32` `:politicas` /
8347/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
8348/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
8349/// well below `u32::MAX` and therefore need explicit typed caps).
8350///
8351/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
8352/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
8353/// scalar every `(:entrada (:host … :para …))` slot without an explicit
8354/// `:port` inherits through the serde default hook; this constant names
8355/// the accept-set floor every declared port must satisfy. The pair is
8356/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
8357/// substrate's default must satisfy its own accept-set floor by
8358/// construction) — a future rebrand that accidentally moved
8359/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
8360/// negative-cast typo, a per-cluster override the operator pins through
8361/// a future `:placement :default-port` slot that lands out-of-range)
8362/// would silently invalidate the serde-default emission at every
8363/// author-side `(:entrada (:host … :para …))` slot — the compile-time
8364/// invariant pin
8365/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
8366/// closes the drift footgun at caixa-core build time.
8367///
8368/// Lifted as a typed `pub const` (rather than an inline `0` literal at
8369/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
8370/// has exactly one source of truth — the future M4
8371/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
8372/// gateway resolver, the future per-Servico
8373/// `computeunit.trigger.service.port` renderer's per-CR port-value
8374/// validator, and every downstream test-fixture navigator asserting
8375/// the accept-set floor all read from one place. Same shape every
8376/// other typed bracket-floor / bracket-ceiling in this crate carries
8377/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
8378/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
8379/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
8380/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
8381/// [`POLICY_RATE_LIMIT_MAX`]).
8382pub const SERVICO_PORT_MIN: u16 = 1;
8383
8384const fn default_port() -> u16 {
8385    DEFAULT_SERVICO_PORT
8386}
8387
8388// ── the typed view ───────────────────────────────────────────────────
8389
8390/// Typed composition view of the flat Aplicacao slots on
8391/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
8392/// validation + downstream renderer consumption.
8393#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
8394#[serde(rename_all = "camelCase")]
8395pub struct AplicacaoSpec {
8396    pub membros: Vec<Membro>,
8397    pub contratos: Vec<WitContract>,
8398    pub politicas: MeshPolicy,
8399    pub placement: Placement,
8400    pub entrada: Option<Entrada>,
8401}
8402
8403impl AplicacaoSpec {
8404    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
8405    /// per-Aplicacao member-list slice-return accessor every
8406    /// per-Aplicacao member-list reader keys off — returns the author-
8407    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
8408    /// over the same backing buffer the raw `self.membros.as_slice()`
8409    /// field access borrows from.
8410    ///
8411    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
8412    /// member list — the load-bearing identity of the application graph
8413    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
8414    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
8415    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
8416    /// accessor) with a `:versao` semver-requirement string (through
8417    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
8418    /// and every downstream consumer that fans on the member-set keys
8419    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
8420    /// membership-lookup `HashSet<&str>` seed's collect input, the
8421    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
8422    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
8423    /// per-member DNS-1123 / semver-requirement / duplicate-detection
8424    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
8425    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
8426    /// programs.yaml per-`:membros` fan-out emitter's per-entry
8427    /// mapping-composition loop, the `feira app graph` per-Aplicacao
8428    /// member-count print line and per-member tree traversal,
8429    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
8430    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
8431    /// placement engine's per-member weight-topology reader).
8432    ///
8433    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
8434    /// inline at six production sites — the [`AplicacaoSpec::validate`]
8435    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
8436    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
8437    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
8438    /// probe, the same method's per-member `for m in &self.membros`
8439    /// validate-loop traversal head, the
8440    /// [`AplicacaoSpec::detect_sync_cycles`]'s
8441    /// `for m in &self.membros` adjacency-list seed, the
8442    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
8443    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
8444    /// paired with the peer `for m in &spec.membros` per-entry fan-out
8445    /// loop, and the `feira app graph` per-Aplicacao print line's
8446    /// `spec.membros.len()` count formatter argument paired with the
8447    /// peer `for m in &spec.membros` per-member tree traversal — six
8448    /// open-coded field-accesses that expressed no compile-time link
8449    /// back to the typed slot. A future extension of the `:membros`
8450    /// axis to a richer author surface (a per-cluster member-set
8451    /// overlay the operator pins through a future
8452    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
8453    /// roadmap acknowledges, a per-tenant member-alias table the M4
8454    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
8455    /// CR at admission time, a per-Aplicacao dynamic member-set
8456    /// derivation the future adaptive-placement engine computes from
8457    /// weighted membership topology, a promotion of the plain
8458    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
8459    /// Orleans-style virtual-actor dynamic-membership comes into typed
8460    /// scope) would have had to be threaded through all six open-coded
8461    /// copies in lockstep or one consumer would silently disagree with
8462    /// the peers on which member-set a given Aplicacao resolves to —
8463    /// the `HashSet<&str>` name-set seed reading the raw slot while
8464    /// the peer `.is_empty()` refusal probe read an operator-resolved
8465    /// slot would silently split the `:contratos` membership-lookup
8466    /// input from the pre-flight-refusal input, a six-consumer split
8467    /// at the validator + programs.yaml emitter + graph printer far
8468    /// from the source `caixa.lisp` with no field naming the member-
8469    /// set-drift root cause. Lifting the resolution rule to a typed
8470    /// method on the substrate primitive means every downstream
8471    /// consumer of the Aplicacao's per-`:membros` member-list surface
8472    /// reaches for exactly one typed dispatch — the resolver's accept-
8473    /// set migrates as a unit on any future axis addition.
8474    ///
8475    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
8476    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
8477    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
8478    /// static-child-list `Vec`-carry axis, and to the M3
8479    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
8480    /// on the peer per-`:placement` distribution-target-list `Vec`-
8481    /// carry axis. Same "one typed dispatch on the substrate primitive,
8482    /// thin projections at each consumer" discipline. The two peer
8483    /// `Vec`-carry axes still unlifted at the time of this lift —
8484    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
8485    /// WIT-typed edge list) and
8486    /// [`crate::UpgradeFromEntry::instructions`]
8487    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
8488    /// — inherit this accessor's discipline as future compounding runs
8489    /// migrate their consumers onto the shared slice-return shape.
8490    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
8491    /// `AplicacaoSpec` type itself, extending the discipline beyond
8492    /// the inner per-slot types ([`crate::Placement`],
8493    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
8494    /// view every renderer consumes. Named `membros()` to match the
8495    /// storage field's name verbatim and the tatara-lisp author-
8496    /// surface term (`:membros`) the field's own docstring already
8497    /// carries; the accessor's identity maps onto the canonical
8498    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
8499    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
8500    /// every downstream consumer of the member list treats it as a
8501    /// read-only sequence — the slice-view is the narrowest borrow
8502    /// that supports every present + roadmapped consumer
8503    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
8504    /// backing `Vec`'s grow/push/reserve surface that no consumer of
8505    /// the typed view reaches for (the storage-side `Vec` remains
8506    /// reachable through the `pub membros` field for the mutation-
8507    /// carrying serde round-trip and per-test fixture-mutation paths).
8508    #[must_use]
8509    pub const fn membros(&self) -> &[Membro] {
8510        self.membros.as_slice()
8511    }
8512
8513    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
8514    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
8515    /// accessor every per-Aplicacao contract-list reader keys off —
8516    /// returns the author-declared `:contratos` list verbatim as a
8517    /// `&[WitContract]` slice-view over the same backing buffer the raw
8518    /// `self.contratos.as_slice()` field access borrows from.
8519    ///
8520    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
8521    /// WIT-typed edge list — the load-bearing set of directed edges
8522    /// on the application graph whose nodes are the `:membros` entries
8523    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
8524    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
8525    /// six-tuple is the edge identity every downstream duplicate gate
8526    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
8527    /// Servico caller name + a `:para` destination-Servico callee name
8528    /// (through the lifted [`WitContract::source`] +
8529    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
8530    /// caller/callee-Servico axis) with a `:wit` world-reference
8531    /// (through the lifted [`WitContract::world_ref`] (0804823)
8532    /// accessor) and the target-shape-appropriate payload-carrier
8533    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
8534    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
8535    /// (ed22b66) accessor on the per-target-shape payload-carrier
8536    /// axis). Every downstream consumer that fans on the edge-set
8537    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
8538    /// name-set / self-edge / target-shape / dedup fan-out loop, the
8539    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
8540    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
8541    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
8542    /// grouping loop, the `feira app graph` per-Aplicacao contract-
8543    /// count print line and per-contract tree traversal, every future
8544    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
8545    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
8546    /// mesh-policy overlay resolver's per-contract typed-edge weight
8547    /// reader).
8548    ///
8549    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
8550    /// accessed inline at four production sites — the
8551    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
8552    /// per-edge validate-loop traversal head (which drives every
8553    /// per-edge name-set membership lookup, self-edge check,
8554    /// target-shape dispatch, and dedup `HashSet` insert), the
8555    /// [`AplicacaoSpec::detect_sync_cycles`]'s
8556    /// `for c in &self.contratos` adjacency-list seed head (which
8557    /// drives every per-edge sync-vs-pub-sub partition and per-edge
8558    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
8559    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
8560    /// `BTreeMap` grouping loop head (which drives every per-CNP
8561    /// fan-out emit), and the `feira app graph` per-Aplicacao print
8562    /// line's `spec.contratos.len()` count formatter argument paired
8563    /// with the peer `for c in &spec.contratos` per-contract tree
8564    /// traversal — four open-coded field-accesses that expressed no
8565    /// compile-time link back to the typed slot. A future extension
8566    /// of the `:contratos` axis to a richer author surface (a
8567    /// per-cluster contract overlay the operator pins through a
8568    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
8569    /// federation roadmap acknowledges, a per-tenant edge-policy
8570    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
8571    /// materializer resolves per-CR at admission time, a per-edge
8572    /// weight scalar the future adaptive-placement engine reads to
8573    /// bias sync-subgraph routing, a promotion of the plain
8574    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
8575    /// once virtual-actor-style dynamic-edge composition comes into
8576    /// typed scope) would have had to be threaded through all four
8577    /// open-coded copies in lockstep or one consumer would silently
8578    /// disagree with the peers on which edge-set a given Aplicacao
8579    /// resolves to — the validator's per-edge dedup `HashSet` seed
8580    /// reading the raw slot while the peer sync-cycle adjacency-list
8581    /// seed read an operator-resolved slot would silently split the
8582    /// build-time edge-set gate from the runtime deadlock-detection
8583    /// gate, a four-consumer split at the validator, the cycle
8584    /// detector, the CNP emitter, and the graph printer far from
8585    /// the source `caixa.lisp` with no field naming the edge-set-
8586    /// drift root cause. Lifting the resolution rule to a typed method on the
8587    /// substrate primitive means every downstream consumer of the
8588    /// Aplicacao's per-`:contratos` edge-list surface reaches for
8589    /// exactly one typed dispatch — the resolver's accept-set
8590    /// migrates as a unit on any future axis addition.
8591    ///
8592    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
8593    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
8594    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
8595    /// static-child-list `Vec`-carry axis, to the M3
8596    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
8597    /// on the peer per-`:placement` distribution-target-list `Vec`-
8598    /// carry axis, and to the immediately-adjacent sibling M3
8599    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
8600    /// the peer per-`:membros` node-list `Vec`-carry axis — the
8601    /// per-`:contratos` edge-list accessor is the natural pair of
8602    /// the per-`:membros` node-list accessor (graph edges over graph
8603    /// nodes; every graph-shaped consumer reads both). Same "one
8604    /// typed dispatch on the substrate primitive, thin projections
8605    /// at each consumer" discipline. The last remaining `Vec`-carry
8606    /// axis still unlifted at the time of this lift —
8607    /// [`crate::UpgradeFromEntry::instructions`]
8608    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
8609    /// list) — inherits this accessor's discipline as future
8610    /// compounding runs migrate its consumers onto the shared slice-
8611    /// return shape. Second `&[T]`-return accessor on the top-level
8612    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
8613    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
8614    /// `:contratos` are the two `Vec` fields on the outer typed
8615    /// composition view — `:politicas`, `:placement`, `:entrada` are
8616    /// scalar/option-shaped and already route through their per-slot
8617    /// accessor families). Named `contratos()` to match the storage
8618    /// field's name verbatim and the tatara-lisp author-surface term
8619    /// (`:contratos`) the field's own docstring already carries; the
8620    /// accessor's identity maps onto the canonical MESH-COMPOSITION
8621    /// §III.1 vocabulary the slot's docstring already reaches for.
8622    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
8623    /// every downstream consumer of the contract list treats it as a
8624    /// read-only sequence — the slice-view is the narrowest borrow
8625    /// that supports every present + roadmapped consumer
8626    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
8627    /// backing `Vec`'s grow/push/reserve surface that no consumer of
8628    /// the typed view reaches for (the storage-side `Vec` remains
8629    /// reachable through the `pub contratos` field for the mutation-
8630    /// carrying serde round-trip and per-test fixture-mutation paths).
8631    #[must_use]
8632    pub const fn contratos(&self) -> &[WitContract] {
8633        self.contratos.as_slice()
8634    }
8635
8636    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
8637    /// per-Aplicacao mesh-policy composite-reference accessor every
8638    /// per-Aplicacao policy-block reader keys off — returns the author-
8639    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
8640    /// reference over the same backing storage the raw `&self.politicas`
8641    /// field access borrows from.
8642    ///
8643    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
8644    /// mesh-policy composite — the load-bearing container of every
8645    /// mesh-level operational-policy axis every downstream mesh-artifact
8646    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
8647    /// mesh-policy overlay is the single typed surface a
8648    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
8649    /// from). Every per-`:politicas` axis threads through a lifted
8650    /// per-slot accessor on the [`MeshPolicy`] type: the
8651    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
8652    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
8653    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
8654    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
8655    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
8656    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
8657    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
8658    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
8659    /// accessor. Every downstream consumer that reaches for a policy
8660    /// axis first passes through this outer accessor onto the composite
8661    /// and then dispatches onto the per-axis accessor — the two-level
8662    /// dispatch means every per-`:politicas` reader now routes through
8663    /// a typed dispatch on the substrate primitive at both altitudes.
8664    ///
8665    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
8666    /// accessed inline at four production sites — the
8667    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
8668    /// &self.politicas;` traversal seed (which drives every per-axis
8669    /// zero-floor + upper-cap + canonical-form bracket dispatch through
8670    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
8671    /// `p.rate_limit()` on the axis-level lifted accessors), the
8672    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
8673    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
8674    /// chain (which drives every per-`(:de, :para)` CNP
8675    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
8676    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
8677    /// timeout + retry overlay emitter's paired
8678    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
8679    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
8680    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
8681    /// open-coded outer-field accesses that expressed no compile-time
8682    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
8683    /// future extension of the `:politicas` outer axis to a richer
8684    /// author surface (a per-cluster policy overlay the operator pins
8685    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
8686    /// §V federation roadmap acknowledges, a per-tenant policy-alias
8687    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
8688    /// resolves per-CR at admission time, a per-Aplicacao dynamic
8689    /// policy-composite derivation the future adaptive-placement engine
8690    /// computes from a per-cluster load-topology reader, a promotion of
8691    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
8692    /// partition once virtual-actor-style dynamic-mesh-policy
8693    /// composition comes into typed scope) would have had to be threaded
8694    /// through all four open-coded copies in lockstep or one consumer
8695    /// would silently disagree with the peers on which mesh-policy
8696    /// composite a given Aplicacao resolves to — the validator's
8697    /// per-axis bracket-dispatch seed reading the raw slot while the
8698    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
8699    /// would silently split the build-time policy-shape gate from the
8700    /// runtime CNP-emission gate, a four-consumer split at the
8701    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
8702    /// the source `caixa.lisp` with no field naming the policy-drift
8703    /// root cause. Lifting the resolution rule to a typed method on the
8704    /// substrate primitive means every downstream consumer of the
8705    /// Aplicacao's per-`:politicas` mesh-policy composite surface
8706    /// reaches for exactly one typed dispatch — the resolver's accept-
8707    /// set migrates as a unit on any future axis addition.
8708    ///
8709    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
8710    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
8711    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
8712    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
8713    /// close the two `Vec`-carry axes on the outer typed composition
8714    /// view; the outer `:politicas` composite-reference axis is the
8715    /// natural pair to the paired outer `Vec`-carry accessors on the
8716    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
8717    /// emitter reads all four axes as one unit (graph nodes + graph
8718    /// edges + mesh policy + placement pool). Peer to the same
8719    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
8720    /// slot: every M2 `SupervisorSpec`-scoped composite reader
8721    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
8722    /// `restart_window`, `children`) already routes through the M2
8723    /// `SupervisorSpec` accessor family — this lift extends the same
8724    /// "one typed dispatch on the substrate primitive at the outer
8725    /// composition altitude" discipline to the M3 mesh-slot
8726    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
8727    /// remaining peer outer-composite axes still unlifted at the time
8728    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
8729    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
8730    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
8731    /// inherit this accessor's discipline as future compounding runs
8732    /// migrate their consumers onto the shared reference-return shape.
8733    /// Named `politicas()` to match the storage field's name verbatim
8734    /// and the tatara-lisp author-surface term (`:politicas`) the
8735    /// field's own docstring already carries; the accessor's identity
8736    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
8737    /// slot's docstring already reaches for. Returns `&MeshPolicy`
8738    /// (not the owning composite by copy or clone) because every
8739    /// downstream consumer of the mesh-policy composite treats it as a
8740    /// read-only per-axis dispatch source — the reference-view is the
8741    /// narrowest borrow that supports every present + roadmapped
8742    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
8743    /// emptiness probe) without cloning the composite through every
8744    /// consumer's fast path.
8745    #[must_use]
8746    pub const fn politicas(&self) -> &MeshPolicy {
8747        &self.politicas
8748    }
8749
8750    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
8751    /// per-Aplicacao distribution-composite composite-reference accessor
8752    /// every per-Aplicacao placement-block reader keys off — returns the
8753    /// author-declared `:placement` composite verbatim as a `&Placement`
8754    /// reference over the same backing storage the raw `&self.placement`
8755    /// field access borrows from.
8756    ///
8757    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
8758    /// distribution composite — the load-bearing container of every
8759    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
8760    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
8761    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
8762    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
8763    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
8764    /// `:affinity` hint). Every per-`:placement` axis threads through a
8765    /// lifted per-slot accessor on the [`Placement`] type: the
8766    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
8767    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
8768    /// per-cluster distribution-target slice-return accessor, the
8769    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
8770    /// optional-scalar accessor, and the [`Placement::shard_key`]
8771    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
8772    /// downstream consumer that reaches for a placement axis first passes
8773    /// through this outer accessor onto the composite and then dispatches
8774    /// onto the per-axis accessor — the two-level dispatch means every
8775    /// per-`:placement` reader now routes through a typed dispatch on the
8776    /// substrate primitive at both altitudes.
8777    ///
8778    /// Prior to this lift the `.placement` `Placement` composite was
8779    /// accessed inline at three production sites — the
8780    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
8781    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
8782    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
8783    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
8784    /// cluster `.clusters()` validate-loop traversal head, the per-
8785    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
8786    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
8787    /// paired with the shape-gate cascade's `.shard_key()` /
8788    /// `.estrategia()` diagnostic-carry pair), the
8789    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
8790    /// per-entry placement-block emitter's outer
8791    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
8792    /// seed (which fans onto every per-cluster `programs[]` entry as a
8793    /// self-describing distribution overlay the aggregator filters by),
8794    /// and the `feira app graph` per-Aplicacao print line's paired
8795    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
8796    /// then-inner-accessor chains (which drive the human-readable
8797    /// distribution summary of the typed Aplicacao view) — three open-
8798    /// coded outer-field accesses that expressed no compile-time link
8799    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
8800    /// extension of the `:placement` outer axis to a richer author surface
8801    /// (a per-cluster placement overlay the operator pins through a
8802    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
8803    /// federation roadmap acknowledges, a per-tenant placement-alias
8804    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
8805    /// resolves per-CR at admission time, a per-Aplicacao dynamic
8806    /// placement-composite derivation the future M5 adaptive-placement
8807    /// engine computes from a per-cluster load-topology reader, a
8808    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
8809    /// partition once Orleans-style virtual-actor dynamic-placement comes
8810    /// into typed scope) would have had to be threaded through all three
8811    /// open-coded copies in lockstep or one consumer would silently
8812    /// disagree with the peers on which placement composite a given
8813    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
8814    /// seed reading the raw slot while the peer
8815    /// `programs_for_aplicacao` emitter read an operator-resolved slot
8816    /// would silently split the build-time distribution-shape gate from
8817    /// the runtime programs.yaml distribution-annotation gate, a three-
8818    /// consumer split at the validator, the programs.yaml emitter, and
8819    /// the `feira app graph` printer far from the source `caixa.lisp`
8820    /// with no field naming the placement-drift root cause. Lifting the
8821    /// resolution rule to a typed method on the substrate primitive
8822    /// means every downstream consumer of the Aplicacao's per-
8823    /// `:placement` distribution composite surface reaches for exactly
8824    /// one typed dispatch — the resolver's accept-set migrates as a unit
8825    /// on any future axis addition.
8826    ///
8827    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
8828    /// `AplicacaoSpec` type itself — sibling to the seed
8829    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
8830    /// composite-reference accessor on the peer per-`:politicas` outer-
8831    /// composite axis, and to the paired slice-return accessors
8832    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
8833    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
8834    /// the two `Vec`-carry axes on the outer typed composition view; the
8835    /// outer `:placement` composite-reference axis is the natural pair
8836    /// to the peer `:politicas` composite-reference axis on the two
8837    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
8838    /// how-to-run policy overlay, `:placement` carries the where-to-run
8839    /// distribution composite — every whole-Aplicacao mesh-artifact
8840    /// emitter reads both as one unit). Same "one typed dispatch on the
8841    /// substrate primitive, thin projections at each consumer"
8842    /// discipline the peer per-`:politicas` composite-reference axis
8843    /// already routes through. The one remaining outer-composite axis
8844    /// still unlifted at the time of this lift —
8845    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
8846    /// external-gateway composite) — inherits this accessor's discipline
8847    /// as the next compounding run migrates its consumers onto the shared
8848    /// reference-return shape, closing the outer-composite altitude on
8849    /// every M3 mesh-slot axis. Named `placement()` to match the storage
8850    /// field's name verbatim and the tatara-lisp author-surface term
8851    /// (`:placement`) the field's own docstring already carries; the
8852    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
8853    /// vocabulary the slot's docstring already reaches for. Returns
8854    /// `&Placement` (not the owning composite by copy or clone) because
8855    /// every downstream consumer of the placement composite treats it as
8856    /// a read-only per-axis dispatch source — the reference-view is the
8857    /// narrowest borrow that supports every present + roadmapped consumer
8858    /// (per-axis accessor dispatch, serde composite-serialization) without
8859    /// cloning the composite through every consumer's fast path.
8860    #[must_use]
8861    pub const fn placement(&self) -> &Placement {
8862        &self.placement
8863    }
8864
8865    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
8866    /// per-Aplicacao external-gateway composite optional-composite-
8867    /// reference accessor every per-Aplicacao gateway-block reader
8868    /// keys off — returns the author-declared `:entrada` composite
8869    /// verbatim as an `Option<&Entrada>` reference over the same
8870    /// backing storage the raw `self.entrada.as_ref()` field access
8871    /// borrows from, with `None` naming the internal-only mesh shape
8872    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
8873    /// gateway_routes emitter treats as "emit nothing" and the peer
8874    /// `feira app graph` printer treats as "internal-only mesh").
8875    ///
8876    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
8877    /// external-gateway composite — the load-bearing container of
8878    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
8879    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
8880    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
8881    /// hostname axis, §III.4 for the `:para` destination-Servico
8882    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
8883    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
8884    /// axis threads through a lifted per-slot accessor on the
8885    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
8886    /// Gateway-API `Listener.hostname` scalar accessor, the paired
8887    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
8888    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
8889    /// backendRefs destination-Servico scalar accessor, the
8890    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
8891    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
8892    /// scalar accessor. Every downstream consumer that reaches for
8893    /// an entrada axis first passes through this outer accessor onto
8894    /// the composite and then dispatches onto the per-axis accessor
8895    /// — the two-level dispatch means every per-`:entrada` reader
8896    /// now routes through a typed dispatch on the substrate primitive
8897    /// at both altitudes.
8898    ///
8899    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
8900    /// was accessed inline at four production sites — the
8901    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
8902    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
8903    /// (which drives every per-axis refusal on the composite: the
8904    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
8905    /// `EntradaMemberMissing` membership lookup against the
8906    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
8907    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
8908    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
8909    /// per-path shape gate on each entry of `e.paths`), the
8910    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
8911    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
8912    /// composite-projection seed (which drives the destination-
8913    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
8914    /// backendRefs port emitter fans on), the
8915    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
8916    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
8917    /// early-return seed (which drives the "no `:entrada` ⇒ no
8918    /// external artifacts" partition on the whole-Aplicacao Gateway-
8919    /// API emitter's fan-out), and the `feira app graph` per-
8920    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
8921    /// external-gateway summary emitter (which drives the human-
8922    /// readable `entrada: host → para (paths=…, port=…)` /
8923    /// `entrada: (internal-only mesh)` partition on the typed
8924    /// Aplicacao view) — four open-coded outer-field accesses that
8925    /// expressed no compile-time link back to the typed slot at the
8926    /// [`AplicacaoSpec`] altitude. A future extension of the
8927    /// `:entrada` outer axis to a richer author surface (a
8928    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
8929    /// at admission time so an Aplicacao can expose a public-web +
8930    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
8931    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
8932    /// operator can pin a per-cluster hostname override without
8933    /// re-authoring the `caixa.lisp`, a promotion of the plain
8934    /// `Option<Entrada>` to a richer `{single, multi}` partition once
8935    /// the multi-`:entrada` roadmap lands) would have had to be
8936    /// threaded through all four open-coded copies in lockstep or one
8937    /// consumer would silently disagree with the peers on which
8938    /// entrada composite a given Aplicacao resolves to — the
8939    /// validator's per-axis bracket-dispatch seed reading the raw
8940    /// slot while the peer `gateway_routes` emitter read an
8941    /// operator-resolved slot would silently split the build-time
8942    /// gateway-shape gate from the runtime Gateway + HTTPRoute
8943    /// emission gate, a four-consumer split at the validator, the
8944    /// `port_for_destination` L4-port resolver, the `gateway_routes`
8945    /// emitter, and the `feira app graph` printer far from the
8946    /// source `caixa.lisp` with no field naming the entrada-drift
8947    /// root cause. Lifting the resolution rule to a typed method on
8948    /// the substrate primitive means every downstream consumer of
8949    /// the Aplicacao's per-`:entrada` external-gateway composite
8950    /// surface reaches for exactly one typed dispatch — the
8951    /// resolver's accept-set migrates as a unit on any future axis
8952    /// addition.
8953    ///
8954    /// Third and final `&Composite`-return accessor on the top-level
8955    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
8956    /// unlifted outer-composite axis on the outer typed composition
8957    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
8958    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
8959    /// accessor on the per-`:politicas` outer-composite axis and to
8960    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
8961    /// distribution-composite composite-reference accessor on the
8962    /// per-`:placement` outer-composite axis; extends the outer-
8963    /// composite reference-return discipline the two peers already
8964    /// route through onto the last unlifted per-`AplicacaoSpec`
8965    /// outer-composite axis. The `:entrada` outer-composite axis is
8966    /// the natural pair to the two peer outer-composite axes on the
8967    /// three operationally-symmetric M3 mesh-slot outer composites
8968    /// (`:politicas` carries the how-to-run policy overlay,
8969    /// `:placement` carries the where-to-run distribution composite,
8970    /// `:entrada` carries the who-can-reach-it external-gateway
8971    /// composite — every whole-Aplicacao mesh-artifact emitter reads
8972    /// all three as one unit). Same "one typed dispatch on the
8973    /// substrate primitive, thin projections at each consumer"
8974    /// discipline the peer outer-composite axes already route through.
8975    /// Named `entrada()` to match the storage field's name verbatim
8976    /// and the tatara-lisp author-surface term (`:entrada`) the
8977    /// field's own docstring already carries; the accessor's
8978    /// identity maps onto the canonical MESH-COMPOSITION §III.4
8979    /// vocabulary the slot's docstring already reaches for. Returns
8980    /// `Option<&Entrada>` (not the owning composite by copy or
8981    /// clone) because every downstream consumer of the entrada
8982    /// composite treats it as a read-only per-axis dispatch source
8983    /// — the reference-view is the narrowest borrow that supports
8984    /// every present + roadmapped consumer (per-axis accessor
8985    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
8986    /// port-fallback projection, early-return partition on the
8987    /// `None` arm) without cloning the composite through every
8988    /// consumer's fast path. The `Option` half of the return-type
8989    /// preserves the load-bearing "author-omitted `:entrada` ⇒
8990    /// internal-only mesh" partition (not a default composite the
8991    /// downstream must reject on emptiness) — the accessor projects
8992    /// the raw `Option<Entrada>` slot's presence bit through the
8993    /// reference-return unchanged.
8994    #[must_use]
8995    pub const fn entrada(&self) -> Option<&Entrada> {
8996        self.entrada.as_ref()
8997    }
8998
8999    /// Validate the typed shape:
9000    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
9001    ///     and a non-empty `:versao`; no two entries share the same
9002    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
9003    ///     not a multiset)
9004    ///   - every `:contratos` :de + :para must be in `:membros`
9005    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
9006    ///     contract is an inter-Servico edge, so a Servico contracting
9007    ///     with itself is a build error under every WIT shape
9008    ///     (MESH-COMPOSITION §III.1)
9009    ///   - no two `:contratos` entries agree on
9010    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
9011    ///     edges are a set, not a multiset (peer of the `:membros` /
9012    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
9013    ///   - `:entrada :para` must be in `:membros`
9014    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
9015    ///     `:placement Replicated`/`SingleNode` must NOT declare
9016    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
9017    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
9018    ///     between strategy and shard-key is symmetric: every validated
9019    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
9020    ///     Sharded`
9021    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
9022    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
9023    ///     the shard pool (MESH-COMPOSITION §III.1)
9024    ///   - every `:clusters` entry is non-empty and unique
9025    ///   - `:placement :affinity`, when set, is non-empty
9026    ///   - the synchronous-`:contratos` subgraph is acyclic
9027    ///     (MESH-COMPOSITION §III.3)
9028    ///   - every declared `:politicas` value is operationally meaningful
9029    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
9030    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
9031    ///     omit the field instead to express "no policy on this axis")
9032    pub fn validate(&self) -> Result<(), AplicacaoError> {
9033        self.validate_membros()?;
9034
9035        // `:contratos` per-slot gate — folds both structural axes on the
9036        // slot into one substrate primitive: the per-entry cascade (shape
9037        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
9038        // target + whole-edge dedup) and the cross-edge sync-cycle axis
9039        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
9040        // — pub-sub edges excluded, "acyclic by construction"). Same
9041        // fold-per-axis-plus-cross-axis discipline the sibling
9042        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
9043        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
9044        // onto `:contratos` so every future consumer of the slot (the M4
9045        // admission webhook re-checking `:contratos` after a per-edge
9046        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
9047        // acknowledges) reaches *both* structural axes through one call.
9048        self.validate_contratos()?;
9049
9050        self.validate_entrada()?;
9051
9052        self.validate_placement()?;
9053
9054        self.validate_politicas()?;
9055
9056        Ok(())
9057    }
9058
9059    /// The `:membros` graph-node name set — the membership oracle every
9060    /// per-Aplicacao name-reference axis resolves against.
9061    ///
9062    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
9063    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
9064    /// :para`, and `:entrada :para`. Each must resolve to a declared
9065    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
9066    /// the external gateway both address graph nodes, so a reference to
9067    /// a node the graph does not contain is a build error). All three
9068    /// resolve against *this* set, so the set's construction is the one
9069    /// shared substrate primitive underneath the whole reference-
9070    /// resolution surface.
9071    ///
9072    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
9073    /// `self.membros().iter().map(Membro::nome).collect()` builder so
9074    /// the two per-slot gates that consume it — the per-`:contratos`
9075    /// membership arms still inline at `validate` and the lifted
9076    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
9077    /// oracle through one dispatch rather than each open-coding the
9078    /// projection. Every future consumer on the same axis (the M4
9079    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
9080    /// reference resolver, the per-`:contratos`-edge `:politicas`
9081    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
9082    /// resolves an edge's endpoints against the same membership set
9083    /// before it can key a per-edge policy off them) inherits the
9084    /// projection through the same call, so a future rebrand of the
9085    /// node-identity axis (a namespace-qualified member name the CR
9086    /// materializer applies per-CR, the `:membros :nome-suffix`
9087    /// overlay §III.2 acknowledges) lands at exactly one place rather
9088    /// than at every reference-resolution site in lockstep. Peer of
9089    /// the sibling per-slot substrate primitives
9090    /// [`MeshPolicy::validate`] (f03a154) and
9091    /// [`WitContract::identity`] on their own axes.
9092    fn membro_names(&self) -> std::collections::HashSet<&str> {
9093        self.membros().iter().map(Membro::nome).collect()
9094    }
9095
9096    /// Reject `:contratos` entries whose endpoints are malformed,
9097    /// reference a Servico outside the graph, self-loop, carry an
9098    /// empty `:wit` shape, duplicate a prior entry on the six-axis
9099    /// identity key, or close a synchronous-edge cycle in the
9100    /// resulting typed graph.
9101    ///
9102    /// The `:contratos` slot is the typed inter-Servico edge set
9103    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
9104    /// edge whose `:de` / `:para` reference two distinct members and
9105    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
9106    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
9107    /// per-HTTP `HTTPRoute`) fans out on.
9108    ///
9109    /// Two structural axes on the slot are folded into this per-slot
9110    /// gate: the per-entry axis (six per-edge arms, listed below) and
9111    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
9112    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
9113    /// per-entry cascade). Same
9114    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
9115    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
9116    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
9117    /// `:politicas` slot, extended here onto `:contratos`.
9118    ///
9119    /// Six per-entry axes are gated first, in the canonical
9120    /// edge-direction order the paired diagnostics already encode
9121    /// (per-arm value shape before graph-membership lookup; structural
9122    /// self-edge before payload-shape target dispatch; whole-edge dedup
9123    /// last):
9124    ///
9125    ///   - per-arm `:de` / `:para` value shape via
9126    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
9127    ///     `:de` before `:para`;
9128    ///   - per-edge graph-membership against the
9129    ///     [`AplicacaoSpec::membro_names`] oracle via
9130    ///     [`WitContract::require_endpoints_in`] (folds the twin
9131    ///     `:de` / `:para` arms onto one substrate-primitive
9132    ///     dispatch), `:de` before `:para`;
9133    ///   - structural self-edge via [`WitContract::is_self_loop`]
9134    ///     (caller-equals-callee under any WIT shape);
9135    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
9136    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
9137    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
9138    ///     `Capability` — each carry their own required payload field);
9139    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
9140    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
9141    ///     slot)` tuple).
9142    ///
9143    /// One cross-edge axis is gated last, after the per-entry cascade
9144    /// completes cleanly:
9145    ///
9146    ///   - synchronous-edge cycle detection via
9147    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
9148    ///     three-coloring over the sync-only subgraph, pub-sub edges
9149    ///     skipped per MESH-COMPOSITION §III.3 —
9150    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
9151    ///     per-entry cascade so a per-entry defect surfaces through its
9152    ///     narrower shape/membership/dedup arm before the cross-edge
9153    ///     cycle diagnostic, matching the pre-fold `validate`-side
9154    ///     dispatch ordering (`validate_contratos()? →
9155    ///     detect_sync_cycles()?`).
9156    ///
9157    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
9158    /// seen_contracts = …; for c in self.contratos() { … }` block onto
9159    /// a named per-slot gate, closing the last unlifted per-slot gate
9160    /// on the M3 mesh-slot family. Every peer slot already carries the
9161    /// shape ([`AplicacaoSpec::validate_membros`],
9162    /// [`AplicacaoSpec::validate_entrada`],
9163    /// [`AplicacaoSpec::validate_placement`],
9164    /// [`AplicacaoSpec::validate_politicas`]).
9165    ///
9166    /// Self-contained on `&self` — it resolves its own membership
9167    /// oracle through [`AplicacaoSpec::membro_names`] rather than
9168    /// borrowing one threaded down from `validate`, and runs its own
9169    /// cross-edge cycle probe rather than deferring the axis to an
9170    /// outer dispatch — so a future consumer that re-validates *one*
9171    /// slot against a mutated spec (the M4 admission webhook
9172    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
9173    /// without re-walking `:membros` / `:entrada` / `:placement` /
9174    /// `:politicas`, or the M4 per-edge policy resolver
9175    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
9176    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
9177    /// own identity closure *and* the sync-cycle invariant before it
9178    /// can key a per-edge override off the endpoint tuple) reaches
9179    /// *both* structural axes on the slot through one call, exactly as
9180    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
9181    /// cross-axis surfaces on `:politicas` through
9182    /// [`MeshPolicy::validate`].
9183    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
9184        let names = self.membro_names();
9185
9186        // Identity key for the typed-edge duplicate gate below: every
9187        // field that distinguishes one contract from another. Two
9188        // entries that agree on all six are *the same edge declared
9189        // twice*, the typed-graph analogue of duplicate `:membros` /
9190        // `:placement :clusters` / `:entrada :paths` entries (which
9191        // are already build errors at this layer). Rejecting it at the
9192        // validate gate closes a renderer-side footgun: caixa-mesh's
9193        // `cilium_network_policies` keys each emitted policy by
9194        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
9195        // (de, para) and identical payload would land as two K8s
9196        // objects with colliding `metadata.name`, rejected at apply
9197        // time far from the source caixa.lisp.
9198        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
9199            std::collections::HashSet::new();
9200        for c in self.contratos() {
9201            // Per-axis value-shape gate on every `:contratos` name
9202            // reference, before any graph-membership lookup. Empty +
9203            // DNS-1123-malformed `:de`/`:para` values silently fell
9204            // through to `ContratoMemberMissing` at the lookup arm
9205            // because every `:membros :caixa` is shape-validated
9206            // (3f9d7a0), so the `names` set structurally cannot contain
9207            // an empty / malformed string and the membership-lookup
9208            // diagnostic always misframed the root cause as
9209            // "this caixa is not in `:membros`". The shape gate runs
9210            // ahead of the lookup so structurally-impossible-to-match
9211            // inputs route through the narrower self-locating
9212            // diagnostic, preserving the legitimate "well-shaped
9213            // phantom reference" arm. `:de` runs before `:para` per
9214            // the canonical edge-direction order the existing
9215            // membership lookup, self-edge check, target dispatch,
9216            // and diagnostic strings already use.
9217            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
9218            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
9219            // Per-edge graph-membership gate on the twin `:de` / `:para`
9220            // arms — folded onto the substrate-primitive dispatch
9221            // [`WitContract::require_endpoints_in`] so every per-edge
9222            // consumer of the endpoint-resolution axis (this per-slot
9223            // gate at build time, the M4 admission webhook re-checking
9224            // one edge after a per-`(:de, :para)` patch, the per-edge
9225            // `:politicas` override MESH-COMPOSITION §III.2 #3
9226            // acknowledges) reaches the axis through one call rather
9227            // than re-inlining the twin `if !names.contains(...)`
9228            // cascade. `:de` fires before `:para` inside the primitive,
9229            // preserving byte-equal diagnostic ordering with the
9230            // pre-lift inline cascade.
9231            c.require_endpoints_in(&names)?;
9232            // A `:contratos` entry is an *inter*-Servico contract
9233            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
9234            // typed edge between two distinct graph nodes. An edge whose
9235            // `:de` equals its `:para` is a Servico contracting with
9236            // itself — a degenerate edge under every WIT shape. Firing
9237            // the gate before the `:wit`/`target()` shape checks means
9238            // the structural "this edge can't exist" error precedes the
9239            // narrower payload-shape diagnostics, and shape-agnostically
9240            // covers all four `WitTarget` arms (HTTP / Store / Capability
9241            // / PubSub) at one point. Peer of the duplicate-`:contratos`
9242            // / duplicate-`:membros` set gates: both reject a structurally
9243            // ill-formed graph at the typed surface, before the renderer
9244            // emits a K8s object that fails or no-ops far from the source
9245            // caixa.lisp.
9246            if c.is_self_loop() {
9247                return Err(AplicacaoError::contrato_self_loop(c));
9248            }
9249            if c.world_ref().is_empty() {
9250                return Err(AplicacaoError::empty_wit(c.edge_pair()));
9251            }
9252            // Shape ↔ target consistency — surfaces "HTTP wit without
9253            // :endpoint", "NATS wit with :endpoint set", etc. as named
9254            // build errors instead of silent renderer drops. Threaded
9255            // through the duplicate-edge diagnostic below (via
9256            // [`WitTarget::label`]) so the "which typed target arm did
9257            // the duplicate carry" question is answered by the typed
9258            // enum's variant discriminator, not by re-probing the raw
9259            // `Option<String>` payload fields.
9260            let target_view = c.target()?;
9261            // Contract identity: (de, para, wit, endpoint, subject, slot).
9262            // Two contracts that match on all six are the same typed edge
9263            // declared twice — author error, not a legitimate variant of
9264            // "same caller-callee pair, different payload" (e.g.
9265            // cart→catalog at /products vs /search), which keeps distinct
9266            // identity keys via the differing endpoint payloads.
9267            let key = c.identity();
9268            crate::render::insert_first_seen(&mut seen_contracts, key, || {
9269                AplicacaoError::contrato_duplicate(c, &target_view)
9270            })?;
9271        }
9272
9273        // Cross-edge cycle axis on the `:contratos` slot — folded into
9274        // the per-slot gate so the two structural axes on `:contratos`
9275        // (per-entry shape + membership + dedup above; cross-edge sync-
9276        // cycle detection here) reach every consumer through one call.
9277        // Same discipline the sibling per-slot compound gate
9278        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
9279        // — one named per-slot gate that folds *both* per-axis and
9280        // cross-axis surfaces on the same slot onto one substrate
9281        // primitive — extended here onto `:contratos`, closing the last
9282        // per-slot-axis-family that lived split across `validate` (the
9283        // per-entry `validate_contratos` half here and the cross-edge
9284        // `detect_sync_cycles` call the sibling below at `validate`
9285        // dispatched separately).
9286        //
9287        // Runs after the per-entry cascade so a per-entry defect (empty
9288        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
9289        // target inconsistency, whole-edge duplicate) surfaces first
9290        // through its narrower [`AplicacaoError`] arm before the cross-
9291        // edge cycle diagnostic. This matches the pre-lift ordering the
9292        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
9293        // → self.detect_sync_cycles()?`) — the cycle detector was
9294        // already the second `:contratos`-axis gate in the dispatch,
9295        // just at the outer altitude; the fold moves it under the same
9296        // named per-slot gate without reshaping the diagnostic order.
9297        self.detect_sync_cycles()?;
9298
9299        Ok(())
9300    }
9301
9302    /// Reject `:entrada` values that are operationally meaningless,
9303    /// structurally malformed, or reference a Servico outside the
9304    /// graph.
9305    ///
9306    /// The `:entrada` slot is the Aplicacao's single external ingress
9307    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
9308    /// Gateway API v1 `Listener`, `:paths` become the paired
9309    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
9310    /// the member the route forwards to. Omitting the slot entirely is
9311    /// the internal-only-mesh partition — an Aplicacao with no external
9312    /// surface — so the `None` arm is a clean pass, not a refusal.
9313    ///
9314    /// Five axes are gated here, in the canonical order the paired
9315    /// diagnostics already encode (reference-resolution before value
9316    /// shape, per-axis emptiness before per-axis grammar):
9317    ///
9318    ///   - `:para` — DNS-1123 value shape, then membership against the
9319    ///     [`AplicacaoSpec::membro_names`] oracle;
9320    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
9321    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
9322    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
9323    ///     path grammar, and set-not-multiset uniqueness.
9324    ///
9325    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
9326    /// Some(e) = self.entrada() { … }` block onto a named per-slot
9327    /// gate, the shape the three peer M3 mesh slots already carry
9328    /// ([`AplicacaoSpec::validate_membros`],
9329    /// [`AplicacaoSpec::validate_placement`],
9330    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
9331    /// `&self` — it resolves its own membership oracle through
9332    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
9333    /// threaded down from `validate` — so a future consumer that
9334    /// re-validates *one* slot against a mutated spec (the M4 admission
9335    /// webhook re-checking `:entrada` after a gateway-host patch
9336    /// without re-walking the whole `:contratos` graph) reaches the
9337    /// axis through one call, exactly as `detect_sync_cycles` is
9338    /// already self-contained for the M4 per-edge policy resolver.
9339    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
9340        let names = self.membro_names();
9341        if let Some(e) = self.entrada() {
9342            // Route the per-`:entrada` composite-reference read
9343            // through the lifted [`AplicacaoSpec::entrada`] accessor
9344            // rather than the raw `&self.entrada` field access — the
9345            // shape-and-membership gate's traversal head is now the
9346            // canonical read-side surface every per-Aplicacao entrada
9347            // consumer routes through, closing the fourth of four
9348            // open-coded outer-field accesses on the per-`:entrada`
9349            // outer-composite axis.
9350            //
9351            // Shape gate on `:entrada :para` runs ahead of the
9352            // membership lookup. Every `:membros :caixa` past
9353            // `validate_membro_caixa` is a valid DNS-1123 label
9354            // (3f9d7a0), so the `names` set structurally cannot
9355            // contain an empty / malformed string and the membership-
9356            // lookup diagnostic always misframed the root cause as
9357            // "this caixa is not in `:membros`". The shape gate
9358            // routes structurally-impossible-to-match inputs through
9359            // the narrower self-locating diagnostic, preserving the
9360            // legitimate "well-shaped phantom reference" arm — the
9361            // same trajectory the peer `:membros :caixa` (3f9d7a0),
9362            // `:placement :clusters` (6c8c00b), and `:contratos :de`
9363            // / `:para` (8d5af6b) axes already follow. This closes
9364            // the fourth and last Aplicacao-level Servico-name
9365            // reference axis on the canonical DNS-1123 floor.
9366            // Route the per-`:entrada :para` byte-string reads through
9367            // the lifted [`Entrada::destination`] accessor rather than
9368            // the raw `e.para` field access — the three
9369            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
9370            // (shape-gate `validate_entrada_para` arg, membership
9371            // lookup, `EntradaMemberMissing` diagnostic carry) now key
9372            // off exactly one typed dispatch on the substrate
9373            // primitive, closing the last unlifted per-`:entrada :para`
9374            // raw-field-access axis on the M3 mesh-slot validator.
9375            // The `.destination().to_string()` at the diagnostic site
9376            // is byte-identical to `.para.clone()` — pinned by the
9377            // sibling `destination_returns_entrada_para_byte_equal` +
9378            // `destination_borrows_from_entrada_para_storage` accessor
9379            // tests — so a future rebrand of the underlying `:para`
9380            // storage (a lift from `String` to a typed
9381            // `ServicoName(String)` newtype, a per-Aplicacao interning
9382            // arena the M4 CR materializer authors, a
9383            // `smol_str::SmolStr` inline-buffer swap) flows through
9384            // the accessor's one body without a coordinated
9385            // per-consumer rewrite across the M3 mesh validator.
9386            validate_entrada_para(e.destination())?;
9387            if !names.contains(e.destination()) {
9388                return Err(AplicacaoError::entrada_member_missing(e));
9389            }
9390            // Route the per-`:entrada :host` byte-string reads through
9391            // the lifted [`Entrada::hostname`] accessor rather than
9392            // the raw `e.host` field access — the emptiness gate and
9393            // the shape-gate `validate_entrada_host` arg now key off
9394            // exactly one typed dispatch on the substrate primitive,
9395            // closing the last unlifted per-`:entrada :host` raw-
9396            // field-access axis on the M3 mesh-slot validator. Peer
9397            // of the sibling per-`:entrada :para` convergence above
9398            // and pinned by the existing
9399            // `hostname_returns_entrada_host_byte_equal` +
9400            // `hostnames_returns_singleton_of_hostname_accessor`
9401            // accessor tests, so any future
9402            // Gateway-API-shaped host renormalization (a wildcard-
9403            // label lift, a trailing-`.` FQDN substitution, an IDNA
9404            // Punycode round-trip the SNI fan-out overlay authors)
9405            // flows through the accessor's one body without a
9406            // coordinated per-consumer rewrite across the M3 mesh
9407            // validator.
9408            if e.hostname().is_empty() {
9409                return Err(AplicacaoError::EmptyEntradaHost);
9410            }
9411            // The `:host` lands verbatim as a K8s Gateway API v1
9412            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
9413            // both apiserver-validated against the same restrictive
9414            // pattern: lowercase RFC 1123 DNS subdomain, optional
9415            // single leading wildcard label (`*.`), max length 253,
9416            // per-label max length 63, no IP literals, no scheme,
9417            // no port. Until this gate landed `validate()` only
9418            // refused the empty string (`EmptyEntradaHost`); a
9419            // structurally invalid hostname (`"https://example.com"`,
9420            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
9421            // `"_underscored.example.com"`, `"FOO.example.com"`,
9422            // `"checkout.quero.cloud."`) silently passed validate
9423            // and the apiserver `field is invalid` error surfaced at
9424            // `kubectl apply` time, far from the source caixa.lisp.
9425            // Lifting the gate to caixa-build time mirrors the
9426            // `:entrada :paths` value-shape trajectory (eb3456d) and
9427            // closes the last unstructured `:entrada` axis.
9428            validate_entrada_host(e.hostname())?;
9429            // Structural-floor gate on `:entrada :port`: every
9430            // validated `Entrada::port` past this gate lies in
9431            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
9432            // type-inferred ceiling closes the top edge, so no companion
9433            // upper-cap arm is needed here — unlike the peer capped-
9434            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
9435            // `require_positive_bounded_u32` bracket covers both edges).
9436            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
9437            // accept-set-floor const rather than the prior inline
9438            // `if e.port == 0` byte-check so a future rebrand of the
9439            // accept-set floor (a hypothetical unprivileged-only
9440            // migration lifting the floor to `1024`, a per-cluster
9441            // scoping the operator pins through a future
9442            // `:placement :port-floor` slot as the M4 typed-slot
9443            // trajectory adds it, the future
9444            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9445            // per-Aplicacao gateway resolver reaching for the same
9446            // floor) is a one-line edit on the canonical
9447            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
9448            // rewrite across the emit site + the pin test + every
9449            // future per-target renderer the substrate adds.
9450            if e.port() < SERVICO_PORT_MIN {
9451                return Err(AplicacaoError::EntradaPortZero);
9452            }
9453            // Each `:entrada :paths` entry becomes a K8s Gateway API
9454            // HTTPRoute `matches[].path.value`. The Gateway API rejects
9455            // values that don't start with `/` for `type: PathPrefix`,
9456            // and an empty value is meaningless. Surface those as build
9457            // errors (MESH-COMPOSITION §III.3) rather than apply-time
9458            // failures. Empty `:paths` itself is fine — caixa-mesh
9459            // falls back to a single `/` catch-all.
9460            let mut seen = std::collections::HashSet::new();
9461            // Route the per-entry value-shape gate's traversal head
9462            // through the lifted [`Entrada::paths`] slice accessor
9463            // rather than the raw `&e.paths` field access — the
9464            // per-Aplicacao `:entrada :paths` validate loop now keys
9465            // off the canonical raw-slot surface every downstream
9466            // per-`:entrada` path-list consumer (the sibling
9467            // [`Entrada::resolved_paths`] fallback-applying resolver
9468            // internal reads, `feira app graph`'s per-Aplicacao entrada
9469            // summary line's `{:?}` Debug print) routes through, so any
9470            // future rebrand on the typed slot's raw-slot reader lands
9471            // at exactly one place. Same convergence discipline as the
9472            // sibling [`Placement::clusters`] (a6e18d7) reader-site
9473            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
9474            // axis.
9475            for p in e.paths() {
9476                if p.is_empty() {
9477                    return Err(AplicacaoError::EntradaPathEmpty);
9478                }
9479                if !p.starts_with('/') {
9480                    return Err(AplicacaoError::entrada_path_not_absolute(p));
9481                }
9482                // Per-entry value-shape gate: the path lands verbatim
9483                // as a K8s Gateway API HTTPRoute `matches[].path.value`
9484                // (caixa-mesh/src/lib.rs:498), apiserver-validated
9485                // against `maxLength: 1024` + the Gateway API webhook's
9486                // path-grammar rules (no `//`, no `/./`, no `/../`, no
9487                // query/fragment separators, no whitespace, no control
9488                // characters, no non-ASCII bytes). Until this gate
9489                // landed `validate` only refused the empty string and
9490                // missing-leading-slash (eb3456d); a structurally
9491                // invalid path (`"/api?q=1"`, `"/api#frag"`,
9492                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
9493                // 1025-byte URL-shaped slug) silently passed validate
9494                // and the failure surfaced at `kubectl apply` time as
9495                // a Gateway API webhook rejection, far from the source
9496                // caixa.lisp, with no field naming the offending
9497                // `:paths` entry. Lifting the gate to caixa-build time
9498                // mirrors the `:entrada :host` value-shape trajectory
9499                // (c7d05ec) on the sibling axis — every author surface
9500                // that emits a Gateway API field now matches the
9501                // apiserver's accepted set at validate time.
9502                validate_entrada_path(p)?;
9503                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
9504                    AplicacaoError::entrada_path_duplicate(p)
9505                })?;
9506            }
9507        }
9508
9509        Ok(())
9510    }
9511
9512    /// Reject `:membros` values that are operationally meaningless. The
9513    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
9514    /// every entry names a Servico that participates in the Aplicacao,
9515    /// and the rendered programs.yaml fan-out emits one entry per
9516    /// `:membros`. Three authoring footguns are closed here:
9517    ///
9518    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
9519    ///     a `programs:` entry whose `name:` is the empty string, which
9520    ///     downstream `lareira-fleet-programs` rejects at template time
9521    ///     with a non-localized error;
9522    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
9523    ///     an empty semver constraint, so the failure surfaces far from
9524    ///     the source caixa.lisp;
9525    ///   - duplicate `:caixa` names — two entries with the same name
9526    ///     produce duplicate programs.yaml entries (one silently
9527    ///     overwrites the other in the cluster's HelmRelease values), and
9528    ///     contract membership lookups against `:contratos` collapse the
9529    ///     two onto one node, masking authoring mistakes.
9530    ///
9531    /// Same value-shape discipline as `:placement :clusters` (where empty
9532    /// + duplicate cluster names are rejected) and `:entrada :paths`
9533    /// (where empty + duplicate path entries are rejected). Lifting these
9534    /// invariants to the typed surface mirrors the MESH-COMPOSITION
9535    /// §III.3 promise that the `:membros` set — the load-bearing identity
9536    /// of the application graph — is well-formed by construction.
9537    fn validate_membros(&self) -> Result<(), AplicacaoError> {
9538        if self.membros().is_empty() {
9539            return Err(AplicacaoError::NoMembros);
9540        }
9541        let mut seen = std::collections::HashSet::new();
9542        for m in self.membros() {
9543            // Every emitted cluster artifact's `metadata.name` derives
9544            // from a `:membros :caixa` value verbatim — the rendered
9545            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
9546            // the [`crate::LABEL_PROGRAM`] label value on every CNP
9547            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
9548            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
9549            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
9550            // `metadata.name` when the member is the `:entrada :para`
9551            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
9552            // schema enforces the DNS-1123 label rule on admission;
9553            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
9554            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
9555            // mistaken-identity slug) silently passes the prior empty-/
9556            // duplicate-only gate and the failure surfaces at `kubectl
9557            // apply` time as a `metadata.name: Invalid value` rejection,
9558            // far from the source caixa.lisp, with no field naming the
9559            // offending `:membros` entry. Lifting the gate to caixa-build
9560            // time mirrors the `:entrada :host` value-shape trajectory
9561            // (c7d05ec) on the peer axis — every author surface that
9562            // emits a K8s name now matches the apiserver's accepted set
9563            // at validate time.
9564            validate_membro_caixa(m.nome())?;
9565            // The author surface for `:versao` is the same Cargo-shaped
9566            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
9567            // `"*"`) every `:deps` entry carries — and the lacre pipeline
9568            // resolves both axes through the same
9569            // [`crate::version::parse_requirement`] entry-point. The
9570            // shared [`crate::render::require_valid_versao_requirement`]
9571            // helper brackets the empty-first + parse cascade both peer
9572            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
9573            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
9574            // route through, so drift between the three axes' accepted
9575            // requirement sets is structurally impossible and the parse-
9576            // side no-op the empty-first arm closes (semver's empty
9577            // parse yields an implicit `*`) lives in exactly one
9578            // predicate.
9579            crate::render::require_valid_versao_requirement(
9580                m.versao_requirement(),
9581                || AplicacaoError::membro_versao_empty(m.nome()),
9582                |reason| {
9583                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
9584                },
9585            )?;
9586            crate::render::insert_first_seen(&mut seen, m.nome(), || {
9587                AplicacaoError::membro_duplicate(m.nome())
9588            })?;
9589        }
9590        Ok(())
9591    }
9592
9593    /// Reject `:placement` values that are operationally meaningless or
9594    /// internally contradictory. Each strategy variant has the same
9595    /// invariants on `:clusters` (non-empty list, non-empty unique
9596    /// entries) — the §III.1 author surface is uniform on this axis,
9597    /// even though the *meaning* of the list differs by strategy
9598    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
9599    /// shard pool).
9600    ///
9601    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
9602    /// are the same authoring footgun closed for `:politicas` zero
9603    /// values and `:entrada` empty paths: the field is *declared* but
9604    /// carries no meaning, so downstream renderers either skip it
9605    /// silently (cluster-fanout drops the empty entry, no diagnostic)
9606    /// or apply it literally and fail at admission time. Lifting both
9607    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
9608    /// violation is a build error" promise.
9609    ///
9610    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
9611    /// is required exactly when `:estrategia Sharded` (hash-keyed
9612    /// distribution, Akka cluster-sharding convention, §II.4) and
9613    /// refused on `:estrategia Replicated`/`SingleNode` (where no
9614    /// hash-keyed routing axis consumes it). The partition closes the
9615    /// "I think I configured sharding" footgun where an author writes
9616    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
9617    /// the typed slot's value silently vanishes at the renderer layer
9618    /// — every validated `Placement` past this call satisfies
9619    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
9620    fn validate_placement(&self) -> Result<(), AplicacaoError> {
9621        // Every strategy needs at least one named cluster: `Replicated`
9622        // and `SingleNode` use the list as hosting/takeover candidates
9623        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
9624        // §II.1), while `Sharded` uses it as the shard pool
9625        // (Akka cluster-sharding convention — §II.4). An empty list is
9626        // meaningless under any of the three.
9627        //
9628        // Route the paired pre-flight `.is_empty()` refusal probe and
9629        // the per-cluster validate loop's traversal head through the
9630        // lifted [`Placement::clusters`] slice-return accessor rather
9631        // than the raw `self.placement.clusters` field access — the
9632        // two production consumers of the per-`:placement` cluster-
9633        // pool `Vec`-carry now key off exactly one typed dispatch on
9634        // the substrate primitive, so any future rebrand on the axis
9635        // (a per-tenant cluster-pool overlay the operator pins through
9636        // a future `:placement :clusters-overrides` slot, a per-
9637        // Aplicacao dynamic cluster-pool derivation the future M5
9638        // adaptive-placement engine computes from `:affinity` weights)
9639        // migrates as a single caixa-core edit rather than a
9640        // coordinated rewrite of the paired arms — sibling of the
9641        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
9642        // arm migration on the per-`:supervisor` static-child-list
9643        // `Vec`-carry axis.
9644        //
9645        // Route the per-`:placement` outer-composite reference read
9646        // through the lifted [`AplicacaoSpec::placement`] outer accessor
9647        // rather than the raw `&self.placement` field access — the
9648        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
9649        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
9650        // axis-level lifted accessor family) now routes through the
9651        // substrate-primitive typed dispatch at the outer composition
9652        // altitude, the same shape the peer caixa-mesh
9653        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
9654        // and the sibling `feira app graph` per-Aplicacao print line
9655        // now key off after this accessor lift.
9656        let p = self.placement();
9657        if p.clusters().is_empty() {
9658            // Route the per-`:placement` empty-clusters diagnostic
9659            // through the substrate-primitive
9660            // [`AplicacaoError::placement_without_clusters`] ctor rather
9661            // than the pre-lift three-line open-coded
9662            // `AplicacaoError::PlacementWithoutClusters { estrategia:
9663            // p.estrategia() }` struct-literal — folds the sole in-crate
9664            // wire-up on this variant onto one dispatch matching the
9665            // sibling per-`:placement :clusters` dedup /
9666            // per-`:contratos` self-edge / per-`:upgrade-from :from`
9667            // duplicate substrate-primitive-projection ctors on the
9668            // same `AplicacaoError` / `UpgradeError` envelopes.
9669            return Err(AplicacaoError::placement_without_clusters(p));
9670        }
9671        let mut seen = std::collections::HashSet::new();
9672        for c in p.clusters() {
9673            // Per-entry value-shape gate: the cluster name lands in
9674            // every K8s context / `lareira-fleet-programs` aggregator
9675            // filter / future M4 CR materializer's per-cluster axis
9676            // a validated `:clusters` entry passes through, each
9677            // enforcing the DNS-1123 label rule on admission. Same
9678            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
9679            // on the peer name axis — both axes' validated values
9680            // are guaranteed-accepted by the apiserver without
9681            // re-validation at any downstream renderer or admission
9682            // layer.
9683            validate_placement_cluster(c)?;
9684            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
9685                // Route the per-`:placement :clusters` dedup diagnostic
9686                // through the substrate-primitive
9687                // [`AplicacaoError::placement_cluster_duplicate`] ctor
9688                // rather than the pre-lift three-line open-coded
9689                // `AplicacaoError::PlacementClusterDuplicate { cluster:
9690                // c.clone() }` struct-literal — folds the sole in-crate
9691                // wire-up on this variant onto one dispatch matching the
9692                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
9693                // per-`:politicas <scalar>` single-slot ctor families on
9694                // the same [`AplicacaoError`] envelope.
9695                AplicacaoError::placement_cluster_duplicate(c)
9696            })?;
9697        }
9698        // Route the per-`:placement :affinity` per-hint value-shape
9699        // gate through the typed [`Placement::affinity`] accessor rather
9700        // than the raw `&self.placement.affinity` field access — the
9701        // sole open-coded field-access site on the per-`:placement`
9702        // M3-Adaptive-compression-hint axis the accessor lift now owns.
9703        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
9704        // the accessor's `Option<&str>` return type;
9705        // [`validate_placement_affinity`]'s `&str` parameter accepts
9706        // the narrower borrow without a re-allocation, so the routing
9707        // change is byte-for-byte in the pass arm and remains
9708        // byte-for-byte in every failure diagnostic
9709        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
9710        // String` field is populated inside
9711        // [`validate_placement_affinity`] via the peer `.to_string()`
9712        // path on the same borrowed slice). Peer of the sibling
9713        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
9714        // routing through [`Placement::shard_key`] at the caixa-core
9715        // site above — extends the "read `:placement` optional-scalars
9716        // through the typed accessor" discipline to the second
9717        // `Option<String>`-shape slot on the M3 mesh-slot family.
9718        //
9719        // Per-hint value-shape gate: the `:affinity` value lands
9720        // verbatim in the M3 Adaptive compression overlay
9721        // (caixa-mesh's `placement.affinity` emission) and every
9722        // future M4 placement-engine routing axis keying off the
9723        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
9724        // selector — each enforces the DNS-1123 label rule on
9725        // admission. Same typed-shape trajectory as `:placement
9726        // :clusters` (6c8c00b) on the sibling slot and the four
9727        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
9728        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
9729        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
9730        // on the Aplicacao surface to land on the canonical
9731        // [`crate::render::is_dns_1123_label`] floor.
9732        if let Some(a) = p.affinity() {
9733            validate_placement_affinity(a)?;
9734        }
9735        match p.estrategia() {
9736            // Route the `Sharded`-arm shape-gate cascade through the
9737            // typed [`Placement::shard_key`] accessor rather than the
9738            // raw `&self.placement.shard_key` field access — one of the
9739            // two open-coded field-access sites on the per-`:placement`
9740            // Akka-cluster-sharding-key axis the accessor lift now
9741            // owns. The `Some(k)`-bound `k` narrows from `&String` to
9742            // `&str` under the accessor's `Option<&str>` return type;
9743            // `str::is_empty` and [`validate_placement_shard_key`]'s
9744            // `&str` parameter both accept the narrower borrow without
9745            // a re-allocation.
9746            PlacementStrategy::Sharded => match p.shard_key() {
9747                None => return Err(AplicacaoError::ShardedWithoutKey),
9748                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
9749                // Per-axis value-shape gate on the Akka-cluster-sharding
9750                // `:shard-key` extractor expression. The shape gate runs
9751                // after the more self-locating `ShardedKeyEmpty` arm so
9752                // a `:shard-key ""` surfaces the narrower empty
9753                // diagnostic first; every non-empty `:shard-key` past
9754                // this call is guaranteed to be a printable-ASCII
9755                // single-token reference the future M4 Akka-style
9756                // cluster-sharding reconciler can hash without
9757                // re-validating at the runtime layer. Mirrors the
9758                // payload-axis shape gates on the peer `:contratos`
9759                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
9760                // 63e18a0 / c4213a4) — each lifts the runtime parser's
9761                // intersection-floor to a caixa-build-time gate.
9762                Some(k) => validate_placement_shard_key(k)?,
9763            },
9764            // `:shard-key` is the Akka-cluster-sharding axis
9765            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
9766            // across the cluster pool. `Replicated` (active-active across
9767            // every named cluster) and `SingleNode` (Erlang/OTP
9768            // distributed-app takeover/failover, §II.1) have no hash-keyed
9769            // routing axis to consume the slot; downstream renderers
9770            // (caixa-mesh's `placement.shardKey` overlay at
9771            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
9772            // sharding reconciler) ignore `:shard-key` outside the
9773            // `Sharded` arm by construction. Until this gate landed an
9774            // author who wrote `:placement (:estrategia Replicated
9775            // :shard-key "tenantId")` (an off-by-one strategy typo, a
9776            // copy-paste from a Sharded sibling caixa, the "I think I
9777            // configured sharding" footgun) silently passed validate and
9778            // the typed slot's value vanished at the renderer layer with
9779            // no diagnostic — the canonical "declared-but-inert" footgun
9780            // the empty-:affinity / empty-shard-key / zero-:politicas /
9781            // empty-:contratos-target gates already close on every other
9782            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
9783            // Lifting the rejection to a build-time gate closes the
9784            // Sharded ↔ non-Sharded partition over the typed
9785            // `:placement` slot: every validated `Placement` past this
9786            // call has `shard_key.is_some()` iff `estrategia ==
9787            // Sharded`, structurally — the future Akka reconciler can
9788            // reach for `placement.shard_key` knowing it's `Some` exactly
9789            // when the strategy consumes it, without re-deriving the
9790            // partition from inline strategy probes.
9791            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
9792                // Route the non-`Sharded`-arm declared-but-inert refusal
9793                // through the typed [`Placement::shard_key`] accessor —
9794                // the second of the two open-coded field-access sites the
9795                // accessor lift now owns. The `Some(k)`-bound `k` narrows
9796                // from `&String` to `&str`; the `AplicacaoError::
9797                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
9798                // materializes the owned `String` via `k.to_string()`
9799                // (peer to the sibling per-Membro `String`-carry sites
9800                // 4127bb6 routed through `m.nome().to_string()` /
9801                // `m.versao_requirement().to_string()`), so the whole
9802                // `Sharded` ↔ non-`Sharded` partition on the
9803                // `:shard-key` axis now flows through the same typed
9804                // dispatch as the sibling `Sharded`-arm shape gate.
9805                if let Some(k) = p.shard_key() {
9806                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
9807                }
9808            }
9809        }
9810        Ok(())
9811    }
9812
9813    /// Reject `:politicas` values that are operationally meaningless.
9814    /// Each axis is optional — omitting it expresses "no policy on this
9815    /// axis". Carrying a *zero* value for a declared axis is the bug
9816    /// this function rejects: zero is either
9817    ///
9818    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
9819    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
9820    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
9821    ///     "every Aplicacao declares :politicas :timeout (no infinite
9822    ///     blocking)", or
9823    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
9824    ///     first call; a 0-rate rate-limit denies every request).
9825    ///
9826    /// Lifting these "0 means the opposite of what you think" idioms to
9827    /// the typed Aplicacao surface as build errors mirrors the §III.3
9828    /// promise that contract drift, capability leaks, and cycles are all
9829    /// build errors — not runtime surprises.
9830    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
9831        // Route the whole per-axis + cross-axis `:politicas` cascade
9832        // through the substrate primitive [`MeshPolicy::validate`],
9833        // which folds all six per-axis brackets (`:timeout`,
9834        // `:retries`, `:circuit-breaker :max-failures`,
9835        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
9836        // window-canonical-form) plus the compound cross-axis fold
9837        // [`MeshPolicy::first_cross_axis_violation`] into one
9838        // `Result<(), AplicacaoError>` return. The whole per-axis-
9839        // brackets + cross-axis-fold cascade collapses to one call, and
9840        // every future [`MeshPolicy`] consumer (the future M4
9841        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9842        // admission webhook, the per-`:contratos`-edge `:politicas`
9843        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
9844        // of which resolves an *effective* per-edge [`MeshPolicy`] and
9845        // must emit *the same* diagnostic on the same input as `feira
9846        // build`) reaches through the same substrate-primitive dispatch
9847        // rather than re-inlining the four-per-axis + one-cross-axis
9848        // cascade in lockstep with this validate gate. Same trajectory
9849        // the peer per-kind compound entry gates
9850        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
9851        // [`crate::render::require_supervisor_view`] (8d8a5c3),
9852        // [`crate::render::require_v0_servico_shape`] (per-Caixa
9853        // layout axis) and the sibling compound cross-axis fold
9854        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
9855        // extended here onto the per-slot compound entry gate that
9856        // folds both per-axis + cross-axis surfaces on the M3
9857        // mesh-slot family.
9858        self.politicas().validate()
9859    }
9860
9861    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
9862    /// A synchronous edge is any contract whose typed [`WitTarget`] is
9863    /// `Http`, `Store`, or `Capability` — the caller blocks on the
9864    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
9865    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
9866    /// block on its subscribers, so they can never close a sync loop.
9867    ///
9868    /// Iterative DFS with three-coloring; the reported cycle is the
9869    /// path of caixa names traversed from the back-edge target around
9870    /// to itself, in declaration order. Adjacency lists and DFS roots
9871    /// are visited in `BTreeMap` key order so the diagnostic is
9872    /// deterministic across runs.
9873    ///
9874    /// Now the cross-edge axis of the per-slot compound gate
9875    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
9876    /// the per-entry cascade rather than at the outer
9877    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
9878    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
9879    /// sync-cycle) reach every consumer through one call. Kept
9880    /// standalone (rather than inlined) so consumers that want only the
9881    /// cross-edge axis (the M4 per-edge policy resolver
9882    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
9883    /// mutates one `:contratos` entry and needs to re-probe *just* the
9884    /// cycle invariant against the post-patch adjacency without
9885    /// re-running the per-entry shape/membership/dedup cascade the
9886    /// per-entry-only [M4 admission] fast path already covered) still
9887    /// have a self-contained entry point on the cycle axis.
9888    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
9889        use std::collections::{BTreeMap, BTreeSet};
9890
9891        #[derive(Clone, Copy, PartialEq, Eq)]
9892        enum Mark {
9893            White,
9894            Gray,
9895            Black,
9896        }
9897
9898        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
9899        for m in self.membros() {
9900            adj.entry(m.nome()).or_default();
9901        }
9902        for c in self.contratos() {
9903            // target() was already called by validate(); re-running here
9904            // keeps detect_sync_cycles self-contained for callers that
9905            // reuse it (M4 per-edge policy resolver) without revalidating.
9906            //
9907            // The pub-sub-arm check routes through the lifted
9908            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
9909            // arm-discriminator predicate rather than a raw `matches!(…,
9910            // WitTarget::PubSub { .. })` on the variant so a future
9911            // rebrand on the axis (an M4 per-edge WIT registry split of
9912            // [`WitTarget::PubSub`] into shape-specific peers, a
9913            // per-consumer rename that the accept-set already carries)
9914            // reaches this call site through the derive rather than a
9915            // scattered per-arm `matches!` rewrite — same
9916            // `IsVariant`-derived-arm-discriminator discipline the
9917            // peer closed-set typed enums ([`crate::CaixaKind`] via
9918            // f5bba80, [`PlacementStrategy`] via 766ec63,
9919            // [`crate::supervisor::RestartStrategy`] +
9920            // [`crate::supervisor::RestartPolicy`],
9921            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
9922            // already route through on the substrate's other typed-enum
9923            // arm-discriminator axes.
9924            if c.target()?.is_pubsub() {
9925                continue;
9926            }
9927            adj.entry(c.source()).or_default().insert(c.destination());
9928        }
9929
9930        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
9931        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
9932
9933        // Stable DFS root order — BTreeMap iteration is sorted by key.
9934        let roots: Vec<&str> = adj.keys().copied().collect();
9935
9936        // Frame: (node, sorted-neighbours snapshot, next-edge index).
9937        for root in roots {
9938            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
9939                continue;
9940            }
9941            let root_neighbors: Vec<&str> = adj
9942                .get(root)
9943                .map(|s| s.iter().copied().collect())
9944                .unwrap_or_default();
9945            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
9946            color.insert(root, Mark::Gray);
9947
9948            loop {
9949                // Read+advance the top frame in one borrow scope so we
9950                // can later mutate the stack (push/pop) without holding
9951                // a borrow across.
9952                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
9953                    let node = top.0;
9954                    if top.2 >= top.1.len() {
9955                        (node, None)
9956                    } else {
9957                        let nxt = top.1[top.2];
9958                        top.2 += 1;
9959                        (node, Some(nxt))
9960                    }
9961                });
9962                let Some((node, nxt_opt)) = step else { break };
9963                let Some(nxt) = nxt_opt else {
9964                    color.insert(node, Mark::Black);
9965                    stack.pop();
9966                    continue;
9967                };
9968                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
9969                match nxt_color {
9970                    Mark::Gray => {
9971                        // Reconstruct the cycle from `node` back through
9972                        // the parent chain to `nxt`, then close.
9973                        let mut cycle = Vec::new();
9974                        let mut cur = node;
9975                        cycle.push(cur.to_string());
9976                        while cur != nxt {
9977                            match parent.get(cur).copied() {
9978                                Some(p) => {
9979                                    cur = p;
9980                                    cycle.push(cur.to_string());
9981                                }
9982                                None => break,
9983                            }
9984                        }
9985                        cycle.reverse();
9986                        cycle.push(nxt.to_string());
9987                        return Err(AplicacaoError::contrato_cycle(cycle));
9988                    }
9989                    Mark::White => {
9990                        parent.insert(nxt, node);
9991                        color.insert(nxt, Mark::Gray);
9992                        let nxt_neighbors: Vec<&str> = adj
9993                            .get(nxt)
9994                            .map(|s| s.iter().copied().collect())
9995                            .unwrap_or_default();
9996                        stack.push((nxt, nxt_neighbors, 0));
9997                    }
9998                    Mark::Black => {}
9999                }
10000            }
10001        }
10002        Ok(())
10003    }
10004
10005    /// Substrate-canonical destination-facing TCP port every emitted
10006    /// per-Aplicacao artifact must key `destination`-shaped port axes
10007    /// off. Returns the typed `:entrada :port` scalar when this
10008    /// Aplicacao's `:entrada` block names `destination` under its
10009    /// `:para` axis (the destination Servico *is* the ingress apex, so
10010    /// the substrate honors the author-declared listener port
10011    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
10012    /// fallback otherwise (every non-apex destination — the internal
10013    /// mesh Servicos `:contratos` reach across, the future per-edge
10014    /// policy resolver's per-destination probe targets, the
10015    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
10016    /// L4 port resolver — reads the same substrate-canonical port floor
10017    /// by construction).
10018    ///
10019    /// Prior to this lift the "if :entrada matches this destination use
10020    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
10021    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
10022    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
10023    /// prior to this lift), with no typed method on the substrate primitive
10024    /// that named the rule. A future per-destination port axis addition
10025    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
10026    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
10027    /// per-Servico listener ports land, a per-cluster override the operator
10028    /// pins through a future `:placement :default-port` slot — would have
10029    /// to be threaded through every renderer's inline cascade in lockstep
10030    /// or one consumer would silently disagree on which port a given
10031    /// destination Servico's ingress lands at. Lifting the rule to a
10032    /// typed method on the substrate primitive means the M4 CR
10033    /// materializer, the future per-edge policy resolver, and every
10034    /// downstream test-fixture navigator reach for exactly one typed
10035    /// dispatch — the resolver's accept-set moves as a unit on any
10036    /// future axis addition.
10037    ///
10038    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
10039    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
10040    /// the typed primitive, thin projections at each consumer"
10041    /// discipline lifts on the sibling `:contratos` payload / `:politicas
10042    /// :rate-limit` unit-suffix axes; extends the discipline onto the
10043    /// destination-facing port-resolution axis every per-Aplicacao
10044    /// L4-fallback renderer consumes.
10045    #[must_use]
10046    pub fn port_for_destination(&self, destination: &str) -> u16 {
10047        // Route the per-`:entrada` composite-reference read through
10048        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
10049        // the raw `self.entrada.as_ref()` field access — the
10050        // per-destination L4-port fallback resolver's composite-
10051        // projection seed is now the canonical read-side surface
10052        // every per-Aplicacao entrada consumer routes through, peer
10053        // of the sibling `validate` per-`:entrada` shape-and-
10054        // membership gate migration on the same outer-composite
10055        // axis.
10056        // Route the per-`:entrada` apex-destination membership probe
10057        // through the lifted [`Entrada::destination`] accessor rather
10058        // than the raw `e.para == destination` field access — the last
10059        // un-lifted `.para` production-code read site on the per-
10060        // `:entrada` `:para` axis, sibling to the four caixa-core
10061        // consumer sites the peer 15ddd8c converge already routed
10062        // through the accessor (the three
10063        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
10064        // membership gate sites: the `validate_entrada_para` DNS-1123
10065        // shape gate, the per-`:membros` membership lookup, and the
10066        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
10067        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
10068        // `entrada.para`-projection converge at
10069        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
10070        // route-name projection site). Prior to this converge the
10071        // `port_for_destination` resolver was the solitary consumer
10072        // bypassing the typed dispatch on the `.para` axis — the two
10073        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
10074        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
10075        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
10076        // reach through the same accessor family compose with this
10077        // resolver at the emit boundary via the apex-identity
10078        // invariant `spec.port_for_destination(entrada.destination())
10079        // == entrada.port` the sibling
10080        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
10081        // pin pins across four permutations. A future extension of the
10082        // `:entrada :para` axis to a richer author surface (a per-
10083        // cluster alias overlay the operator pins through a future
10084        // `:placement`-scoped slot, a namespace-qualified rewrite the
10085        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
10086        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
10087        // §III.2 acknowledges) that lands on the accessor would silently
10088        // disagree between this resolver and the two `caixa-mesh` emit
10089        // sites — an author-declared `:para "cart"` value the accessor
10090        // rewrote to `"cart-v2"` under a future canary arm would leave
10091        // the resolver's membership arm falling through to
10092        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
10093        // `.para`) while the peer emit-site consumers landed on the
10094        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
10095        // silently disagreed on which destination port a given typed
10096        // `:entrada` resolves to at cluster-apply time. Pinned by the
10097        // drift-detection test
10098        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
10099        // below.
10100        self.entrada()
10101            .filter(|e| e.destination() == destination)
10102            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
10103    }
10104}
10105
10106/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
10107/// entry may name the Aplicacao's own `:nome`.
10108///
10109/// An Aplicacao that lists itself as a member is a degenerate self-edge in
10110/// the typed graph — the application graph is a DAG rooted at the Aplicacao
10111/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
10112/// Servicos that compose the app; an Aplicacao is never its own constituent),
10113/// and the lacre pipeline's closure-resolution would otherwise be handed a
10114/// node that is its own parent: a one-node cycle it either rejects far from
10115/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
10116/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
10117/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
10118/// label + lacre closure root), a member whose `:caixa` equals the
10119/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
10120/// peer.
10121///
10122/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
10123/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
10124/// gate `validate_upgrade_from_against_versao` and the supervision-tree
10125/// self-parent gate `crate::supervisor::validate_no_self_supervision`
10126/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
10127/// not a tree/mesh edge" discipline, here on the second typed-graph axis
10128/// (the Aplicacao :membros set; the supervision-tree :children list was the
10129/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
10130/// every validated Supervisor's children are distinct from its `:nome`,
10131/// every validated Aplicacao's membros are distinct from its `:nome`. The
10132/// transitive consequence is that `:entrada :para` and `:contratos`
10133/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
10134/// name the Aplicacao itself, without re-deriving the partition.
10135pub fn validate_no_self_membership(
10136    membros: &[Membro],
10137    parent_nome: &str,
10138) -> Result<(), AplicacaoError> {
10139    for m in membros {
10140        if m.nome() == parent_nome {
10141            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
10142        }
10143    }
10144    Ok(())
10145}
10146
10147#[derive(Debug, Error, PartialEq, Eq)]
10148pub enum AplicacaoError {
10149    #[error("Aplicacao must declare at least one :membros entry")]
10150    NoMembros,
10151    #[error(
10152        ":membros entry has empty :caixa (every member must name a Servico; \
10153         omit the entry instead of carrying an empty name)"
10154    )]
10155    MembroCaixaEmpty,
10156    #[error(
10157        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
10158         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
10159         name / label value the member name lands in; use a lowercase \
10160         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
10161    )]
10162    MembroCaixaInvalid { caixa: String, reason: String },
10163    #[error(
10164        ":membros entry {caixa:?} has empty :versao (every member must pin a \
10165         semver constraint that resolves through the lacre pipeline)"
10166    )]
10167    MembroVersaoEmpty { caixa: String },
10168    #[error(
10169        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
10170         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
10171         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
10172         carries; the lacre pipeline resolves both through the same parser)"
10173    )]
10174    MembroVersaoInvalid {
10175        caixa: String,
10176        versao: String,
10177        reason: String,
10178    },
10179    #[error(
10180        ":membros entry {caixa:?} appears more than once (the graph node set \
10181         is a set, not a multiset; duplicate members produce duplicate \
10182         programs.yaml entries and ambiguous :contratos membership lookups)"
10183    )]
10184    MembroDuplicate { caixa: String },
10185    #[error(
10186        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
10187         never its own constituent Servico (the application graph is a DAG rooted \
10188         at the Aplicacao; :membros names the *other* caixas that compose the \
10189         app, not the app itself). Since every :nome is a globally-unique \
10190         substrate identity, a member naming the Aplicacao's own :nome is a \
10191         one-node lacre-closure recursion, not a coincidentally-named peer; \
10192         drop the self-referential :membros entry or rename it to the actual \
10193         constituent caixa."
10194    )]
10195    MembroIsSelfAplicacao { caixa: String },
10196    #[error(
10197        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
10198         caixa declared in :membros; omit the contract or fill the {slot} field with a \
10199         member name)"
10200    )]
10201    ContratoCaixaEmpty { slot: &'static str },
10202    #[error(
10203        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
10204         :contratos {slot} value names a member of :membros, which is itself a \
10205         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
10206         object the member name lands in — Service, Pod, identity-based Cilium \
10207         selector; use a lowercase alphanumeric + hyphen identifier like \
10208         `\"checkout\"` or `\"cart-v2\"`)"
10209    )]
10210    ContratoCaixaInvalid {
10211        slot: &'static str,
10212        caixa: String,
10213        reason: String,
10214    },
10215    #[error("contrato references caixa {caixa:?} not declared in :membros")]
10216    ContratoMemberMissing { caixa: String },
10217    #[error(
10218        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
10219         entry is an inter-Servico contract whose :de and :para must name distinct \
10220         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
10221         the contract, or point :para at the member it actually calls)"
10222    )]
10223    ContratoSelfLoop { caixa: String, wit: String },
10224    #[error("contrato {de:?} → {para:?} has empty :wit")]
10225    EmptyWit { de: String, para: String },
10226    #[error(
10227        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
10228         {reason} (the substrate dispatches `:wit` values on the canonical \
10229         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
10230         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
10231         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
10232         kebab-case identifier per segment)"
10233    )]
10234    ContratoWitInvalid {
10235        de: String,
10236        para: String,
10237        wit: String,
10238        reason: String,
10239    },
10240    #[error(
10241        ":entrada :para is empty (every :entrada must route to a caixa declared in \
10242         :membros; fill the :para field with a member name)"
10243    )]
10244    EntradaParaEmpty,
10245    #[error(
10246        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
10247         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
10248         label per the K8s apiserver's `metadata.name` rule on every object the \
10249         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
10250         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
10251         `\"checkout\"` or `\"cart-v2\"`)"
10252    )]
10253    EntradaParaInvalid { para: String, reason: String },
10254    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
10255    EntradaMemberMissing { para: String },
10256    #[error(":entrada must declare a non-empty :host")]
10257    EmptyEntradaHost,
10258    #[error(
10259        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
10260         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
10261         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
10262         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
10263    )]
10264    EntradaHostInvalid { host: String, reason: String },
10265    #[error(":entrada :port must be in 1..=65535, got 0")]
10266    EntradaPortZero,
10267    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
10268    EntradaPathEmpty,
10269    #[error(
10270        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
10271    )]
10272    EntradaPathNotAbsolute { path: String },
10273    #[error(
10274        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
10275         value: {reason} (the K8s apiserver enforces the same shape on \
10276         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
10277         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
10278         requires percent-encoding `%XX` for non-ASCII and whitespace)"
10279    )]
10280    EntradaPathInvalid { path: String, reason: String },
10281    #[error(":entrada :paths entry {path:?} appears more than once")]
10282    EntradaPathDuplicate { path: String },
10283    #[error(
10284        ":placement {estrategia} requires at least one :clusters entry \
10285         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
10286    )]
10287    PlacementWithoutClusters { estrategia: PlacementStrategy },
10288    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
10289    PlacementClusterEmpty,
10290    #[error(
10291        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
10292         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
10293         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
10294         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
10295         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
10296         identifier like `\"rio\"` or `\"mar-east\"`)"
10297    )]
10298    PlacementClusterInvalid { cluster: String, reason: String },
10299    #[error(":placement :clusters entry {cluster:?} appears more than once")]
10300    PlacementClusterDuplicate { cluster: String },
10301    #[error(
10302        ":placement :affinity must be non-empty when set (omit :affinity to express \
10303         `no placement hint`)"
10304    )]
10305    PlacementAffinityEmpty,
10306    #[error(
10307        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
10308         (placement hints land verbatim in the M3 Adaptive compression overlay's \
10309         `placement.affinity` field and in every future M4 placement-engine routing \
10310         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
10311         selector — both enforce the DNS-1123 label rule on admission; use a \
10312         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
10313         `\"low-latency\"`, or `\"anti-affinity\"`)"
10314    )]
10315    PlacementAffinityInvalid { affinity: String, reason: String },
10316    #[error(":placement Sharded requires :shard-key")]
10317    ShardedWithoutKey,
10318    #[error(
10319        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
10320         hashes every entity onto the same shard, defeating sharding entirely)"
10321    )]
10322    ShardedKeyEmpty,
10323    #[error(
10324        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
10325         entity-id extractor expression: {reason} (the future M4 Akka-style \
10326         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
10327         as a single-token property reference and hashes the extracted entity ID \
10328         to compute shard placement; use a printable-ASCII extractor expression \
10329         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
10330         `\"${{tenant}}\"`)"
10331    )]
10332    ShardKeyInvalid { shard_key: String, reason: String },
10333    #[error(
10334        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
10335         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
10336         convention); :estrategia Replicated runs every cluster active-active and \
10337         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
10338         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
10339         to :estrategia Sharded if hash-keyed routing is the intent"
10340    )]
10341    ShardKeyOnNonSharded {
10342        estrategia: PlacementStrategy,
10343        shard_key: String,
10344    },
10345    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
10346    ContratoMissingTarget {
10347        de: String,
10348        para: String,
10349        wit: String,
10350        expected: &'static str,
10351    },
10352    #[error(
10353        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
10354         expected `:{expected}` only"
10355    )]
10356    ContratoWrongTarget {
10357        de: String,
10358        para: String,
10359        wit: String,
10360        expected: &'static str,
10361    },
10362    #[error(
10363        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
10364         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
10365         that matches no traffic and silently drops every request)"
10366    )]
10367    ContratoEndpointEmpty { de: String, para: String },
10368    #[error(
10369        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
10370         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
10371         :entrada :paths)"
10372    )]
10373    ContratoEndpointNotAbsolute {
10374        de: String,
10375        para: String,
10376        endpoint: String,
10377    },
10378    #[error(
10379        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
10380         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
10381         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
10382         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
10383         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
10384         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
10385         and whitespace)"
10386    )]
10387    ContratoEndpointInvalid {
10388        de: String,
10389        para: String,
10390        endpoint: String,
10391        reason: String,
10392    },
10393    #[error(
10394        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
10395         subject is a no-op subscribe; omit :subject only if the WIT world is not \
10396         pub-sub-shaped)"
10397    )]
10398    ContratoSubjectEmpty { de: String, para: String },
10399    #[error(
10400        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
10401         NATS subject: {reason} (the NATS server's subject parser enforces the \
10402         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
10403         single-token and `>` multi-token wildcards — at publish/subscribe time; \
10404         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
10405         `\"orders.*.completed\"` — a malformed subject silently drops every \
10406         message at runtime far from the source caixa.lisp)"
10407    )]
10408    ContratoSubjectInvalid {
10409        de: String,
10410        para: String,
10411        subject: String,
10412        reason: String,
10413    },
10414    #[error(
10415        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
10416         addresses the bucket root, defeating the per-key isolation the slot exists \
10417         for; omit :slot only if the WIT world is not store-shaped)"
10418    )]
10419    ContratoSlotEmpty { de: String, para: String },
10420    #[error(
10421        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
10422         WASI keyvalue store slot template: {reason} (the substrate enforces \
10423         the printable-ASCII intersection-floor every kv backend admits — \
10424         use a single-token path / template expression like `\"checkout/$orderId\"`, \
10425         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
10426         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
10427         slot either gets rejected on write by strict backends or silently \
10428         corrupts the next read on permissive ones, far from the source caixa.lisp)"
10429    )]
10430    ContratoSlotInvalid {
10431        de: String,
10432        para: String,
10433        slot: String,
10434        reason: String,
10435    },
10436    #[error(
10437        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
10438         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
10439        cycle.join(" → ")
10440    )]
10441    ContratoCycle { cycle: Vec<String> },
10442    #[error(
10443        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
10444         than once (the typed graph edges are a set, not a multiset; duplicate \
10445         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
10446         values that K8s admission rejects far from the source caixa.lisp)"
10447    )]
10448    ContratoDuplicate {
10449        de: String,
10450        para: String,
10451        wit: String,
10452        target: String,
10453    },
10454    #[error(
10455        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
10456         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
10457         express `no per-call deadline on this axis`"
10458    )]
10459    PolicyTimeoutZero,
10460    #[error(
10461        ":politicas :retries must be > 0 when set; omit :retries to express \
10462         `no retries on transient failure`"
10463    )]
10464    PolicyRetriesZero,
10465    #[error(
10466        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
10467         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
10468         retry policy into a thundering-herd amplification vector on transient \
10469         failure (one caller request fans out to `(retries+1)^depth` server-side \
10470         calls across the synchronous-:contratos subgraph), exactly the failure \
10471         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
10472         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
10473         or omit :retries to disable retries entirely"
10474    )]
10475    PolicyRetriesExceedsCap { retries: u32 },
10476    #[error(
10477        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
10478         breaker trips on the first call); omit :circuit-breaker to disable it"
10479    )]
10480    PolicyBreakerZeroFailures,
10481    #[error(
10482        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
10483         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
10484         above this cap turns the typed breaker policy into a no-op: the trip \
10485         threshold is structurally so high that no realistic failures-per-:window \
10486         traffic shape can reach it, so the breaker never trips and every typed-slot \
10487         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
10488         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
10489         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
10490         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
10491         omit :circuit-breaker to disable the breaker entirely"
10492    )]
10493    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10494    #[error(
10495        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
10496         tracks no failures); omit :circuit-breaker to disable it"
10497    )]
10498    PolicyBreakerZeroWindow,
10499    #[error(
10500        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
10501         request); omit :rate-limit to disable rate limiting"
10502    )]
10503    PolicyRateLimitZero,
10504    #[error(
10505        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
10506         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
10507         rate-limit policy into a no-op limiter: the token-bucket capacity is \
10508         structurally so high that no realistic per-edge traffic shape can drain it, \
10509         so the limiter never trips and every typed-slot consumer (the future \
10510         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10511         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
10512         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
10513         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
10514         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
10515         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
10516         to disable rate limiting entirely"
10517    )]
10518    PolicyRateLimitExceedsCap { rate: u32 },
10519    #[error(
10520        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
10521         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
10522         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
10523         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
10524         three canonical windows)"
10525    )]
10526    PolicyRateLimitWindowNotCanonical { window: Duration },
10527    #[error(
10528        ":politicas :timeout must be an integer number of milliseconds — the canonical \
10529         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
10530         duration codec round-trips losslessly; got {timeout:?} which carries a \
10531         sub-millisecond residue that either truncates to a different `Duration` on \
10532         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
10533         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
10534         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
10535         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
10536    )]
10537    PolicyTimeoutNotCanonical { timeout: Duration },
10538    #[error(
10539        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
10540         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
10541         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
10542         overlays carry a deadline so long no realistic synchronous-:contratos \
10543         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
10544         CSE invariant degenerates to enforcement only at the per-Servico \
10545         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
10546         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
10547         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
10548         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
10549         maxes out at the same `3600s` ceiling) or omit :timeout to express \
10550         `no per-call deadline on this axis` (the synchronous-call deadline then \
10551         relies entirely on the per-Servico `:limits :wall-clock` axis)"
10552    )]
10553    PolicyTimeoutExceedsCap { timeout: Duration },
10554    #[error(
10555        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
10556         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
10557         the shared duration codec round-trips losslessly; got {window:?} which carries a \
10558         sub-millisecond residue that either truncates to a different `Duration` on \
10559         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
10560         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
10561    )]
10562    PolicyBreakerWindowNotCanonical { window: Duration },
10563    #[error(
10564        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
10565         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
10566         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
10567         is structurally so long that transient failures are never forgotten, the breaker \
10568         trips once and stays tripped for the lifetime of the component, and every typed-slot \
10569         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10570         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
10571         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
10572         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
10573         the breaker entirely"
10574    )]
10575    PolicyBreakerWindowExceedsCap { window: Duration },
10576    #[error(
10577        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
10578         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
10579         a single timing-out call can be declared failed, so the dominant failure mode \
10580         the breaker exists to catch is structurally never counted: a call dispatched at \
10581         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
10582         open at dispatch has already rolled, and every typed-slot consumer (the future \
10583         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10584         outlier_detection.interval paired against the per-route request timeout) emits a \
10585         breaker that cannot trip on timeouts however high the call volume. Pin :window \
10586         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
10587         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
10588         same shape), lower :timeout, or omit one of the two axes"
10589    )]
10590    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
10591    #[error(
10592        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
10593         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
10594         :window ({cb_window:?}) — the token-bucket dispatches at most \
10595         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
10596         structurally below the trip threshold, so the breaker cannot trip even under \
10597         100% failure and every typed-slot consumer (the future \
10598         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10599         outlier_detection.consecutive_5xx paired against \
10600         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
10601         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
10602         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
10603    )]
10604    PolicyBreakerCannotTripUnderRateLimit {
10605        rate: u32,
10606        rl_window: Duration,
10607        max_failures: u32,
10608        cb_window: Duration,
10609    },
10610    #[error(
10611        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
10612         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
10613         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
10614         at or before the last retry, so the breaker opens with declared retries still \
10615         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
10616         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
10617         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
10618         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
10619         Envoy / resilience4j production playbooks recommend the breaker's trip \
10620         threshold be observably larger than any single client's retry budget so the \
10621         breaker distinguishes one persistently-failing client from sustained \
10622         multi-client failure), lower :retries, or omit one of the two axes"
10623    )]
10624    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
10625    #[error(
10626        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
10627         ({retries}) plus the initial attempt — one client's declared retry sequence is \
10628         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
10629         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
10630         retry policy is silently truncated by the same rate limiter it feeds through and \
10631         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
10632         overlay, Envoy's retry_policy.num_retries paired against \
10633         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
10634         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
10635         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
10636         bucket capacity be observably larger than any single client's retry budget so the \
10637         limiter distinguishes one client's declared retries from sustained multi-client \
10638         load), lower :retries, or omit one of the two axes"
10639    )]
10640    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
10641}
10642
10643// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
10644// ctor `entrada_host_invalid` is folded onto the sibling
10645// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
10646// `{ <field>: String, reason: String }` variants
10647// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
10648// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
10649// `ShardKeyInvalid`), so every variant on the uniform two-slot
10650// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
10651// reads through one substrate-primitive family rather than one macro
10652// closing six sites plus a hand-written seventh ctor closing the
10653// paired site alone. Prior separate-ctor rationale (17dd504) migrates
10654// verbatim to the macro's outer doc block.
10655
10656// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
10657// wit, expected }` wire-up sites at [`WitContract::target`] onto one
10658// substrate-primitive family per typed variant — the paired sibling on
10659// [`AplicacaoError`] of the four `LayoutError` constructor families
10660// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
10661// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
10662// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
10663// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
10664// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
10665// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
10666// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
10667// HTTP with subject/slot, PubSub with endpoint/slot, Store with
10668// endpoint/subject, Capability with any payload; three
10669// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
10670// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
10671// opened the identical six-line
10672// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
10673// WitTarget::<label> }` struct-literal against the local `edge()` closure
10674// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
10675// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
10676// on the same altitude the peer four `LayoutError` constructor families
10677// each closed on their sibling envelopes.
10678//
10679// The macro below generates one `#[must_use]` inherent constructor per
10680// variant of shape `fn <ctor>(edge: (String, String, String), expected:
10681// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
10682// dispatch per arm: `return
10683// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
10684// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
10685// the pre-lift struct-literal on the same edge fixture. The uniform four-
10686// field construction (`de, para, wit` triple-destructure onto same-named
10687// fields + `expected` verbatim) is spelled once — inside the macro —
10688// rather than at every wire-up site. `#[must_use]` fires a compile warning
10689// at any wire-up that mistakenly discards the constructed error.
10690//
10691// Every future consumer that wants to construct one of these two variants
10692// outside [`WitContract::target`] (a deferred
10693// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10694// admission validator raising wrong-target / missing-target diagnostics
10695// on unrecognized shapes, a future `feira validate --contratos` per-caixa
10696// admission verb, a per-`WitContract` payload-axis pre-emitter probing
10697// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
10698// slots) reaches the variant through one call rather than re-inlining the
10699// six-line struct-literal block in lockstep with the seven in-crate
10700// wire-up sites.
10701macro_rules! contrato_target_ctors {
10702    ($($ctor:ident => $variant:ident),* $(,)?) => {
10703        impl AplicacaoError {
10704            $(
10705                #[doc = concat!(
10706                    "Construct an [`AplicacaoError::",
10707                    stringify!($variant),
10708                    "`] naming the offending edge `(de, para, wit)` triple ",
10709                    "under the given `expected` payload-field-name label. ",
10710                    "Folds the uniform `{ de, para, wit, expected }` four-",
10711                    "slot struct-literal onto one substrate primitive so ",
10712                    "every [`WitContract::target`] wire-up on this variant ",
10713                    "reads through one dispatch rather than the pre-lift ",
10714                    "six-line open-coded block. The `edge` triple threads ",
10715                    "verbatim from [`WitContract::edge_triple`] via the ",
10716                    "local `edge()` closure at the call site."
10717                )]
10718                #[must_use]
10719                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
10720                    let (de, para, wit) = edge;
10721                    Self::$variant { de, para, wit, expected }
10722                }
10723            )*
10724        }
10725    };
10726}
10727
10728contrato_target_ctors! {
10729    contrato_wrong_target => ContratoWrongTarget,
10730    contrato_missing_target => ContratoMissingTarget,
10731}
10732
10733// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
10734// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
10735// onto one substrate-primitive family per typed variant — the paired
10736// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
10737// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
10738// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
10739// `ContratoMissingTarget`) and of the two-slot
10740// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
10741// on the sibling per-`:entrada :host` envelope. Every one of the four
10742// wire-up sites — three under [`WitContract::target`] (the empty
10743// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
10744// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
10745// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
10746// value-shape gate fires ahead of) — opened the identical two-line
10747// `let (de, para) = <contract>.edge_pair(); return Err(
10748// AplicacaoError::<Variant> { de, para });` block against the local
10749// [`WitContract::edge_pair`] composite-projection accessor, the exact
10750// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
10751// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
10752// and [`AplicacaoError::entrada_host_invalid`] each closed on their
10753// sibling envelopes.
10754//
10755// The macro below generates one `#[must_use]` inherent constructor per
10756// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
10757// collapsing the four sites onto one dispatch per arm:
10758// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
10759// equal to the pre-lift struct-literal on the same edge pair. The
10760// uniform two-field construction (`de, para` pair-destructure onto
10761// same-named fields) is spelled once — inside the macro — rather than
10762// at every wire-up site. `#[must_use]` fires a compile warning at any
10763// wire-up that mistakenly discards the constructed error.
10764//
10765// Every future consumer that wants to construct one of these four
10766// variants outside the two in-crate wire-up sites (a deferred
10767// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10768// admission validator raising empty-payload / empty-`:wit` diagnostics,
10769// a future `feira validate --contratos` per-caixa admission verb, an
10770// M4 typed WIT-registry-driven per-arm pre-emitter probing the
10771// [`WitContract`] payload slot against a canonical per-arm requirement
10772// table) reaches the variant through one call rather than re-inlining
10773// the two-line pair-destructure block in lockstep with the four
10774// in-crate wire-up sites.
10775macro_rules! contrato_empty_pair_ctors {
10776    ($($ctor:ident => $variant:ident),* $(,)?) => {
10777        impl AplicacaoError {
10778            $(
10779                #[doc = concat!(
10780                    "Construct an [`AplicacaoError::",
10781                    stringify!($variant),
10782                    "`] naming the offending edge `(de, para)` pair. ",
10783                    "Folds the uniform `{ de, para }` two-slot struct-",
10784                    "literal onto one substrate primitive so every ",
10785                    "wire-up on this variant reads through one dispatch ",
10786                    "rather than the pre-lift two-line open-coded ",
10787                    "`let (de, para) = <contract>.edge_pair(); return ",
10788                    "Err(<Variant> { de, para });` block. The `edge` ",
10789                    "pair threads verbatim from [`WitContract::edge_pair`] ",
10790                    "at the call site."
10791                )]
10792                #[must_use]
10793                pub fn $ctor(edge: (String, String)) -> Self {
10794                    let (de, para) = edge;
10795                    Self::$variant { de, para }
10796                }
10797            )*
10798        }
10799    };
10800}
10801
10802contrato_empty_pair_ctors! {
10803    empty_wit => EmptyWit,
10804    contrato_endpoint_empty => ContratoEndpointEmpty,
10805    contrato_subject_empty => ContratoSubjectEmpty,
10806    contrato_slot_empty => ContratoSlotEmpty,
10807}
10808
10809// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
10810// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
10811// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
10812// onto one substrate primitive on [`AplicacaoError`] — sibling on the
10813// `{ de: String, para: String, <field>: String }` three-slot envelope of
10814// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
10815// variants on the paired `{ de, para }` two-slot envelope carrying the
10816// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
10817// { de, para });` pair-destructure prelude), the peer four-slot
10818// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
10819// the paired `{ de, para, <field>: String, reason: String }` envelope
10820// carrying the parser-shaped `reason` trailer), and the peer four-slot
10821// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
10822// `{ de, para, wit, expected: &'static str }` envelope carrying the
10823// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
10824// variant is the sole occupant of the three-slot `{ de, para, <field>:
10825// String }` shape on [`AplicacaoError`] (no sibling
10826// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
10827// and `:slot` axes carry no "must start with /" invariant, since the
10828// NATS subject grammar and the WASI keyvalue slot template grammar don't
10829// share the Gateway-API-HTTPPathMatch leading-slash prelude the
10830// `:endpoint` axis does), so a full macro isn't warranted; a single
10831// `#[must_use]` inherent ctor matching the ambient
10832// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
10833// peer per-`:contratos` ctor families each carry closes the last
10834// open-coded three-slot struct-literal on the envelope, matching the
10835// same standalone-ctor discipline the sibling
10836// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
10837// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
10838// [`crate::SupervisorError::child_caixa_invalid`] /
10839// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
10840// `{ caixa: String, [versao: String,] reason: String }` two- and three-
10841// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
10842// one variant on the `{ host: String, reason: String }` two-slot
10843// envelope) apply on their sibling one-off variants.
10844//
10845// The one wire-up site on this variant — [`WitContract::target`]'s
10846// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
10847// six per-`:contratos` value-shape gates inside the same method body,
10848// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
10849// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
10850// `ContratoWitInvalid`) each already reach through one of the three
10851// peer macro-generated ctor families above — opened the same five-line
10852// `let (de, para) = self.edge_pair(); return
10853// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
10854// ep.to_string() });` struct-literal against the local
10855// [`WitContract::edge_pair`] composite-projection accessor and the
10856// caller-side `&str` endpoint — the exact "same block re-inlined at
10857// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10858// altitude the six peer `AplicacaoError` constructor families each
10859// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
10860// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
10861// becomes a caixa-build error, not a Cilium L7 policy-side path-match
10862// silent traffic drop far from the source caixa.lisp) now routes through
10863// one substrate primitive on the envelope.
10864//
10865// The ctor below folds the site onto one dispatch:
10866// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
10867// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
10868// on the same `(edge_pair, endpoint)` pair. The uniform three-field
10869// construction (`de, para` pair-destructure onto same-named fields +
10870// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
10871// body — rather than at the wire-up site. `#[must_use]` fires a compile
10872// warning at any future wire-up that mistakenly discards the constructed
10873// error.
10874//
10875// Every future consumer that wants to construct this variant outside
10876// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
10877// CR materializer's per-`:contratos` admission validator raising the
10878// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
10879// `feira validate --contratos` per-caixa admission verb re-running the
10880// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
10881// probing each declared `:endpoint` against the same shared
10882// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
10883// resolver rejecting a leading-slash-missing `:endpoint` against a
10884// cluster-local Cilium snapshot the M4 CR materializer projects) now
10885// reaches this variant through one call rather than re-inlining the
10886// five-line pair-destructure + struct-literal block in lockstep with
10887// the sole in-crate wire-up site.
10888impl AplicacaoError {
10889    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
10890    /// naming the offending edge `(de, para)` pair and the per-payload
10891    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
10892    /// endpoint.to_string() }` three-slot struct-literal onto one
10893    /// substrate primitive so every wire-up on this variant reads
10894    /// through one dispatch rather than the pre-lift five-line
10895    /// pair-destructure + struct-literal block. The `edge` pair threads
10896    /// verbatim from [`WitContract::edge_pair`] at the call site,
10897    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
10898    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
10899    /// paired two-slot and four-slot per-`:contratos :endpoint`
10900    /// envelopes on the same [`AplicacaoError`] type.
10901    #[must_use]
10902    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
10903        let (de, para) = edge;
10904        Self::ContratoEndpointNotAbsolute {
10905            de,
10906            para,
10907            endpoint: endpoint.to_string(),
10908        }
10909    }
10910
10911    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
10912    /// offending self-edge's owning `caixa` and its `:wit` world
10913    /// reference, projecting both slots through the [`WitContract`]'s
10914    /// own [`WitContract::source`] and [`WitContract::world_ref`]
10915    /// scalar accessors on the substrate primitive.
10916    ///
10917    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
10918    /// contract.world_ref().to_string() }` two-slot struct-literal onto
10919    /// one substrate primitive so every wire-up on this variant reads
10920    /// through one dispatch rather than the pre-lift four-line
10921    /// twin-`.to_string()` struct-literal block. The `contract` borrow
10922    /// threads verbatim from the caller-side `for c in
10923    /// self.contratos()` iteration at the sole in-crate wire-up site
10924    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
10925    /// per-`:contratos` `WitContract`-projection ctor discipline the
10926    /// peer [`AplicacaoError::empty_wit`] /
10927    /// [`AplicacaoError::contrato_endpoint_empty`] /
10928    /// [`AplicacaoError::contrato_subject_empty`] /
10929    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
10930    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
10931    /// envelope.
10932    ///
10933    /// The `caixa` slot is projected through [`WitContract::source`]
10934    /// rather than [`WitContract::destination`] to preserve byte-equal
10935    /// diagnostic ordering with the pre-lift open-coded body — a
10936    /// [`WitContract::is_self_loop`]-gated call site has
10937    /// `source() == destination()` by that predicate's own contract, so
10938    /// the two accessors are exchange-symmetric at this call site, but
10939    /// naming `source` at the ctor definition matches the pre-lift
10940    /// site's field selection and pins the discipline for any future
10941    /// consumer that constructs the variant against a not-yet-gated
10942    /// candidate contract (e.g. an M4
10943    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10944    /// webhook re-checking a per-`(:de, :para)` patched contract, a
10945    /// future `feira validate --contratos` per-caixa verb re-running
10946    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
10947    /// overlay resolver rejecting a self-edge introduced by a
10948    /// cluster-local `:contratos` override the M4 CR materializer
10949    /// projects).
10950    ///
10951    /// Peer of the sibling `WitContract`-projection ctors on the
10952    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
10953    /// same "one typed dispatch on the substrate primitive, projecting
10954    /// through the paired [`WitContract`] accessors, thin projections
10955    /// at each consumer" discipline extended here onto the last unlifted
10956    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
10957    /// inside [`AplicacaoSpec::validate_contratos`].
10958    #[must_use]
10959    pub fn contrato_self_loop(contract: &WitContract) -> Self {
10960        Self::ContratoSelfLoop {
10961            caixa: contract.source().to_string(),
10962            wit: contract.world_ref().to_string(),
10963        }
10964    }
10965
10966    /// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
10967    /// offending duplicate edge's `(:de, :para, :wit)` triple and the
10968    /// per-payload `:target` byte-string, projecting the first three slots
10969    /// through the paired [`WitContract::edge_triple`] typed-accessor and
10970    /// the trailing `target:` slot through [`WitTarget::label`] on the
10971    /// substrate primitive.
10972    ///
10973    /// Folds the uniform `let (de, para, wit) = contract.edge_triple();
10974    /// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
10975    /// six-line pair-destructure + struct-literal onto one substrate
10976    /// primitive so every wire-up on this variant reads through one
10977    /// dispatch rather than the pre-lift open-coded block inside the
10978    /// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
10979    /// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
10980    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
10981    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
10982    /// per-`:contratos` self-edge two-slot envelope) and the sibling
10983    /// [`AplicacaoError::empty_wit`] (projecting through
10984    /// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
10985    /// `:wit` two-slot envelope) `WitContract`-projection ctors on the
10986    /// same [`AplicacaoError`] type — extended here onto the last unlifted
10987    /// four-slot `{ de: String, para: String, wit: String, target: String }`
10988    /// per-`:contratos` whole-edge-dedup envelope inside
10989    /// [`AplicacaoSpec::validate_contratos`], closing the paired
10990    /// duplicate-gate diagnostic constructor site the peer
10991    /// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
10992    /// the last unlifted composite-projection wire-up.
10993    ///
10994    /// The `contract` borrow threads verbatim from the caller-side `for c
10995    /// in self.contratos()` iteration at the sole in-crate wire-up site
10996    /// [`AplicacaoSpec::validate_contratos`], and `target` threads
10997    /// verbatim from the paired `let target_view = c.target()?` local
10998    /// materialized upstream of the [`crate::render::insert_first_seen`]
10999    /// dedup dispatch — both project onto their respective substrate-
11000    /// primitive accessors ([`WitContract::edge_triple`] +
11001    /// [`WitTarget::label`]) inside the ctor body, matching the sibling
11002    /// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
11003    /// posture verbatim on the paired self-edge envelope.
11004    ///
11005    /// Every future consumer that wants to construct this variant outside
11006    /// [`AplicacaoSpec::validate_contratos`] — a deferred
11007    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11008    /// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
11009    /// candidate against a per-tenant `:contratos` overlay before the
11010    /// whole-edge dedup gate re-fires, a future `feira validate
11011    /// --contratos` per-caixa admission verb re-running the dedup check on
11012    /// demand, an M4 per-cluster contrato-cap resolver rejecting a
11013    /// cross-tenant duplicate-edge collision introduced by a fleet-local
11014    /// overlay the M4 CR materializer projects — now reaches this variant
11015    /// through one call rather than re-inlining the six-line pair-
11016    /// destructure + struct-literal block in lockstep with the existing
11017    /// wire-up.
11018    #[must_use]
11019    pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
11020        let (de, para, wit) = contract.edge_triple();
11021        Self::ContratoDuplicate {
11022            de,
11023            para,
11024            wit,
11025            target: target.label(),
11026        }
11027    }
11028
11029    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
11030    /// offending `:membros :caixa` and its `:versao` requirement under
11031    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
11032    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
11033    /// reason.into() }` three-slot struct-literal onto one substrate
11034    /// primitive so every wire-up on this variant reads through one
11035    /// dispatch, matching the peer
11036    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
11037    /// shape verbatim on the sibling `SupervisorError { caixa: String,
11038    /// versao: String, reason: String }` envelope's per-`:children :versao`
11039    /// axis. `reason` accepts both `&str` literals and `format!(…)`
11040    /// outputs through the `impl Into<String>` bound so the sole
11041    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
11042    /// requirement-cascade closure (routing the shared
11043    /// [`crate::render::require_valid_versao_requirement`]-delivered
11044    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
11045    /// transformation on the caller-side `reason` axis. The
11046    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
11047    /// routing the sole wire-up already threads through remains verbatim
11048    /// — the ctor's two `&str` parameters accept the two accessors'
11049    /// returns as-is with no re-allocation at the call site.
11050    #[must_use]
11051    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
11052        Self::MembroVersaoInvalid {
11053            caixa: caixa.to_string(),
11054            versao: versao.to_string(),
11055            reason: reason.into(),
11056        }
11057    }
11058
11059    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
11060    /// the offending `:placement :clusters` entry.
11061    ///
11062    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
11063    /// cluster.to_string() }` one-field struct-literal onto one substrate
11064    /// primitive so every wire-up on this variant reads through one
11065    /// dispatch rather than the pre-lift three-line open-coded
11066    /// struct-literal block. The `cluster` slot threads verbatim from the
11067    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
11068    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
11069    /// per-entry dedup closure passed to
11070    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
11071    /// bracket accepts the free function pointer as-is.
11072    ///
11073    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
11074    /// per-`:politicas <scalar>` single-slot ctor families
11075    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
11076    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
11077    /// `{ path: String }` at the peer per-gateway envelope,
11078    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
11079    /// at the peer per-`:politicas` cap-scalar envelope) on the same
11080    /// [`AplicacaoError`] type — extends the "one typed dispatch per
11081    /// substrate primitive on every single-slot per-M3-slot envelope"
11082    /// discipline onto the last unlifted `{ cluster: String }` one-slot
11083    /// per-`:placement :clusters` dedup-envelope inside
11084    /// [`AplicacaoSpec::validate_placement_shape`].
11085    ///
11086    /// Every future consumer that wants to construct this variant outside
11087    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
11088    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11089    /// webhook re-checking a `:placement :clusters` overlay against a
11090    /// per-tenant cluster-topology snapshot, a future `feira validate
11091    /// --placement` per-caixa admission verb re-running the dedup check
11092    /// on demand, an M4 per-cluster placement resolver rejecting a
11093    /// duplicate cluster-name entry introduced by a fleet-local overlay
11094    /// the M4 CR materializer projects — now reaches this variant through
11095    /// one call rather than re-inlining the three-line struct-literal.
11096    #[must_use]
11097    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
11098        Self::PlacementClusterDuplicate {
11099            cluster: cluster.to_string(),
11100        }
11101    }
11102
11103    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
11104    /// the offending `:placement :estrategia` scalar the empty `:clusters`
11105    /// list was declared against, projecting through the paired
11106    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
11107    /// primitive.
11108    ///
11109    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
11110    /// placement.estrategia() }` one-field struct-literal onto one
11111    /// substrate primitive so every wire-up on this variant reads through
11112    /// one dispatch rather than the pre-lift three-line open-coded
11113    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
11114    /// p.estrategia() }` block inside
11115    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
11116    /// projection posture as the sibling
11117    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
11118    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
11119    /// per-`:contratos` self-edge envelope) and the peer
11120    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
11121    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
11122    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
11123    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
11124    /// per-`:placement` empty-clusters envelope inside
11125    /// [`AplicacaoSpec::validate_placement`].
11126    ///
11127    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
11128    /// [`Placement::estrategia`] `Copy`-scalar return through one
11129    /// zero-runtime-work construction — no allocation, no owned-string
11130    /// materialization — so the pre-lift `Copy`-pass-through property the
11131    /// open-coded `p.estrategia()` field expression carried survives
11132    /// verbatim through the substrate primitive. The sibling
11133    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
11134    /// carries the paired `.to_string()`-owned-String allocation on the
11135    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
11136    /// preserves the zero-alloc posture at the substrate-primitive
11137    /// dispatch, matching the peer
11138    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
11139    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
11140    /// per-`:politicas` cap-scalar envelopes.
11141    ///
11142    /// Every future consumer that wants to construct this variant outside
11143    /// [`AplicacaoSpec::validate_placement`] — a deferred
11144    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11145    /// webhook re-checking a `:placement :clusters` overlay against a
11146    /// per-tenant cluster-topology snapshot when the overlay resolves to
11147    /// an empty list, a future `feira validate --placement` per-caixa
11148    /// admission verb re-running the empty-clusters check on demand, an
11149    /// M4 per-cluster placement resolver rejecting an empty cluster pool
11150    /// after a fleet-local overlay strips every declared cluster — now
11151    /// reaches this variant through one call rather than re-inlining the
11152    /// three-line struct-literal in lockstep with the one in-crate
11153    /// wire-up site.
11154    #[must_use]
11155    pub const fn placement_without_clusters(placement: &Placement) -> Self {
11156        Self::PlacementWithoutClusters {
11157            estrategia: placement.estrategia(),
11158        }
11159    }
11160
11161    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
11162    /// offending `:placement :estrategia` scalar and the declared-but-
11163    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
11164    /// the strategy through the paired [`Placement::estrategia`]
11165    /// `Copy`-scalar accessor on the substrate primitive.
11166    ///
11167    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
11168    /// placement.estrategia(), shard_key: shard_key.to_string() }`
11169    /// two-slot struct-literal onto one substrate primitive so every
11170    /// wire-up on this variant reads through one dispatch rather than
11171    /// the pre-lift four-line open-coded struct-literal block inside
11172    /// [`AplicacaoSpec::validate_placement`]'s
11173    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
11174    /// arm. Same substrate-primitive-projection posture as the sibling
11175    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
11176    /// projecting through [`Placement::estrategia`] on the peer
11177    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
11178    /// empty-clusters envelope) and the peer
11179    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
11180    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
11181    /// the paired per-`:contratos` self-edge envelope) ctors — extended
11182    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
11183    /// shard_key: String }` two-slot per-`:placement :shard-key`
11184    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
11185    /// partition.
11186    ///
11187    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
11188    /// `&str` from the sole in-crate wire-up site (narrowed from
11189    /// `Option<&str>` via [`Placement::shard_key`]) and any future
11190    /// `&String` deref from a downstream consumer that reaches for the
11191    /// slot through the paired accessor, materializing the owned
11192    /// [`String`] via one `.to_string()` at the substrate primitive so
11193    /// no per-arm `.to_string()` allocation lives at the caller. The
11194    /// `estrategia` slot threads through [`Placement::estrategia`]'s
11195    /// `Copy`-scalar return rather than accepting a bare
11196    /// [`PlacementStrategy`] argument, matching the peer
11197    /// [`AplicacaoError::placement_without_clusters`] discipline —
11198    /// carrying the [`Placement`] borrow through one accessor call at
11199    /// the substrate primitive is strictly stronger than accepting the
11200    /// scalar as a separate argument (a future caller that constructs
11201    /// the error against a candidate [`Placement`] whose
11202    /// [`Placement::estrategia`] value the caller re-derives from
11203    /// another source can silently disagree with the storage the
11204    /// [`Placement`] carries; the accessor-projected primitive cannot).
11205    ///
11206    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
11207    /// families on the same [`AplicacaoError`] type — same "one typed
11208    /// dispatch on the substrate primitive, projecting through the
11209    /// paired [`Placement`] accessors, thin projections at each
11210    /// consumer" discipline extended here onto the last unlifted
11211    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
11212    /// [`AplicacaoSpec::validate_placement`].
11213    ///
11214    /// Every future consumer that wants to construct this variant
11215    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
11216    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11217    /// webhook re-checking a `:placement (:estrategia Replicated
11218    /// :shard-key …)` overlay against a per-tenant cluster-topology
11219    /// snapshot, a future `feira validate --placement` per-caixa
11220    /// admission verb re-running the non-`Sharded`-arm refusal on
11221    /// demand, an M4 per-cluster placement resolver rejecting a
11222    /// declared-but-inert `:shard-key` introduced by a fleet-local
11223    /// overlay the M4 CR materializer projects — now reaches this
11224    /// variant through one call rather than re-inlining the four-line
11225    /// struct-literal in lockstep with the one in-crate wire-up site.
11226    #[must_use]
11227    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
11228        Self::ShardKeyOnNonSharded {
11229            estrategia: placement.estrategia(),
11230            shard_key: shard_key.to_string(),
11231        }
11232    }
11233
11234    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
11235    /// offending `:entrada :para` value the membership lookup against the
11236    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
11237    /// slot through the paired [`Entrada::destination`] byte-string
11238    /// accessor on the substrate primitive.
11239    ///
11240    /// Folds the uniform `Self::EntradaMemberMissing { para:
11241    /// entrada.destination().to_string() }` one-field struct-literal onto
11242    /// one substrate primitive so every wire-up on this variant reads
11243    /// through one dispatch rather than the pre-lift three-line
11244    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
11245    /// e.destination().to_string() }` block inside
11246    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
11247    /// projection posture as the sibling
11248    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
11249    /// projecting through [`Placement::estrategia`] on the peer
11250    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
11251    /// empty-clusters envelope) and the sibling
11252    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
11253    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
11254    /// the paired per-`:contratos` self-edge envelope) ctors — extended
11255    /// here onto the last unlifted `{ para: String }` one-slot
11256    /// per-`:entrada :para` phantom-reference envelope on the sibling
11257    /// per-`:entrada` slot.
11258    ///
11259    /// The `entrada: &Entrada` parameter threads verbatim from the
11260    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
11261    /// the sole in-crate wire-up site
11262    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
11263    /// per-`:entrada` byte-string reads that already route through
11264    /// [`Entrada::destination`] one accessor call earlier in the same
11265    /// gate (`validate_entrada_para(e.destination())?;` +
11266    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
11267    /// borrow through one accessor call at the substrate primitive is
11268    /// strictly stronger than accepting the bare `&str` as a separate
11269    /// argument — a future consumer that constructs the error against a
11270    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
11271    /// caller re-derives from another source (a raw `e.para` field
11272    /// access that skipped the accessor, a stale snapshot of the
11273    /// pre-normalization storage) can silently disagree with the
11274    /// storage the [`Entrada`] carries; the accessor-projected primitive
11275    /// cannot. Matches the peer
11276    /// [`AplicacaoError::placement_without_clusters`] and
11277    /// [`AplicacaoError::shard_key_on_non_sharded`]
11278    /// [`Placement`]-borrow-projection discipline on the sibling
11279    /// per-`:placement` envelope, and matches the peer
11280    /// [`AplicacaoError::contrato_self_loop`] and
11281    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
11282    /// [`WitContract`]-borrow-projection discipline on the sibling
11283    /// per-`:contratos` envelope.
11284    ///
11285    /// Every future consumer that wants to construct this variant
11286    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
11287    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11288    /// webhook re-checking a `:entrada :para` overlay against a
11289    /// per-tenant `:membros` snapshot after a fleet-local overlay
11290    /// renames a member, a future `feira validate --entrada` per-caixa
11291    /// admission verb re-running the phantom-reference lookup on
11292    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
11293    /// `:entrada :para` whose target Servico was stripped from the
11294    /// cluster-local `:membros` overlay, a future authoring-surface
11295    /// widening the field into a `(String, Vec<Suggestion>)` pair
11296    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
11297    /// this variant through one call rather than re-inlining the
11298    /// three-line struct-literal in lockstep with the one in-crate
11299    /// wire-up site.
11300    #[must_use]
11301    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
11302        Self::EntradaMemberMissing {
11303            para: entrada.destination().to_string(),
11304        }
11305    }
11306
11307    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
11308    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
11309    /// sync-only-subgraph gate at
11310    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
11311    /// gray-arm's back-edge target through the parent chain, folding the
11312    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
11313    /// onto one substrate primitive so every wire-up on this variant
11314    /// reads through one dispatch rather than the pre-lift open-coded
11315    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
11316    /// in-crate wire-up site inside
11317    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
11318    /// return. Same substrate-primitive-projection posture as the
11319    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
11320    /// projecting through [`Entrada::destination`] on the peer `{ para:
11321    /// String }` one-slot per-`:entrada :para` phantom-reference
11322    /// envelope) and [`AplicacaoError::placement_without_clusters`]
11323    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
11324    /// sibling `{ estrategia: PlacementStrategy }` one-slot
11325    /// per-`:placement` empty-clusters envelope) ctors — extended here
11326    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
11327    /// per-`:contratos` cross-edge sync-cycle envelope on the same
11328    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
11329    /// struct-literal wire-up under
11330    /// [`AplicacaoSpec::detect_sync_cycles`].
11331    ///
11332    /// The `cycle: Vec<String>` parameter threads verbatim from the
11333    /// caller-side DFS traversal's reconstructed cycle path (built up by
11334    /// walking `parent` from the gray-back-edge's source node back to
11335    /// its target, reversing, then appending the target once more so the
11336    /// first and last elements coincide by construction and the
11337    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
11338    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
11339    /// the pre-lift open-coded body's field selection exactly. Taking
11340    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
11341    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
11342    /// caller already owns the reconstructed [`Vec<String>`] at the
11343    /// gray-arm return, so no per-arm re-allocation lands on the ctor
11344    /// path).
11345    ///
11346    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
11347    /// families on the same [`AplicacaoError`] type — same "one typed
11348    /// dispatch on the substrate primitive, thin projections at each
11349    /// consumer" discipline extended here onto the last unlifted
11350    /// per-`:contratos` cross-edge cycle envelope inside
11351    /// [`AplicacaoSpec::detect_sync_cycles`].
11352    ///
11353    /// Every future consumer that wants to construct this variant
11354    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
11355    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11356    /// webhook re-checking a per-tenant `:contratos` overlay's
11357    /// sync-cycle invariant after a fleet-local overlay adds or removes
11358    /// a synchronous edge, a future `feira validate --contratos`
11359    /// per-caixa admission verb re-running the cross-edge cycle detector
11360    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
11361    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
11362    /// entry and needs to re-probe *just* the cycle invariant against
11363    /// the post-patch adjacency), a future authoring-surface widening
11364    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
11365    /// the per-hop WIT shape for a richer "break here" hint — now
11366    /// reaches this variant through one call rather than re-inlining the
11367    /// open-coded struct-literal in lockstep with the one in-crate
11368    /// wire-up site.
11369    #[must_use]
11370    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
11371        Self::ContratoCycle { cycle }
11372    }
11373
11374    /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
11375    /// naming the offending `:politicas :circuit-breaker :window` and
11376    /// the paired `:politicas :timeout` scalars under the first-firing
11377    /// cross-axis-violation gate at
11378    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
11379    /// `window` slot through the [`CircuitBreaker::window`] scalar
11380    /// accessor on the substrate primitive.
11381    ///
11382    /// Folds the uniform `{ window: cb.window(), timeout: t }`
11383    /// two-slot `Copy`-`Duration` struct-literal onto one substrate
11384    /// primitive so every wire-up on this variant reads through one
11385    /// dispatch rather than the pre-lift four-line struct-literal
11386    /// block. The `cb` borrow threads verbatim from the caller-side
11387    /// `if let (Some(t), Some(cb)) = (self.timeout(),
11388    /// self.circuit_breaker())` pair-destructure at the sole in-crate
11389    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
11390    /// window-below-timeout arm; `timeout` threads verbatim from the
11391    /// paired [`MeshPolicy::timeout`] accessor return already
11392    /// destructured out of the same `if let` pair. `const fn`
11393    /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
11394    /// property verbatim (both fields are [`Duration`], the
11395    /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
11396    /// no `.to_string()` / `.into()` allocation lands on the ctor
11397    /// path).
11398    ///
11399    /// The `window` slot is projected through [`CircuitBreaker::window`]
11400    /// (not spelled out as a bare `Duration` parameter) so a future
11401    /// widening of the `:circuit-breaker :window` axis — a
11402    /// per-`:contratos`-edge `:circuit-breaker :window` override the
11403    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
11404    /// the plain [`Duration`] window to a richer per-status-class
11405    /// window tuple once Envoy's `outlier_detection.interval` peers
11406    /// come into scope — reaches the diagnostic through one accessor
11407    /// swap rather than every wire-up in lockstep, matching the peer
11408    /// substrate-primitive-projection posture of
11409    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
11410    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
11411    /// the sibling `{ caixa: String, wit: String }` two-slot
11412    /// per-`:contratos` self-edge envelope),
11413    /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
11414    /// through [`Entrada::destination`] on the sibling `{ para: String }`
11415    /// one-slot per-`:entrada :para` phantom-reference envelope), and
11416    /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
11417    /// through [`Placement::estrategia`] on the sibling `{ estrategia:
11418    /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
11419    /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
11420    /// / `:placement` envelopes.
11421    ///
11422    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
11423    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
11424    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
11425    /// [`MeshPolicy::validate`] gate — extended here onto the
11426    /// first-firing cross-axis compound variant, whose multi-slot
11427    /// `{ window: Duration, timeout: Duration }` shape does not fit
11428    /// that macro's one-`Copy`-scalar-per-variant arity. The three
11429    /// remaining cross-axis variants
11430    /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
11431    /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
11432    /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
11433    /// on the two-slot `{ retries, max_failures }` envelope, and
11434    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
11435    /// two-slot `{ retries, rate }` envelope) each carry a distinct
11436    /// substrate-primitive-projection shape and are folded on their
11437    /// own axis by their own per-variant ctors as those wire-ups are
11438    /// lifted.
11439    ///
11440    /// Every future consumer that wants to construct this variant
11441    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
11442    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11443    /// webhook re-checking a per-tenant `:politicas` overlay's
11444    /// window-vs-timeout cross-axis invariant after a cluster-local
11445    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
11446    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
11447    /// future per-`:contratos`-edge `:politicas` override the M4 CR
11448    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
11449    /// projecting a per-tenant per-axis ceiling into the same
11450    /// diagnostic shape — now reaches this variant through one call
11451    /// rather than re-inlining the open-coded struct-literal in
11452    /// lockstep with the one in-crate wire-up site.
11453    #[must_use]
11454    pub const fn policy_breaker_window_below_timeout(
11455        cb: &CircuitBreaker,
11456        timeout: Duration,
11457    ) -> Self {
11458        Self::PolicyBreakerWindowBelowTimeout {
11459            window: cb.window(),
11460            timeout,
11461        }
11462    }
11463
11464    /// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
11465    /// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
11466    /// cross-axis pair whose token-bucket window structurally starves the
11467    /// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
11468    /// :window`.
11469    ///
11470    /// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
11471    /// max_failures: cb.max_failures(), cb_window: cb.window() }`
11472    /// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
11473    /// primitive so every wire-up on this variant reads through one dispatch
11474    /// rather than the pre-lift six-line struct-literal block. Both `rl` and
11475    /// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
11476    /// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
11477    /// pair-destructure at the sole in-crate wire-up site inside
11478    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
11479    /// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
11480    /// zero-runtime-work property verbatim (all four fields are `u32` /
11481    /// [`Duration`], every projected accessor is itself `const fn`, and no
11482    /// `.to_string()` / `.into()` allocation lands on the ctor path).
11483    ///
11484    /// Every slot is projected through its paired substrate-primitive
11485    /// accessor ([`RateLimit::rate`], [`RateLimit::window`],
11486    /// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
11487    /// than spelled out as bare `u32` / [`Duration`] parameters so a future
11488    /// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
11489    /// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
11490    /// acknowledges, a promotion of the plain scalar rate to a richer
11491    /// per-status-class token bucket once Envoy's per-descriptor
11492    /// `local_rate_limit` peers come into scope — reaches the diagnostic
11493    /// through one accessor swap rather than every wire-up in lockstep.
11494    /// Matches the peer substrate-primitive-projection posture of
11495    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
11496    /// projecting through [`CircuitBreaker::window`] on the sibling
11497    /// two-slot `{ window, timeout }` cross-axis
11498    /// `(:timeout, :circuit-breaker)` envelope) on the sibling
11499    /// first-firing cross-axis compound variant.
11500    ///
11501    /// Second cross-axis Policy* variant folded onto its own per-variant
11502    /// substrate primitive — extending the peer
11503    /// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
11504    /// onto the second-firing cross-axis compound variant, whose four-slot
11505    /// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
11506    /// the sibling two-slot ctor's arity. The two remaining cross-axis
11507    /// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
11508    /// on the two-slot `{ retries, max_failures }` envelope and
11509    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
11510    /// two-slot `{ retries, rate }` envelope) each carry a distinct
11511    /// substrate-primitive-projection shape and are folded on their own
11512    /// axis by their own per-variant ctors as those wire-ups are lifted.
11513    ///
11514    /// Every future consumer that wants to construct this variant outside
11515    /// [`MeshPolicy::first_cross_axis_violation`] — a deferred
11516    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11517    /// webhook re-checking a per-tenant `:politicas` overlay's
11518    /// starve-under-rate-limit cross-axis invariant after a cluster-local
11519    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
11520    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
11521    /// future per-`:contratos`-edge `:politicas` override the M4 CR
11522    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
11523    /// projecting a per-tenant per-axis ceiling into the same diagnostic
11524    /// shape — now reaches this variant through one call rather than
11525    /// re-inlining the open-coded struct-literal in lockstep with the one
11526    /// in-crate wire-up site.
11527    #[must_use]
11528    pub const fn policy_breaker_cannot_trip_under_rate_limit(
11529        rl: &RateLimit,
11530        cb: &CircuitBreaker,
11531    ) -> Self {
11532        Self::PolicyBreakerCannotTripUnderRateLimit {
11533            rate: rl.rate(),
11534            rl_window: rl.window(),
11535            max_failures: cb.max_failures(),
11536            cb_window: cb.window(),
11537        }
11538    }
11539
11540    /// Construct an
11541    /// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
11542    /// naming the offending `:politicas :retries` and the paired
11543    /// `:politicas :circuit-breaker :max-failures` scalars under the
11544    /// third-firing cross-axis-violation gate at
11545    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
11546    /// `max_failures` slot through the [`CircuitBreaker::max_failures`]
11547    /// scalar accessor on the substrate primitive.
11548    ///
11549    /// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
11550    /// two-slot `Copy`-`u32` struct-literal onto one substrate
11551    /// primitive so every wire-up on this variant reads through one
11552    /// dispatch rather than the pre-lift four-line struct-literal
11553    /// block. The `cb` borrow threads verbatim from the caller-side
11554    /// `if let (Some(retries), Some(cb)) = (self.retries(),
11555    /// self.circuit_breaker())` pair-destructure at the sole in-crate
11556    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
11557    /// retries-saturate arm; `retries` threads verbatim from the paired
11558    /// [`MeshPolicy::retries`] accessor return already destructured out
11559    /// of the same `if let` pair. `const fn` preserves the pre-lift
11560    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
11561    /// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
11562    /// is itself `const fn`, and no `.to_string()` / `.into()`
11563    /// allocation lands on the ctor path).
11564    ///
11565    /// The `max_failures` slot is projected through
11566    /// [`CircuitBreaker::max_failures`] (not spelled out as a bare
11567    /// `u32` parameter) so a future widening of the
11568    /// `:circuit-breaker :max-failures` axis — a
11569    /// per-`:contratos`-edge `:circuit-breaker :max-failures` override
11570    /// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
11571    /// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
11572    /// resolver projects, a promotion of the plain `u32` count to a
11573    /// richer per-status-class trip counter once Envoy's
11574    /// `outlier_detection.consecutive_5xx` peers come into scope —
11575    /// reaches the diagnostic through one accessor swap rather than
11576    /// every wire-up in lockstep, matching the peer
11577    /// substrate-primitive-projection posture of
11578    /// [`AplicacaoError::policy_breaker_window_below_timeout`]
11579    /// (9b30c07, projecting through [`CircuitBreaker::window`] on the
11580    /// sibling two-slot `{ window, timeout }` first cross-axis
11581    /// envelope) and
11582    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
11583    /// (6bb4e46, projecting through [`RateLimit::rate`] /
11584    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
11585    /// [`CircuitBreaker::window`] on the sibling four-slot second
11586    /// cross-axis envelope). `retries` remains a bare `u32` parameter,
11587    /// matching the sibling first-arm ctor's bare `timeout: Duration`
11588    /// parameter discipline: [`MeshPolicy::retries`] returns
11589    /// `Option<u32>` and the caller-side `if let` already destructures
11590    /// the inner `u32` out, so the ctor takes the destructured scalar
11591    /// verbatim rather than re-wrapping it into an accessor call.
11592    ///
11593    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
11594    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
11595    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
11596    /// [`MeshPolicy::validate`] gate — extended here onto the
11597    /// third-firing cross-axis compound variant, whose multi-slot
11598    /// `{ retries: u32, max_failures: u32 }` shape does not fit that
11599    /// macro's one-`Copy`-scalar-per-variant arity. The one remaining
11600    /// cross-axis variant
11601    /// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
11602    /// two-slot `{ retries, rate }` envelope) carries a distinct
11603    /// substrate-primitive-projection shape (projecting through
11604    /// [`RateLimit::rate`] rather than
11605    /// [`CircuitBreaker::max_failures`]) and is folded on its own axis
11606    /// by its own per-variant ctor as that wire-up is lifted in a
11607    /// follow-up run.
11608    ///
11609    /// Every future consumer that wants to construct this variant
11610    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
11611    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11612    /// webhook re-checking a per-tenant `:politicas` overlay's
11613    /// retries-vs-max-failures cross-axis invariant after a
11614    /// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
11615    /// #3 roadmap acknowledges resolves an *effective* per-edge
11616    /// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
11617    /// override the M4 CR resolver projects, an M4 per-cluster
11618    /// `:politicas`-cap resolver projecting a per-tenant per-axis
11619    /// ceiling into the same diagnostic shape — now reaches this
11620    /// variant through one call rather than re-inlining the open-coded
11621    /// struct-literal in lockstep with the one in-crate wire-up site.
11622    #[must_use]
11623    pub const fn policy_breaker_trips_before_retries_exhausted(
11624        retries: u32,
11625        cb: &CircuitBreaker,
11626    ) -> Self {
11627        Self::PolicyBreakerTripsBeforeRetriesExhausted {
11628            retries,
11629            max_failures: cb.max_failures(),
11630        }
11631    }
11632
11633    /// Construct an
11634    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
11635    /// the offending `:politicas :retries` and the paired `:politicas
11636    /// :rate-limit` `:rate` scalars under the fourth-firing (and last-
11637    /// remaining) cross-axis-violation gate at
11638    /// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
11639    /// slot through the [`RateLimit::rate`] scalar accessor on the
11640    /// substrate primitive.
11641    ///
11642    /// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
11643    /// `Copy`-`u32` struct-literal onto one substrate primitive so every
11644    /// wire-up on this variant reads through one dispatch rather than
11645    /// the pre-lift four-line struct-literal block. The `rl` borrow
11646    /// threads verbatim from the caller-side `if let (Some(retries),
11647    /// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
11648    /// at the sole in-crate wire-up site inside
11649    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
11650    /// limit arm; `retries` threads verbatim from the paired
11651    /// [`MeshPolicy::retries`] accessor return already destructured out
11652    /// of the same `if let` pair. `const fn` preserves the pre-lift
11653    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
11654    /// fields are `u32`, the [`RateLimit::rate`] accessor is itself
11655    /// `const fn`, and no `.to_string()` / `.into()` allocation lands on
11656    /// the ctor path).
11657    ///
11658    /// The `rate` slot is projected through [`RateLimit::rate`] (not
11659    /// spelled out as a bare `u32` parameter) so a future widening of
11660    /// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
11661    /// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
11662    /// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
11663    /// per-cluster `:politicas`-cap resolver projects, a promotion of
11664    /// the plain `u32` token capacity to a richer
11665    /// `{max_tokens, tokens_per_fill}` tuple once Envoy's
11666    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
11667    /// axis comes into scope — reaches the diagnostic through one
11668    /// accessor swap rather than every wire-up in lockstep, matching
11669    /// the peer substrate-primitive-projection posture of
11670    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
11671    /// projecting through [`CircuitBreaker::window`] on the sibling
11672    /// two-slot `{ window, timeout }` first cross-axis envelope),
11673    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
11674    /// (6bb4e46, projecting through [`RateLimit::rate`] /
11675    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
11676    /// [`CircuitBreaker::window`] on the sibling four-slot second
11677    /// cross-axis envelope), and
11678    /// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
11679    /// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
11680    /// the sibling two-slot `{ retries, max_failures }` third cross-axis
11681    /// envelope). `retries` remains a bare `u32` parameter, matching
11682    /// the sibling third-arm ctor's bare `retries: u32` parameter
11683    /// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
11684    /// caller-side `if let` already destructures the inner `u32` out, so
11685    /// the ctor takes the destructured scalar verbatim rather than
11686    /// re-wrapping it into an accessor call.
11687    ///
11688    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
11689    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
11690    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
11691    /// [`MeshPolicy::validate`] gate — extended here onto the
11692    /// fourth-firing (and final) cross-axis compound variant, whose
11693    /// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
11694    /// macro's one-`Copy`-scalar-per-variant arity. After this lift all
11695    /// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
11696    /// read through one substrate-primitive ctor dispatch each; the
11697    /// per-envelope compound cross-axis Policy* family closes on this
11698    /// variant.
11699    ///
11700    /// Every future consumer that wants to construct this variant
11701    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
11702    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11703    /// webhook re-checking a per-tenant `:politicas` overlay's
11704    /// retries-vs-rate cross-axis invariant after a cluster-local
11705    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
11706    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
11707    /// future per-`:contratos`-edge `:politicas` override the M4 CR
11708    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
11709    /// projecting a per-tenant per-axis ceiling into the same diagnostic
11710    /// shape — now reaches this variant through one call rather than
11711    /// re-inlining the open-coded struct-literal in lockstep with the
11712    /// one in-crate wire-up site.
11713    #[must_use]
11714    pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
11715        Self::PolicyRateLimitCannotAdmitRetryBurst {
11716            retries,
11717            rate: rl.rate(),
11718        }
11719    }
11720
11721    /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
11722    /// offending `:contratos <slot>` (`:de` / `:para`) and the value
11723    /// that broke the shared DNS-1123-label floor under the given
11724    /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
11725    /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
11726    /// struct-literal onto one substrate primitive so every wire-up on
11727    /// this variant reads through one dispatch rather than the pre-lift
11728    /// six-line struct-literal block inside
11729    /// [`validate_contrato_caixa`]'s
11730    /// [`crate::render::require_valid_dns_1123_label`]
11731    /// `|reason| …` closure.
11732    ///
11733    /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
11734    /// (981060b) macro-generated ctor family
11735    /// ([`AplicacaoError::membro_caixa_invalid`],
11736    /// [`AplicacaoError::entrada_para_invalid`],
11737    /// [`AplicacaoError::entrada_host_invalid`],
11738    /// [`AplicacaoError::entrada_path_invalid`],
11739    /// [`AplicacaoError::placement_cluster_invalid`],
11740    /// [`AplicacaoError::placement_affinity_invalid`],
11741    /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
11742    /// dispatch per substrate primitive on every `{ <field>: String,
11743    /// reason: String }` per-axis parser-shaped envelope" discipline
11744    /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
11745    /// String, reason: String }` sibling whose extra `slot: &'static
11746    /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
11747    /// on the per-`:contratos`-edge value axis and so does not fit the
11748    /// two-slot macro's arity.
11749    ///
11750    /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
11751    /// (`&'static str` is `Copy`, no allocation), matching the caller-
11752    /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11753    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
11754    /// sole in-crate wire-up threads through. `reason: impl
11755    /// Into<String>` accepts both `&str` literals and the shared
11756    /// [`crate::render::require_valid_dns_1123_label`]-delivered
11757    /// owned-`String` return verbatim so the closure picks the ctor up
11758    /// without a per-arm wrapper transformation, matching the peer
11759    /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
11760    /// Into<String>` bound. `#[must_use]` fires a compile warning at
11761    /// any wire-up that mistakenly discards the constructed error
11762    /// rather than routing it through `return Err(…)` / `.map_err(…)`
11763    /// / a closure return.
11764    ///
11765    /// Every future consumer that wants to construct this variant
11766    /// outside the current in-crate wire-up (the deferred
11767    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
11768    /// per-`:contratos`-edge admission validator projecting the same
11769    /// diagnostic through the caller-facing `slot: &'static str` tag,
11770    /// a future `feira validate --contratos` per-caixa admission verb,
11771    /// an M4 per-`:contratos`-edge pre-emitter running the same
11772    /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
11773    /// pair before hitting the apiserver-side selector, an M4
11774    /// per-cluster contrato-cap resolver rejecting a cross-tenant
11775    /// selector projection into the same diagnostic shape) — now
11776    /// reaches this variant through one call rather than re-inlining
11777    /// the six-line struct-literal block in lockstep with the one
11778    /// in-crate wire-up site.
11779    #[must_use]
11780    pub fn contrato_caixa_invalid(
11781        slot: &'static str,
11782        caixa: &str,
11783        reason: impl Into<String>,
11784    ) -> Self {
11785        Self::ContratoCaixaInvalid {
11786            slot,
11787            caixa: caixa.to_string(),
11788            reason: reason.into(),
11789        }
11790    }
11791
11792    /// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
11793    /// offending `:contratos <slot>` (`:de` / `:para`) at which the
11794    /// caixa-reference value is the empty string. Folds the uniform
11795    /// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
11796    /// one substrate primitive so the sole in-crate closure passed to
11797    /// [`crate::render::require_valid_dns_1123_label`] at
11798    /// [`validate_contrato_caixa`] on this variant reads through one
11799    /// dispatch rather than the pre-lift open-coded block. The `slot`
11800    /// label threads verbatim from the caller-side
11801    /// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11802    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
11803    /// wire-up feeds through [`validate_contrato_caixa`]'s
11804    /// `slot: &'static str` parameter.
11805    ///
11806    /// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
11807    /// substrate primitive on the same
11808    /// [`crate::render::require_valid_dns_1123_label`] two-closure
11809    /// cascade — the empty-arm and invalid-arm now both reach the
11810    /// `AplicacaoError` envelope through one substrate primitive per
11811    /// typed variant, closing the pair. Same shape discipline as the
11812    /// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
11813    /// `{ slot: &'static str }` sibling on the `BehaviorError`
11814    /// envelope's four-arm sandboxed-lisp-path cascade
11815    /// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
11816    /// onto the sibling `AplicacaoError` envelope's two-arm
11817    /// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
11818    ///
11819    /// `slot` stays `&'static str` (not `&str`) — every `:contratos
11820    /// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
11821    /// `const` roster carrying program-lifetime storage, matching the
11822    /// enum-field type and the [`validate_contrato_caixa`] wire-up's
11823    /// per-axis dispatch. A runtime-borrowed `&str` would silently
11824    /// downgrade the label lifetime and let a caller stash a
11825    /// non-`'static` borrow into the returned error. `#[must_use]` fires
11826    /// a compile warning at any wire-up that mistakenly discards the
11827    /// constructed error rather than routing it through `return Err(…)`
11828    /// / `.map_err(…)` / a closure return. `pub const fn` matches the
11829    /// peer per-envelope one-slot `Copy`-scalar ctor family discipline
11830    /// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
11831    /// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
11832    /// at every wire-up site.
11833    ///
11834    /// Every future consumer that wants to construct this variant
11835    /// outside the current in-crate wire-up (the deferred
11836    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
11837    /// per-`:contratos`-edge admission validator projecting the same
11838    /// diagnostic through the caller-facing `slot: &'static str` tag,
11839    /// a future `feira validate --contratos` per-caixa admission verb,
11840    /// an M4 per-`:contratos`-edge pre-emitter running the same
11841    /// DNS-1123-label floor's empty-arm against a caller-supplied
11842    /// `:de` / `:para` pair before hitting the apiserver-side selector,
11843    /// a per-`Caixa` overlay resolver rejecting an author-supplied
11844    /// `:contratos` overlay's empty `:de` / `:para` against a
11845    /// cluster-local snapshot) — now reaches this variant through one
11846    /// call rather than re-inlining the open-coded closure block in
11847    /// lockstep with the one in-crate wire-up site.
11848    #[must_use]
11849    pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
11850        Self::ContratoCaixaEmpty { slot }
11851    }
11852}
11853
11854// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
11855// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
11856// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
11857// substrate-primitive family per typed variant — the paired
11858// `{ <field>: String, reason: String }` two-slot sibling on
11859// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
11860// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
11861// `ContratoMissingTarget`) and the peer two-slot
11862// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
11863// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
11864// on the sibling per-`:contratos` envelopes, plus the peer four-family
11865// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
11866// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
11867// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
11868// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
11869// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
11870// sibling layout-side envelope.
11871//
11872// Every one of the seven wire-up sites — six under the per-axis
11873// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
11874// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
11875// on `EntradaParaInvalid`, `validate_placement_cluster` on
11876// `PlacementClusterInvalid`, `validate_placement_affinity` on
11877// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
11878// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
11879// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
11880// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
11881// sites at [`validate_entrada_host`] (17dd504 already folded onto the
11882// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
11883// the macro-generated ctor of the same name), opened the identical
11884// four-line `AplicacaoError::<Variant>Invalid
11885// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
11886// the local `<field>: &str` argument — the exact "same block re-inlined
11887// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
11888// same altitude the peer three `AplicacaoError` constructor families
11889// and the four peer `LayoutError` constructor families each closed on
11890// their sibling envelopes.
11891//
11892// The macro below generates one `#[must_use]` inherent constructor per
11893// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
11894// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
11895// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
11896// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
11897// pre-lift struct-literal on the same `(<field>, reason)` pair. The
11898// uniform two-field construction (`<field>: <val>.to_string()`,
11899// `reason: reason.into()`) is spelled once — inside the macro — rather
11900// than at every wire-up site. The `reason: impl Into<String>` bound
11901// accepts both `&str` literals (with or without a trailing
11902// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
11903// wire-up site changes its per-arm diagnostic shape at the lift.
11904// `#[must_use]` fires a compile warning at any wire-up that mistakenly
11905// discards the constructed error rather than routing it through
11906// `return Err(…)` / `.map_err(…)` / a closure return.
11907//
11908// Every future consumer that wants to construct one of these seven
11909// variants outside the current in-crate wire-up sites (the deferred
11910// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
11911// admission validators, a future `feira validate --<axis>` per-caixa
11912// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
11913// on `:entrada :host`, an M4 typed placement-engine per-cluster /
11914// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
11915// per-path pre-emitter) reaches the variant through one call rather
11916// than re-inlining the four-line struct-literal block in lockstep with
11917// the current in-crate wire-up sites.
11918macro_rules! aplicacao_field_reason_ctors {
11919    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
11920        impl AplicacaoError {
11921            $(
11922                #[doc = concat!(
11923                    "Construct an [`AplicacaoError::",
11924                    stringify!($variant),
11925                    "`] naming the offending `",
11926                    stringify!($field),
11927                    "` under the given `reason`. Folds the uniform ",
11928                    "`{ ",
11929                    stringify!($field),
11930                    ": ",
11931                    stringify!($field),
11932                    ".to_string(), reason: reason.into() }` two-slot ",
11933                    "construction onto one substrate primitive so every ",
11934                    "wire-up on this variant reads through one dispatch ",
11935                    "rather than the pre-lift four-line struct-literal ",
11936                    "block. `reason` accepts both `&str` literals and ",
11937                    "`format!(…)` outputs through the `impl Into<String>` ",
11938                    "bound."
11939                )]
11940                #[must_use]
11941                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
11942                    Self::$variant {
11943                        $field: $field.to_string(),
11944                        reason: reason.into(),
11945                    }
11946                }
11947            )*
11948        }
11949    };
11950}
11951
11952aplicacao_field_reason_ctors! {
11953    membro_caixa_invalid => MembroCaixaInvalid { caixa },
11954    entrada_para_invalid => EntradaParaInvalid { para },
11955    entrada_host_invalid => EntradaHostInvalid { host },
11956    entrada_path_invalid => EntradaPathInvalid { path },
11957    placement_cluster_invalid => PlacementClusterInvalid { cluster },
11958    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
11959    shard_key_invalid => ShardKeyInvalid { shard_key },
11960}
11961
11962// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
11963// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
11964// [`WitContract::target`] onto one substrate-primitive family per typed
11965// variant — the paired `{ de: String, para: String, <field>: String,
11966// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
11967// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
11968// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
11969// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
11970// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
11971// `ContratoSlotEmpty`), and the peer two-slot
11972// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
11973// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
11974// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
11975// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
11976// sibling `AplicacaoError` envelopes, plus the peer four-family
11977// `LayoutError` ctor set on the sibling layout-side envelope.
11978//
11979// Every one of the four wire-up sites — four per-`:contratos` value-
11980// shape gates inside [`WitContract::target`] (the world-ref prefix
11981// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
11982// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
11983// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
11984// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
11985// failure on `:slot`) — opened the identical five-line
11986// `let (de, para) = self.edge_pair();
11987// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
11988// <field>: <val>.to_string(), reason });` block against the local
11989// [`WitContract::edge_pair`] composite-projection accessor and the
11990// per-arm `<val>: &str` argument — the exact "same block re-inlined at
11991// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
11992// altitude the peer three `AplicacaoError` constructor families and the
11993// four peer `LayoutError` constructor families each closed on their
11994// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
11995// macro closes the last unlifted `{ de, para, <field>: String, reason:
11996// String }` four-slot envelope inside `impl WitContract`, so every
11997// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
11998// reads through this one substrate primitive.
11999//
12000// The macro below generates one `#[must_use]` inherent constructor per
12001// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
12002// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
12003// sites onto one dispatch per arm:
12004// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
12005// byte-equal to the pre-lift struct-literal on the same
12006// `(edge_pair, <val>, reason)` triple. The uniform four-field
12007// construction (`de, para` pair-destructure onto same-named fields +
12008// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
12009// once — inside the macro — rather than at every wire-up site. The
12010// `reason: impl Into<String>` bound accepts both `&str` literals and
12011// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
12012// diagnostic shape at the lift, matching the peer
12013// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
12014// envelope. `#[must_use]` fires a compile warning at any wire-up that
12015// mistakenly discards the constructed error.
12016//
12017// Every future consumer that wants to construct one of these four
12018// variants outside [`WitContract::target`] (a deferred
12019// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
12020// admission validator raising per-payload value-shape diagnostics on
12021// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
12022// future `feira validate --contratos` per-caixa admission verb, an M4
12023// typed WIT-registry-driven per-arm pre-emitter probing each declared
12024// `:endpoint` / `:subject` / `:slot` payload against a canonical
12025// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
12026// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
12027// pre-emitter probing each `:endpoint` against the same shared
12028// HTTPPathMatch grammar) reaches the variant through one call rather
12029// than re-inlining the five-line pair-destructure + struct-literal
12030// block in lockstep with the four in-crate wire-up sites.
12031macro_rules! contrato_pair_value_reason_ctors {
12032    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
12033        impl AplicacaoError {
12034            $(
12035                #[doc = concat!(
12036                    "Construct an [`AplicacaoError::",
12037                    stringify!($variant),
12038                    "`] naming the offending edge `(de, para)` pair, the ",
12039                    "per-payload `",
12040                    stringify!($field),
12041                    "` value, and the parser-shaped `reason`. Folds the ",
12042                    "uniform `{ de, para, ",
12043                    stringify!($field),
12044                    ": ",
12045                    stringify!($field),
12046                    ".to_string(), reason: reason.into() }` four-slot ",
12047                    "construction onto one substrate primitive so every ",
12048                    "wire-up on this variant reads through one dispatch ",
12049                    "rather than the pre-lift five-line pair-destructure ",
12050                    "+ struct-literal block. The `edge` pair threads ",
12051                    "verbatim from [`WitContract::edge_pair`] at the ",
12052                    "call site; `reason` accepts both `&str` literals ",
12053                    "and `format!(…)` outputs through the `impl ",
12054                    "Into<String>` bound."
12055                )]
12056                #[must_use]
12057                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
12058                    let (de, para) = edge;
12059                    Self::$variant {
12060                        de,
12061                        para,
12062                        $field: $field.to_string(),
12063                        reason: reason.into(),
12064                    }
12065                }
12066            )*
12067        }
12068    };
12069}
12070
12071contrato_pair_value_reason_ctors! {
12072    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
12073    contrato_subject_invalid => ContratoSubjectInvalid { subject },
12074    contrato_slot_invalid => ContratoSlotInvalid { slot },
12075    contrato_wit_invalid => ContratoWitInvalid { wit },
12076}
12077
12078// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
12079// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
12080// caixa-only struct-variant wire-up sites at
12081// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
12082// `:contratos :para` arms of `ContratoMemberMissing`),
12083// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
12084// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
12085// and [`validate_no_self_membership`] (one site, the parent-`:nome`
12086// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
12087// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
12088// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
12089// three variants on `{ caixa: String }` at
12090// [`crate::SupervisorSpec::validate_children`] and
12091// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
12092// `SupervisorError` envelope, extending the same "one substrate primitive per
12093// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
12094// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
12095// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
12096// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
12097// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
12098// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
12099// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
12100// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
12101// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
12102// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
12103// variants on `{ nome, caminho }`), and
12104// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
12105// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
12106// peer three `AplicacaoError` sub-family folds already lifted here
12107// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
12108// [`aplicacao_field_reason_ctors!`] 981060b,
12109// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
12110// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
12111// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
12112// [`crate::LayoutError::missing_entry`] 1b09f9d,
12113// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
12114// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
12115//
12116// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
12117// at the per-`:contratos :de`/`:para` unknown-member arms, one on
12118// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
12119// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
12120// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
12121// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
12122// three-line struct-literal against a caller-side `&str` — the exact "same
12123// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
12124// bug, on the same altitude the peer `SupervisorError` /
12125// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
12126// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
12127// their sibling envelopes. The four variants share one `{ caixa: String }`
12128// shape, so the fold routes each wire-up site through one dispatch per typed
12129// variant.
12130//
12131// The macro below generates one `#[must_use]` inherent constructor per
12132// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
12133// wire-up site collapses onto one dispatch:
12134// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
12135// on the same `&str` fixture. The uniform one-field construction
12136// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
12137// than at every wire-up site. Every constructor is `#[must_use]` so a caller
12138// who mistakenly discards the constructed error trips a compile warning at
12139// the wire-up site.
12140//
12141// Every future consumer that wants to construct one of these four variants
12142// outside the current in-crate wire-up sites — a deferred
12143// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
12144// re-checking one added/renamed `:membros` entry against the sibling
12145// `:contratos` graph, a future `feira validate --membros` per-caixa admission
12146// verb re-checking each declared `:membros` entry's `:caixa` name against the
12147// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
12148// duplicate / self-referencing / unknown-membered `:contratos` entry against
12149// a cluster-local snapshot the M4 CR materializer projects — now reaches each
12150// variant through one call rather than re-inlining the three-line
12151// struct-literal in lockstep with the five in-crate wire-up sites.
12152macro_rules! aplicacao_caixa_only_ctors {
12153    ($($ctor:ident => $variant:ident),* $(,)?) => {
12154        impl AplicacaoError {
12155            $(
12156                #[doc = concat!(
12157                    "Construct an [`AplicacaoError::",
12158                    stringify!($variant),
12159                    "`] naming the offending `:membros :caixa` (or ",
12160                    "parent `:nome`, on the self-membership arm; or ",
12161                    "`:contratos :de`/`:para`, on the unknown-member ",
12162                    "arm). Folds the uniform `Self::",
12163                    stringify!($variant),
12164                    " { caixa: caixa.to_string() }` one-field ",
12165                    "struct-literal onto one substrate primitive so ",
12166                    "every wire-up on this variant reads through one ",
12167                    "dispatch rather than the pre-lift three-line ",
12168                    "open-coded struct-literal block."
12169                )]
12170                #[must_use]
12171                pub fn $ctor(caixa: &str) -> Self {
12172                    Self::$variant { caixa: caixa.to_string() }
12173                }
12174            )*
12175        }
12176    };
12177}
12178
12179aplicacao_caixa_only_ctors! {
12180    contrato_member_missing => ContratoMemberMissing,
12181    membro_versao_empty => MembroVersaoEmpty,
12182    membro_duplicate => MembroDuplicate,
12183    membro_is_self_aplicacao => MembroIsSelfAplicacao,
12184}
12185
12186// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
12187// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
12188// sites onto one substrate-primitive family per typed variant — the direct
12189// per-`:entrada :paths` value-shape sibling of the peer
12190// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
12191// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
12192// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
12193// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
12194// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
12195// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
12196// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
12197// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
12198// `:deps` envelope — every single-`String`-slot error family in caixa-core
12199// now reaches through one substrate primitive per typed variant.
12200//
12201// The three wire-up sites — one under [`validate_entrada_path`]'s
12202// leading-slash grammar arm (`EntradaPathNotAbsolute` against
12203// `path: &str`), one under the per-`:entrada :paths` loop's identical
12204// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
12205// and one under the per-`:entrada :paths` loop's dedup arm
12206// (`EntradaPathDuplicate` against the same `&String` via
12207// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
12208// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
12209// three-line struct-literal against a caller-side `&str` / `&String`, the
12210// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
12211// names as a bug. Every one of the compile-time guarantees in
12212// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
12213// start with `/` becomes a caixa-build error, not a Gateway API webhook
12214// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
12215// becomes a caixa-build error, not a silent last-writer-wins render) now
12216// routes through one dispatch per typed variant at every emit site.
12217//
12218// The macro below generates one `#[must_use]` inherent constructor per
12219// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
12220// every wire-up site onto one dispatch:
12221// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
12222// on the same `&str` fixture) or the `&String` sites through
12223// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
12224// construction (`path: path.to_string()`) is spelled once — inside the
12225// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
12226// a caller who mistakenly discards the constructed error trips a compile
12227// warning at the wire-up site.
12228//
12229// Every future consumer that wants to construct one of these two variants
12230// outside the current in-crate wire-up sites — a deferred
12231// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
12232// per-`:entrada :paths` re-check against a cluster-local Gateway API
12233// snapshot, a future `feira validate --entrada` per-caixa admission verb
12234// re-checking each declared `:paths` entry against the same axes, a
12235// per-tenant per-`Aplicacao` overlay resolver rejecting a
12236// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
12237// snapshot the M4 CR materializer projects — now reaches each variant
12238// through one call rather than re-inlining the three-line struct-literal in
12239// lockstep with the three in-crate wire-up sites.
12240macro_rules! aplicacao_path_only_ctors {
12241    ($($ctor:ident => $variant:ident),* $(,)?) => {
12242        impl AplicacaoError {
12243            $(
12244                #[doc = concat!(
12245                    "Construct an [`AplicacaoError::",
12246                    stringify!($variant),
12247                    "`] naming the offending `:entrada :paths` entry. ",
12248                    "Folds the uniform `Self::",
12249                    stringify!($variant),
12250                    " { path: path.to_string() }` one-field ",
12251                    "struct-literal onto one substrate primitive so ",
12252                    "every wire-up on this variant reads through one ",
12253                    "dispatch rather than the pre-lift three-line ",
12254                    "open-coded struct-literal block."
12255                )]
12256                #[must_use]
12257                pub fn $ctor(path: &str) -> Self {
12258                    Self::$variant { path: path.to_string() }
12259                }
12260            )*
12261        }
12262    };
12263}
12264
12265aplicacao_path_only_ctors! {
12266    entrada_path_not_absolute => EntradaPathNotAbsolute,
12267    entrada_path_duplicate => EntradaPathDuplicate,
12268}
12269
12270// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
12271// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
12272// substrate-primitive family per typed variant — the per-`:politicas` copy-
12273// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
12274// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
12275// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
12276// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
12277// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
12278// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
12279// the `String`-slot axis, and the peer per-`:politicas` cross-axis
12280// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
12281// carries at line 3064 on the same M3 mesh envelope.
12282//
12283// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
12284// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
12285// { <slot> }` one-line struct-literal closure against the caller-side
12286// `<slot>: <ty>` argument that the shared
12287// [`crate::render::require_positive_bounded_u32`] /
12288// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
12289// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
12290// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
12291// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
12292// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
12293// on line 3211) — the exact "same one-line struct-literal re-inlined at every
12294// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
12295// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
12296// been folded onto a substrate primitive.
12297//
12298// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
12299// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
12300// collapsing every wire-up onto either one direct dispatch
12301// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
12302// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
12303// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
12304// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
12305// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
12306// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
12307// constructor with matching arity and signature. The `const fn` qualifier
12308// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
12309// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
12310// per-variant `$field:ident` axis re-uses the enum's canonical field name so
12311// the generated ctor's parameter name matches every wire-up's local binding
12312// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
12313// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
12314// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
12315// warning at any wire-up that mistakenly discards the constructed error, on
12316// the same footing as every sibling `AplicacaoError` / `DepError` /
12317// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
12318// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
12319// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
12320// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
12321//
12322// Every future consumer that wants to construct one of these eight variants
12323// outside [`MeshPolicy::validate`] — a deferred
12324// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
12325// checking each `:politicas` axis against a cluster-local `:politicas` cap
12326// overlay, a future per-`:contratos`-edge `:politicas` override the
12327// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
12328// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
12329// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
12330// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
12331// a future `feira validate --politicas` per-caixa admission verb re-checking
12332// each declared per-axis value against the same bounds — now reaches each
12333// variant through one call rather than re-inlining the one-line struct-
12334// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
12335// which is exactly the invariant every prior ctor-macro lift already closed
12336// on its sibling envelope. Closes the last remaining per-`:politicas`
12337// per-axis `AplicacaoError` variant family that had not yet been folded onto
12338// a substrate primitive; the compound cross-axis variants
12339// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
12340// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
12341// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
12342macro_rules! aplicacao_policy_scalar_ctors {
12343    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
12344        impl AplicacaoError {
12345            $(
12346                #[doc = concat!(
12347                    "Construct an [`AplicacaoError::",
12348                    stringify!($variant),
12349                    "`] naming the offending per-`:politicas` `",
12350                    stringify!($field),
12351                    "` scalar. Folds the uniform `Self::",
12352                    stringify!($variant),
12353                    " { ",
12354                    stringify!($field),
12355                    " }` one-field `Copy`-pass-through struct-literal onto ",
12356                    "one substrate primitive so every per-axis wire-up on ",
12357                    "this variant reads through one dispatch — as a direct ",
12358                    "call (`AplicacaoError::",
12359                    stringify!($ctor),
12360                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
12361                    "the same `Copy`-`",
12362                    stringify!($ty),
12363                    "` fixture) or as a bare function pointer in the ",
12364                    "`impl FnOnce(",
12365                    stringify!($ty),
12366                    ") -> AplicacaoError` bracket-closure slot every ",
12367                    "`crate::render::require_positive_bounded_*` / ",
12368                    "`crate::render::require_positive_canonical_bounded_*` ",
12369                    "gate carries — rather than the pre-lift open-coded ",
12370                    "one-line closure over the same one-field struct-",
12371                    "literal. `const fn` preserves the `Copy`-pass-through's ",
12372                    "zero-runtime-work property verbatim."
12373                )]
12374                #[must_use]
12375                pub const fn $ctor($field: $ty) -> Self {
12376                    Self::$variant { $field }
12377                }
12378            )*
12379        }
12380    };
12381}
12382
12383aplicacao_policy_scalar_ctors! {
12384    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
12385    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
12386    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
12387    policy_breaker_max_failures_exceeds_cap =>
12388        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
12389    policy_breaker_window_not_canonical =>
12390        PolicyBreakerWindowNotCanonical { window: Duration },
12391    policy_breaker_window_exceeds_cap =>
12392        PolicyBreakerWindowExceedsCap { window: Duration },
12393    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
12394    policy_rate_limit_window_not_canonical =>
12395        PolicyRateLimitWindowNotCanonical { window: Duration },
12396}
12397
12398#[cfg(test)]
12399mod tests {
12400    use super::*;
12401
12402    fn membro(name: &str, ver: &str) -> Membro {
12403        Membro {
12404            caixa: name.into(),
12405            versao: ver.into(),
12406        }
12407    }
12408
12409    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
12410        WitContract {
12411            de: de.into(),
12412            para: para.into(),
12413            wit: "wasi:http/proxy".into(),
12414            endpoint: Some(ep.into()),
12415            subject: None,
12416            slot: None,
12417        }
12418    }
12419
12420    fn three_member_spec() -> AplicacaoSpec {
12421        AplicacaoSpec {
12422            membros: vec![
12423                membro("catalog", "^0.1"),
12424                membro("cart", "^0.1"),
12425                membro("payment", "^0.2"),
12426            ],
12427            contratos: vec![
12428                contract_http("cart", "catalog", "/products/:id"),
12429                contract_http("cart", "payment", "/charge"),
12430            ],
12431            politicas: MeshPolicy {
12432                timeout: Some(Duration::from_secs(30)),
12433                retries: Some(3),
12434                mtls_required: Some(true),
12435                ..Default::default()
12436            },
12437            placement: Placement {
12438                estrategia: PlacementStrategy::Replicated,
12439                clusters: vec!["rio".into(), "mar".into()],
12440                affinity: Some("data-locality".into()),
12441                shard_key: None,
12442            },
12443            entrada: Some(Entrada {
12444                host: "checkout.quero.cloud".into(),
12445                para: "cart".into(),
12446                paths: vec!["/api/cart".into(), "/api/products".into()],
12447                port: 8080,
12448            }),
12449        }
12450    }
12451
12452    #[test]
12453    fn happy_path_validates() {
12454        three_member_spec().validate().unwrap();
12455    }
12456
12457    #[test]
12458    fn rejects_empty_membros() {
12459        let mut s = three_member_spec();
12460        s.membros = vec![];
12461        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
12462    }
12463
12464    #[test]
12465    fn rejects_empty_membro_caixa() {
12466        // A `:caixa ""` entry has no name to render into programs.yaml
12467        // and no caixa.lisp to resolve at lacre time.
12468        let mut s = three_member_spec();
12469        s.membros[1].caixa = String::new();
12470        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
12471    }
12472
12473    #[test]
12474    fn rejects_empty_membro_versao() {
12475        // A `:versao ""` entry can't pin a semver constraint, so the
12476        // lacre pipeline fails far from the source.
12477        let mut s = three_member_spec();
12478        s.membros[2].versao = String::new();
12479        let err = s.validate().unwrap_err();
12480        assert!(
12481            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
12482            "got {err:?}"
12483        );
12484    }
12485
12486    #[test]
12487    fn rejects_duplicate_membro_caixa() {
12488        // Two `:membros` entries with the same `:caixa` collapse to one
12489        // node in the membership HashSet, which masks `:contratos`
12490        // membership errors and produces duplicate programs.yaml entries.
12491        let mut s = three_member_spec();
12492        s.membros.push(membro("cart", "^0.2"));
12493        let err = s.validate().unwrap_err();
12494        assert!(
12495            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
12496            "got {err:?}"
12497        );
12498    }
12499
12500    #[test]
12501    fn rejects_invalid_membro_versao_requirement() {
12502        // The fail-before-pass-after pin: a non-empty but malformed
12503        // semver requirement (`"^bad-version"`) silently passed
12504        // `validate()` on every pre-gate codebase because the prior
12505        // shape only refused the empty string. The parse failure
12506        // surfaced far downstream at lacre-resolve time with a
12507        // `semver::Error` that didn't name which `:membros` entry
12508        // carried the typo. The new gate moves the check to caixa-build
12509        // time at the source caixa.lisp.
12510        let mut s = three_member_spec();
12511        s.membros[2].versao = "^bad-version".into();
12512        let err = s.validate().unwrap_err();
12513        assert!(
12514            matches!(
12515                err,
12516                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
12517                    if caixa == "payment" && versao == "^bad-version"
12518            ),
12519            "got {err:?}"
12520        );
12521    }
12522
12523    #[test]
12524    fn rejects_membro_versao_with_double_caret_typo() {
12525        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
12526        // Cargo-shaped requirement on first glance but fails the parser
12527        // because semver doesn't accept stacked operators. Pin this
12528        // adjacent-shape footgun explicitly so a future relaxation that
12529        // accepts "looks-canonical-but-isn't" forms surfaces here.
12530        let mut s = three_member_spec();
12531        s.membros[0].versao = "^^0.1".into();
12532        let err = s.validate().unwrap_err();
12533        assert!(
12534            matches!(
12535                err,
12536                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
12537                    if caixa == "catalog" && versao == "^^0.1"
12538            ),
12539            "got {err:?}"
12540        );
12541    }
12542
12543    #[test]
12544    fn rejects_membro_versao_with_v_prefixed_tag() {
12545        // `"v0.1"` is the canonical "git-tag-shape leaking into the
12546        // semver requirement slot" typo — an author copies the
12547        // publish-side git-tag string verbatim into `:versao`, but
12548        // Cargo's semver parser rejects the leading `v` (only digits +
12549        // canonical operators are valid in the major-version
12550        // position). The gate's diagnostic names which member entry
12551        // carried the v-prefix so the fix is one edit, not a grep
12552        // through every member's `:versao`. (Note: bare `x`-glob
12553        // shorthands like `^0.1.x` are *accepted* by the semver crate
12554        // as an `*` wildcard on the patch axis — they're a Cargo-side
12555        // valid shape, not a typo, so the gate intentionally lets them
12556        // through.)
12557        let mut s = three_member_spec();
12558        s.membros[1].versao = "v0.1".into();
12559        let err = s.validate().unwrap_err();
12560        assert!(
12561            matches!(
12562                err,
12563                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
12564                    if caixa == "cart" && versao == "v0.1"
12565            ),
12566            "got {err:?}"
12567        );
12568    }
12569
12570    #[test]
12571    fn accepts_canonical_membro_versao_forms() {
12572        // The four Cargo-shaped requirement forms `:deps :versao`
12573        // already accepts via `crate::parse_requirement` must pass the
12574        // membros gate without re-validating at the resolver layer.
12575        // Pin every leg so a future tightening of the canonical set
12576        // surfaces here as a test failure.
12577        for form in [
12578            "^0.1",      // caret — minor-range pin (the most common shape)
12579            "~0.1.2",    // tilde — patch-range pin
12580            "0.1.0",     // exact — single-version pin
12581            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
12582            ">=0.1, <2", // multi-range — comma-separated comparators
12583        ] {
12584            let mut s = three_member_spec();
12585            for m in &mut s.membros {
12586                m.versao = form.into();
12587            }
12588            s.validate()
12589                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
12590        }
12591    }
12592
12593    #[test]
12594    fn membro_versao_empty_takes_precedence_over_invalid() {
12595        // Order pin: the existing `MembroVersaoEmpty` diagnostic
12596        // (which doesn't try to parse) fires before the new
12597        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
12598        // `:versao` keeps its narrower error message — `parse_requirement`
12599        // would also reject `""`, but the empty-string arm is the more
12600        // self-locating diagnostic for the author.
12601        let mut s = three_member_spec();
12602        s.membros[1].versao = String::new();
12603        let err = s.validate().unwrap_err();
12604        assert!(
12605            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
12606            "got {err:?}"
12607        );
12608    }
12609
12610    #[test]
12611    fn membro_versao_invalid_fires_before_duplicate_check() {
12612        // Order pin: a malformed requirement on a non-duplicate entry
12613        // surfaces *its own* diagnostic (which names the offending
12614        // `:versao` string), even when a later entry would otherwise
12615        // collapse onto an earlier name. The per-entry shape gate runs
12616        // inline before the duplicate-key insert, parallel to
12617        // `membros_validation_runs_before_contratos_membership_check`
12618        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
12619        let mut s = three_member_spec();
12620        s.membros[0].versao = "^bad".into();
12621        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
12622        let err = s.validate().unwrap_err();
12623        assert!(
12624            matches!(
12625                err,
12626                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
12627            ),
12628            "got {err:?}"
12629        );
12630    }
12631
12632    #[test]
12633    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
12634        // The diagnostic-shape pin: the error names the offending
12635        // `:versao` value verbatim so the author can grep their
12636        // caixa.lisp without re-running the build, and carries a
12637        // non-empty `reason` from `semver::VersionReq::parse` so the
12638        // parser's own wording flows through to the diagnostic.
12639        let mut s = three_member_spec();
12640        s.membros[2].versao = "not-a-req".into();
12641        let err = s.validate().unwrap_err();
12642        let AplicacaoError::MembroVersaoInvalid {
12643            caixa,
12644            versao,
12645            reason,
12646        } = err
12647        else {
12648            panic!("expected MembroVersaoInvalid, got other variant");
12649        };
12650        assert_eq!(caixa, "payment");
12651        assert_eq!(versao, "not-a-req");
12652        assert!(
12653            !reason.is_empty(),
12654            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
12655        );
12656    }
12657
12658    #[test]
12659    fn membro_versao_invalid_runs_before_contratos_check() {
12660        // A malformed `:versao` on any member must surface its own
12661        // diagnostic (which names *which* member to fix) before any
12662        // `:contratos` membership lookup raises `ContratoMemberMissing`.
12663        // The `:contratos` gate runs after `validate_membros`, so this
12664        // is structurally guaranteed — pin it explicitly so a future
12665        // refactor that reorders the gates surfaces here.
12666        let mut s = three_member_spec();
12667        s.membros[1].versao = "^^0.1".into();
12668        // Add a contrato whose `:para` doesn't exist — would normally
12669        // raise ContratoMemberMissing at the membership lookup, but
12670        // the membros gate must fire first.
12671        s.contratos
12672            .push(contract_http("cart", "phantom", "/never-reached"));
12673        let err = s.validate().unwrap_err();
12674        assert!(
12675            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
12676            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
12677        );
12678    }
12679
12680    #[test]
12681    fn membros_validation_runs_before_contratos_membership_check() {
12682        // If `:membros` carries a duplicate, the membership-collapse
12683        // would silently accept a `:contratos :para "phantom"` so long
12684        // as some entry hashes to "phantom". Pinning order: the
12685        // duplicate-membros error fires first, regardless of whether
12686        // contratos reference real members.
12687        let mut s = three_member_spec();
12688        s.membros = vec![
12689            membro("cart", "^0.1"),
12690            membro("cart", "^0.2"),
12691            membro("catalog", "^0.1"),
12692            membro("payment", "^0.1"),
12693        ];
12694        let err = s.validate().unwrap_err();
12695        assert!(
12696            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
12697            "got {err:?}"
12698        );
12699    }
12700
12701    #[test]
12702    fn distinct_membros_validate() {
12703        // Pin the happy-path: every `:membros` entry has a non-empty
12704        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
12705        // The fixture already satisfies this; this test makes the
12706        // invariant explicit so a future refactor of the fixture can't
12707        // silently break the guarantee.
12708        three_member_spec().validate().unwrap();
12709    }
12710
12711    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
12712
12713    #[test]
12714    fn rejects_membro_caixa_with_uppercase() {
12715        // The canonical "I copied the Servico's display name verbatim"
12716        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
12717        // but author tools often round-trip a TitleCase or CamelCase
12718        // identifier from an ADR or a sketch. Pin the diagnostic names
12719        // the offending name and suggests the lower-cased fix in one
12720        // edit, mirroring the `rejects_entrada_host_with_uppercase`
12721        // gate's shape (c7d05ec).
12722        let mut s = three_member_spec();
12723        s.membros[1].caixa = "Cart".into();
12724        let err = s.validate().unwrap_err();
12725        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12726            panic!("expected MembroCaixaInvalid, got other variant");
12727        };
12728        assert_eq!(caixa, "Cart");
12729        assert!(
12730            reason.contains("uppercase"),
12731            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12732        );
12733        assert!(
12734            reason.contains("\"cart\""),
12735            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
12736        );
12737    }
12738
12739    #[test]
12740    fn rejects_membro_caixa_with_underscore() {
12741        // The canonical "I'm thinking of a Python module / Postgres
12742        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
12743        // label schema. K8s rejects `metadata.name: my_cart` at admission
12744        // time with an opaque `field is invalid` (no source-citing
12745        // diagnostic). The gate moves it to caixa-build time.
12746        let mut s = three_member_spec();
12747        s.membros[0].caixa = "my_cart".into();
12748        let err = s.validate().unwrap_err();
12749        assert!(
12750            matches!(
12751                err,
12752                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12753                    if caixa == "my_cart" && reason.contains('_')
12754            ),
12755            "got {err:?}"
12756        );
12757    }
12758
12759    #[test]
12760    fn rejects_membro_caixa_with_dot() {
12761        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
12762        // subdomain — even though K8s `metadata.name` itself accepts
12763        // dots (DNS-1123 subdomain rule), this string also lands as a
12764        // K8s Service name (DNS-1035 label — no dots) and as a label
12765        // value on identity-based Cilium selectors. The strictest floor
12766        // among the use sites wins. The "I want to namespace my member
12767        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
12768        let mut s = three_member_spec();
12769        s.membros[2].caixa = "team.cart".into();
12770        let err = s.validate().unwrap_err();
12771        assert!(
12772            matches!(
12773                err,
12774                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12775                    if caixa == "team.cart" && reason.contains('.')
12776            ),
12777            "got {err:?}"
12778        );
12779    }
12780
12781    #[test]
12782    fn rejects_membro_caixa_with_leading_hyphen() {
12783        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
12784        // with an alphanumeric. The K8s apiserver rejects `-cart`
12785        // outright; the renderer would emit a `metadata.name: "-cart"`
12786        // that fails admission far from the source caixa.lisp.
12787        let mut s = three_member_spec();
12788        s.membros[0].caixa = "-cart".into();
12789        let err = s.validate().unwrap_err();
12790        assert!(
12791            matches!(
12792                err,
12793                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12794                    if caixa == "-cart" && reason.contains("start and end")
12795            ),
12796            "got {err:?}"
12797        );
12798    }
12799
12800    #[test]
12801    fn rejects_membro_caixa_with_trailing_hyphen() {
12802        // The symmetric arm of the boundary rule. Pin separately so
12803        // both ends of the label are covered against a future relaxation
12804        // that only checks one boundary.
12805        let mut s = three_member_spec();
12806        s.membros[1].caixa = "cart-".into();
12807        let err = s.validate().unwrap_err();
12808        assert!(
12809            matches!(
12810                err,
12811                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12812                    if caixa == "cart-"
12813            ),
12814            "got {err:?}"
12815        );
12816    }
12817
12818    #[test]
12819    fn rejects_membro_caixa_with_unicode() {
12820        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12821        // (`xn--…`) by the author before it reaches K8s. The byte-by-
12822        // byte ASCII validity check rejects multi-byte UTF-8 sequences
12823        // by the first byte that fails the `[a-z0-9-]` predicate.
12824        let mut s = three_member_spec();
12825        s.membros[2].caixa = "café".into();
12826        let err = s.validate().unwrap_err();
12827        assert!(
12828            matches!(
12829                err,
12830                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12831                    if caixa == "café"
12832            ),
12833            "got {err:?}"
12834        );
12835    }
12836
12837    #[test]
12838    fn rejects_membro_caixa_with_whitespace() {
12839        // Whitespace is the canonical "I pasted from a sketch / doc"
12840        // footgun. The apiserver rejects every `metadata.name` value
12841        // carrying whitespace; pin the gate fires at the right boundary.
12842        let mut s = three_member_spec();
12843        s.membros[0].caixa = "my cart".into();
12844        let err = s.validate().unwrap_err();
12845        assert!(
12846            matches!(
12847                err,
12848                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12849                    if caixa == "my cart"
12850            ),
12851            "got {err:?}"
12852        );
12853    }
12854
12855    #[test]
12856    fn rejects_membro_caixa_too_long() {
12857        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
12858        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
12859        // exactly. The gate's reason names both the cap and the actual
12860        // length so the author can shorten in one edit.
12861        let mut s = three_member_spec();
12862        let too_long = "a".repeat(64);
12863        s.membros[1].caixa = too_long.clone();
12864        let err = s.validate().unwrap_err();
12865        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12866            panic!("expected MembroCaixaInvalid");
12867        };
12868        assert_eq!(caixa, too_long);
12869        assert!(
12870            reason.contains("63") && reason.contains("64"),
12871            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
12872        );
12873    }
12874
12875    #[test]
12876    fn membro_caixa_max_length_validates() {
12877        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
12878        // so a future tightening (e.g. dropping to 62) surfaces here as
12879        // a regression, mirroring `entrada_host_max_length_validates`
12880        // (c7d05ec).
12881        let mut s = three_member_spec();
12882        s.membros[2].caixa = "a".repeat(63);
12883        s.entrada.as_mut().unwrap().para = "a".repeat(63);
12884        // remove contratos referencing the renamed member; they'd
12885        // raise ContratoMemberMissing otherwise
12886        s.contratos
12887            .retain(|c| c.de != "payment" && c.para != "payment");
12888        s.validate().unwrap();
12889    }
12890
12891    #[test]
12892    fn accepts_canonical_membro_caixa_forms() {
12893        // The DNS-1123 label shapes a caixa author is realistically
12894        // going to write: single-word lowercase, hyphen-joined, ending
12895        // in a digit-suffixed version (`cart-v2`), starting with a
12896        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
12897        // DNS-1035 which requires a letter at position 0), single-
12898        // character (`a` — boundary). Pin every leg so a future
12899        // tightening that bans (e.g.) digit-start identifiers surfaces
12900        // here.
12901        for form in [
12902            "checkout",
12903            "cart",
12904            "cart-v2",
12905            "a",
12906            "c0",
12907            "3rd-party-shim",
12908            "x-1-2-3-4",
12909        ] {
12910            let mut s = three_member_spec();
12911            // Renaming a member also requires updating downstream refs;
12912            // drop everything else and rebuild a minimal spec around
12913            // just the one renamed member.
12914            s.membros = vec![membro(form, "^0.1")];
12915            s.contratos = vec![];
12916            s.entrada = None;
12917            s.validate()
12918                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
12919        }
12920    }
12921
12922    #[test]
12923    fn membro_caixa_empty_takes_precedence_over_invalid() {
12924        // Order pin: the existing `MembroCaixaEmpty` diagnostic
12925        // (which doesn't try to parse) fires before the new
12926        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
12927        // `:caixa` keeps its narrower error message — the new gate
12928        // would also reject `""`, but the empty-string arm is the more
12929        // self-locating diagnostic for the author. Mirrors the
12930        // `entrada_host_empty_takes_precedence_over_invalid` pin
12931        // (c7d05ec).
12932        let mut s = three_member_spec();
12933        s.membros[1].caixa = String::new();
12934        let err = s.validate().unwrap_err();
12935        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
12936    }
12937
12938    #[test]
12939    fn membro_caixa_invalid_fires_before_versao_check() {
12940        // Order pin: an invalid-shape `:caixa` surfaces *its own*
12941        // diagnostic (which names the offending caixa name), even when
12942        // the same entry's `:versao` is also empty/invalid. The shape
12943        // gate runs first because the diagnostic is more self-locating —
12944        // an empty/invalid `:versao` on an invalid-shape caixa name is
12945        // a downstream-fix-after-the-caixa-rename concern.
12946        let mut s = three_member_spec();
12947        s.membros[1].caixa = "Cart".into();
12948        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
12949        let err = s.validate().unwrap_err();
12950        assert!(
12951            matches!(
12952                err,
12953                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
12954            ),
12955            "got {err:?}"
12956        );
12957    }
12958
12959    #[test]
12960    fn membro_caixa_invalid_fires_before_duplicate_check() {
12961        // Order pin: a malformed-shape `:caixa` on an earlier entry
12962        // surfaces *its own* diagnostic, even when a later entry would
12963        // otherwise collapse onto a duplicate name. The per-entry shape
12964        // gate runs inline before the duplicate-key insert, parallel
12965        // to `membro_versao_invalid_fires_before_duplicate_check`.
12966        let mut s = three_member_spec();
12967        s.membros[0].caixa = "Catalog".into();
12968        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
12969        let err = s.validate().unwrap_err();
12970        assert!(
12971            matches!(
12972                err,
12973                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
12974            ),
12975            "got {err:?}"
12976        );
12977    }
12978
12979    #[test]
12980    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
12981        // The diagnostic-shape pin: the error names the offending
12982        // `:caixa` value verbatim so the author can grep their
12983        // caixa.lisp without re-running the build, and carries a
12984        // non-empty `reason` naming the specific violation. Same
12985        // shape every typed-shape gate enshrines (c7d05ec's
12986        // `entrada_host_diagnostic_carries_offending_host`,
12987        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
12988        let mut s = three_member_spec();
12989        s.membros[2].caixa = "BAD_NAME".into();
12990        let err = s.validate().unwrap_err();
12991        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12992            panic!("expected MembroCaixaInvalid");
12993        };
12994        assert_eq!(caixa, "BAD_NAME");
12995        assert!(
12996            !reason.is_empty(),
12997            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
12998        );
12999    }
13000
13001    #[test]
13002    fn rejects_contrato_with_unknown_de() {
13003        let mut s = three_member_spec();
13004        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13005        let err = s.validate().unwrap_err();
13006        assert!(
13007            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
13008        );
13009    }
13010
13011    #[test]
13012    fn rejects_contrato_with_unknown_para() {
13013        let mut s = three_member_spec();
13014        s.contratos.push(contract_http("cart", "phantom", "/x"));
13015        let err = s.validate().unwrap_err();
13016        assert!(
13017            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
13018        );
13019    }
13020
13021    #[test]
13022    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
13023        // The read-path pin: the phantom-`:de` refusal arm's
13024        // `ContratoMemberMissing.caixa` carrier must be observed through
13025        // the lifted [`WitContract::source`] accessor, not the raw
13026        // `.de.clone()` field-access `String`-carry. Peer of the sibling
13027        // per-`:contratos` self-loop arm's `.source().to_string()` /
13028        // `.world_ref().to_string()` `String`-carry sites the earlier
13029        // convergence lifted onto the same accessor pair. A future
13030        // silent detour that reintroduced the raw `.de.clone()` at the
13031        // wrap envelope while the shape-gate and membership lookup
13032        // routed through the accessor would surface here as a byte-equal
13033        // miss between the fired diagnostic's `caixa:` field and the
13034        // offending edge's `.source()` — pinning the accessor as the
13035        // sole read path across the phantom-name refusal arm's arg +
13036        // wrap-envelope emit surface.
13037        let mut s = three_member_spec();
13038        let phantom = contract_http("phantom", "catalog", "/x");
13039        s.contratos.push(phantom.clone());
13040        let err = s.validate().unwrap_err();
13041        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
13042            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
13043        };
13044        assert_eq!(
13045            caixa,
13046            phantom.source(),
13047            "ContratoMemberMissing.caixa on the phantom-:de arm must \
13048             byte-equal WitContract::source — the wrap envelope must \
13049             route through the lifted accessor rather than the raw \
13050             .de.clone() field-access String-carry"
13051        );
13052    }
13053
13054    #[test]
13055    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
13056        // The symmetric read-path pin on the `:para` phantom-name
13057        // refusal arm — same shape as the sibling `:de` pin above but
13058        // on the callee-Servico axis. Pins the wrap envelope's
13059        // `caixa:` field is observed through the lifted
13060        // [`WitContract::destination`] accessor, not the raw
13061        // `.para.clone()` field-access `String`-carry.
13062        let mut s = three_member_spec();
13063        let phantom = contract_http("cart", "phantom", "/x");
13064        s.contratos.push(phantom.clone());
13065        let err = s.validate().unwrap_err();
13066        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
13067            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
13068        };
13069        assert_eq!(
13070            caixa,
13071            phantom.destination(),
13072            "ContratoMemberMissing.caixa on the phantom-:para arm must \
13073             byte-equal WitContract::destination — the wrap envelope \
13074             must route through the lifted accessor rather than the raw \
13075             .para.clone() field-access String-carry"
13076        );
13077    }
13078
13079    #[test]
13080    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
13081        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
13082        // refusal arm — the `validate_contrato_caixa` arg must be
13083        // observed through the lifted [`WitContract::source`] accessor,
13084        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
13085        // value routes through the shared
13086        // [`crate::render::require_valid_dns_1123_label`] floor with the
13087        // accessor-projected value; the fired
13088        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
13089        // the offending edge's `.source()`, pinning that the arg + the
13090        // downstream `caixa: caixa.to_string()` wrap route through the
13091        // same accessor's read path.
13092        let mut s = three_member_spec();
13093        let malformed = contract_http("BAD_NAME", "catalog", "/x");
13094        s.contratos.push(malformed.clone());
13095        let err = s.validate().unwrap_err();
13096        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
13097            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
13098        };
13099        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
13100        assert_eq!(
13101            caixa,
13102            malformed.source(),
13103            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
13104             byte-equal WitContract::source — the shape-gate arg + wrap \
13105             envelope must route through the lifted accessor rather \
13106             than the raw &c.de &String-borrow"
13107        );
13108    }
13109
13110    #[test]
13111    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
13112        // Symmetric arm to the sibling `:de` malformed-shape pin above,
13113        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
13114        // route through the lifted [`WitContract::destination`]
13115        // accessor. `:para` runs after the `:de` shape gate in the
13116        // canonical edge-direction order, so the `:de` value must be
13117        // well-shaped for the `:para` gate to fire — the `cart` :de is
13118        // canonical.
13119        let mut s = three_member_spec();
13120        let malformed = contract_http("cart", "BAD_NAME", "/x");
13121        s.contratos.push(malformed.clone());
13122        let err = s.validate().unwrap_err();
13123        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
13124            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
13125        };
13126        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
13127        assert_eq!(
13128            caixa,
13129            malformed.destination(),
13130            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
13131             byte-equal WitContract::destination — the shape-gate arg + \
13132             wrap envelope must route through the lifted accessor \
13133             rather than the raw &c.para &String-borrow"
13134        );
13135    }
13136
13137    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
13138
13139    #[test]
13140    fn rejects_contrato_de_empty() {
13141        // `:de ""` previously fell through to `ContratoMemberMissing`
13142        // (with `caixa: ""`) because the validated `:membros :caixa`
13143        // set never contains the empty string. The narrower
13144        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
13145        // the offending slot.
13146        let mut s = three_member_spec();
13147        s.contratos.push(contract_http("", "catalog", "/x"));
13148        let err = s.validate().unwrap_err();
13149        assert_eq!(
13150            err,
13151            AplicacaoError::ContratoCaixaEmpty {
13152                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
13153            },
13154            "got {err:?}"
13155        );
13156    }
13157
13158    #[test]
13159    fn rejects_contrato_para_empty() {
13160        // Symmetric arm to `:de ""` — `:para ""` previously fell
13161        // through to `ContratoMemberMissing { caixa: "" }`.
13162        let mut s = three_member_spec();
13163        s.contratos.push(contract_http("cart", "", "/x"));
13164        let err = s.validate().unwrap_err();
13165        assert_eq!(
13166            err,
13167            AplicacaoError::ContratoCaixaEmpty {
13168                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
13169            },
13170            "got {err:?}"
13171        );
13172    }
13173
13174    #[test]
13175    fn rejects_contrato_de_with_uppercase() {
13176        // The canonical "I copied the Servico's TitleCase display
13177        // name from an ADR" typo. Until this gate landed `:de "Cart"`
13178        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
13179        // as "this caixa isn't in `:membros`" when the root cause is
13180        // "this `:de` value's shape can never legitimately match a
13181        // validated member (DNS-1123 labels are lowercase)". The
13182        // narrower diagnostic names the offending slot, the value
13183        // verbatim, and the parser-shaped reason.
13184        let mut s = three_member_spec();
13185        s.contratos.push(contract_http("Cart", "catalog", "/x"));
13186        let err = s.validate().unwrap_err();
13187        let AplicacaoError::ContratoCaixaInvalid {
13188            slot,
13189            caixa,
13190            reason,
13191        } = err
13192        else {
13193            panic!("expected ContratoCaixaInvalid, got other variant");
13194        };
13195        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
13196        assert_eq!(caixa, "Cart");
13197        assert!(
13198            reason.contains("uppercase"),
13199            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
13200        );
13201    }
13202
13203    #[test]
13204    fn rejects_contrato_para_with_underscore() {
13205        // The canonical "I'm thinking of a Python module" leak —
13206        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
13207        // Pin the `:para` axis surfaces the same diagnostic shape as
13208        // the `:de` axis on the underscore violation.
13209        let mut s = three_member_spec();
13210        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
13211        let err = s.validate().unwrap_err();
13212        assert!(
13213            matches!(
13214                err,
13215                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
13216                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
13217            ),
13218            "got {err:?}"
13219        );
13220    }
13221
13222    #[test]
13223    fn rejects_contrato_de_with_dot() {
13224        // A `:contratos :de` value is a single DNS-1123 *label*, not
13225        // a subdomain — mirroring the `:membros :caixa` floor. The
13226        // strictest floor among the use sites wins.
13227        let mut s = three_member_spec();
13228        s.contratos
13229            .push(contract_http("team.cart", "catalog", "/x"));
13230        let err = s.validate().unwrap_err();
13231        assert!(
13232            matches!(
13233                err,
13234                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
13235                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
13236            ),
13237            "got {err:?}"
13238        );
13239    }
13240
13241    #[test]
13242    fn rejects_contrato_para_with_unicode() {
13243        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
13244        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
13245        // validity check rejects multi-byte UTF-8 by the first
13246        // non-`[a-z0-9-]` byte.
13247        let mut s = three_member_spec();
13248        s.contratos.push(contract_http("cart", "café", "/x"));
13249        let err = s.validate().unwrap_err();
13250        assert!(
13251            matches!(
13252                err,
13253                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
13254                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
13255            ),
13256            "got {err:?}"
13257        );
13258    }
13259
13260    #[test]
13261    fn rejects_contrato_de_with_leading_hyphen() {
13262        // DNS-1123 boundary rule: labels must start and end with an
13263        // alphanumeric. K8s rejects `-cart` outright; the narrower
13264        // shape diagnostic now names the violation at caixa-build
13265        // time rather than the misframed membership-lookup arm.
13266        let mut s = three_member_spec();
13267        s.contratos.push(contract_http("-cart", "catalog", "/x"));
13268        let err = s.validate().unwrap_err();
13269        assert!(
13270            matches!(
13271                err,
13272                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
13273                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
13274            ),
13275            "got {err:?}"
13276        );
13277    }
13278
13279    #[test]
13280    fn contrato_de_empty_takes_precedence_over_invalid() {
13281        // Order pin: the `ContratoCaixaEmpty` arm fires before the
13282        // `ContratoCaixaInvalid` parse-side arm — same empty-first
13283        // cascade `validate_membro_caixa` / `validate_placement_cluster`
13284        // / `validate_entrada_host` already establish on their peer
13285        // name axes. The empty string is a structurally distinct
13286        // authoring footgun (the author left the field blank, vs.
13287        // typed a malformed value), so it gets its own diagnostic.
13288        let mut s = three_member_spec();
13289        s.contratos.push(contract_http("", "catalog", "/x"));
13290        let err = s.validate().unwrap_err();
13291        assert_eq!(
13292            err,
13293            AplicacaoError::ContratoCaixaEmpty {
13294                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
13295            }
13296        );
13297    }
13298
13299    #[test]
13300    fn contrato_de_shape_fires_before_para_shape() {
13301        // Per-axis order pin: within one `:contratos` entry, the `:de`
13302        // shape gate fires before the `:para` shape gate — same
13303        // edge-direction order the existing `ContratoMemberMissing` /
13304        // `ContratoSelfLoop` / target-dispatch checks use, so the
13305        // diagnostic for a contract with both `:de` and `:para`
13306        // malformed is stable. Authors fixing the surfaced `:de`
13307        // first will see `:para`'s diagnostic on re-run.
13308        let mut s = three_member_spec();
13309        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
13310        let err = s.validate().unwrap_err();
13311        assert!(
13312            matches!(
13313                err,
13314                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
13315                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
13316            ),
13317            "got {err:?}"
13318        );
13319    }
13320
13321    #[test]
13322    fn contrato_shape_fires_before_membership_lookup() {
13323        // The load-bearing pin: an invalid-shape `:de` surfaces its
13324        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
13325        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
13326        // an invalid-shape `:de` could never legitimately match any
13327        // member — the prior `ContratoMemberMissing` diagnostic was
13328        // a structural impossibility framed as a graph-membership
13329        // failure. The shape gate now routes every such input through
13330        // the narrower self-locating diagnostic.
13331        let mut s = three_member_spec();
13332        s.contratos.push(contract_http("Cart", "catalog", "/x"));
13333        let err = s.validate().unwrap_err();
13334        assert!(
13335            matches!(
13336                err,
13337                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
13338            ),
13339            "got {err:?}"
13340        );
13341        // And the symmetric case: an invalid-shape `:para` surfaces
13342        // its own diagnostic too, even when `:de` is well-shaped.
13343        let mut s = three_member_spec();
13344        s.contratos.push(contract_http("cart", "Catalog", "/x"));
13345        let err = s.validate().unwrap_err();
13346        assert!(
13347            matches!(
13348                err,
13349                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
13350            ),
13351            "got {err:?}"
13352        );
13353    }
13354
13355    #[test]
13356    fn contrato_shape_fires_before_self_edge_check() {
13357        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
13358        // bugs: the shape violation (uppercase) and the self-edge
13359        // violation. The narrower per-axis shape diagnostic surfaces
13360        // first because fixing the shape may reveal that the author
13361        // also meant to point `:para` at a different member — the
13362        // self-edge framing is only useful once both endpoints have
13363        // valid shape.
13364        let mut s = three_member_spec();
13365        s.contratos.push(contract_http("Cart", "Cart", "/x"));
13366        let err = s.validate().unwrap_err();
13367        assert!(
13368            matches!(
13369                err,
13370                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
13371                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
13372            ),
13373            "got {err:?}"
13374        );
13375    }
13376
13377    #[test]
13378    fn contrato_well_shaped_phantom_still_raises_member_missing() {
13379        // Strict-improvement pin: a well-shaped `:de` that simply
13380        // isn't in `:membros` (a phantom reference — author meant
13381        // to add the member but didn't, or renamed and missed an
13382        // update) still surfaces `ContratoMemberMissing`, unchanged.
13383        // The shape gate only intercepts inputs that could never
13384        // legitimately match a validated member; legitimately-shaped
13385        // phantom references remain on the graph-membership axis.
13386        let mut s = three_member_spec();
13387        s.contratos
13388            .push(contract_http("phantom-shim", "catalog", "/x"));
13389        let err = s.validate().unwrap_err();
13390        assert!(
13391            matches!(
13392                err,
13393                AplicacaoError::ContratoMemberMissing { ref caixa }
13394                    if caixa == "phantom-shim"
13395            ),
13396            "got {err:?}"
13397        );
13398    }
13399
13400    #[test]
13401    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
13402        // The diagnostic-shape pin: the error names the offending
13403        // slot (`:de` or `:para`) verbatim and the offending value
13404        // verbatim plus a non-empty parser-shaped reason, so the
13405        // author can grep their caixa.lisp for `:de "<name>"` /
13406        // `:para "<name>"` and fix it in one edit. Same diagnostic
13407        // shape as `MembroCaixaInvalid` (3f9d7a0) and
13408        // `PlacementClusterInvalid` (6c8c00b).
13409        let mut s = three_member_spec();
13410        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
13411        let err = s.validate().unwrap_err();
13412        let AplicacaoError::ContratoCaixaInvalid {
13413            slot,
13414            caixa,
13415            reason,
13416        } = err
13417        else {
13418            panic!("expected ContratoCaixaInvalid, got {err:?}");
13419        };
13420        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
13421        assert_eq!(caixa, "BAD_NAME");
13422        assert!(
13423            !reason.is_empty(),
13424            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
13425        );
13426    }
13427
13428    #[test]
13429    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
13430        // Scalar-value pin: the two author-facing kebab-case labels the
13431        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
13432        // admits on the `:contratos` per-entry endpoint-shape axis,
13433        // one arm per typed sub-slot. Mirrors the peer scalar-value
13434        // pin the sibling top-level M2 / M3 / Supervisor
13435        // author-facing-label consts carry
13436        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
13437        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
13438        // slot itself), so every altitude of the typed-slot algebra
13439        // shares the same "one canonical byte-string per arm"
13440        // discipline. A future rebrand (`:de` → `:from` matching the
13441        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
13442        // sibling, `:para` → `:to` matching the same, or
13443        // `:de`/`:para` → `:source`/`:target` matching the WIT
13444        // world's `import`/`export` half-vocabulary) lands as an
13445        // edit to exactly one const, and every consumer that reaches
13446        // for the label picks it up at build time rather than at
13447        // runtime as a downstream `ContratoCaixaEmpty` /
13448        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
13449        // diagnostic mismatch far from the rename's commit.
13450        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
13451        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
13452    }
13453
13454    #[test]
13455    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
13456        // Production-through-const pin: the two per-axis labels the
13457        // per-`:contratos` entry endpoint-shape gate at
13458        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
13459        // argument to [`validate_contrato_caixa`] route through the
13460        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
13461        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
13462        // future rebrand that reaches the const but not the gate (or
13463        // vice versa) surfaces here at build time rather than at
13464        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
13465        // `slot: <stale-kebab-case>` diagnostic far from the rename's
13466        // commit. Mirror of the peer
13467        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
13468        // pin (882f498) on the sibling M3 top-level slot axis.
13469        let mut s = three_member_spec();
13470        s.contratos.push(contract_http("", "catalog", "/x"));
13471        assert_eq!(
13472            s.validate().unwrap_err(),
13473            AplicacaoError::ContratoCaixaEmpty {
13474                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
13475            }
13476        );
13477        let mut s = three_member_spec();
13478        s.contratos.push(contract_http("cart", "", "/x"));
13479        assert_eq!(
13480            s.validate().unwrap_err(),
13481            AplicacaoError::ContratoCaixaEmpty {
13482                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
13483            }
13484        );
13485    }
13486
13487    #[test]
13488    fn accepts_canonical_contrato_caixa_forms() {
13489        // The DNS-1123 label shapes a caixa author is realistically
13490        // going to write on a `:contratos :de` / `:para`. Pin every
13491        // leg so a future tightening that bans (e.g.) digit-start
13492        // identifiers surfaces here, mirroring
13493        // `accepts_canonical_membro_caixa_forms` on the peer name
13494        // axis.
13495        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
13496            let mut s = three_member_spec();
13497            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
13498            s.contratos = vec![contract_http("checkout", form, "/x")];
13499            s.entrada = None;
13500            s.validate().unwrap_or_else(|e| {
13501                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
13502            });
13503
13504            let mut s = three_member_spec();
13505            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
13506            s.contratos = vec![contract_http(form, "catalog", "/x")];
13507            s.entrada = None;
13508            s.validate().unwrap_or_else(|e| {
13509                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
13510            });
13511        }
13512    }
13513
13514    #[test]
13515    fn rejects_empty_wit() {
13516        let mut s = three_member_spec();
13517        s.contratos.push(WitContract {
13518            de: "cart".into(),
13519            para: "catalog".into(),
13520            wit: String::new(),
13521            endpoint: None,
13522            subject: None,
13523            slot: None,
13524        });
13525        let err = s.validate().unwrap_err();
13526        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
13527    }
13528
13529    #[test]
13530    fn rejects_entrada_to_unknown_member() {
13531        let mut s = three_member_spec();
13532        s.entrada.as_mut().unwrap().para = "phantom".into();
13533        assert!(matches!(
13534            s.validate().unwrap_err(),
13535            AplicacaoError::EntradaMemberMissing { .. }
13536        ));
13537    }
13538
13539    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
13540
13541    #[test]
13542    fn rejects_entrada_para_empty() {
13543        // `:para ""` previously fell through to
13544        // `EntradaMemberMissing { para: "" }` because the validated
13545        // `:membros :caixa` set never contains the empty string. The
13546        // narrower `EntradaParaEmpty` diagnostic now names the
13547        // offending slot directly — same empty-first cascade
13548        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
13549        // `ContratoCaixaEmpty` establish on the peer name axes.
13550        let mut s = three_member_spec();
13551        s.entrada.as_mut().unwrap().para = String::new();
13552        let err = s.validate().unwrap_err();
13553        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
13554    }
13555
13556    #[test]
13557    fn rejects_entrada_para_with_uppercase() {
13558        // The canonical "I copied the Servico's TitleCase display
13559        // name from an ADR" typo. Until this gate landed `:para "Cart"`
13560        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
13561        // as "this caixa isn't in `:membros`" when the root cause is
13562        // "this `:para` value's shape can never legitimately match a
13563        // validated member (DNS-1123 labels are lowercase)". The
13564        // narrower diagnostic names the value verbatim plus the
13565        // parser-shaped reason.
13566        let mut s = three_member_spec();
13567        s.entrada.as_mut().unwrap().para = "Cart".into();
13568        let err = s.validate().unwrap_err();
13569        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
13570            panic!("expected EntradaParaInvalid, got other variant");
13571        };
13572        assert_eq!(para, "Cart");
13573        assert!(
13574            reason.contains("uppercase"),
13575            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
13576        );
13577    }
13578
13579    #[test]
13580    fn rejects_entrada_para_with_underscore() {
13581        // The canonical "I'm thinking of a Python module" leak —
13582        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
13583        let mut s = three_member_spec();
13584        s.entrada.as_mut().unwrap().para = "my_cart".into();
13585        let err = s.validate().unwrap_err();
13586        assert!(
13587            matches!(
13588                err,
13589                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13590                    if para == "my_cart" && reason.contains('_')
13591            ),
13592            "got {err:?}"
13593        );
13594    }
13595
13596    #[test]
13597    fn rejects_entrada_para_with_dot() {
13598        // An `:entrada :para` value is a single DNS-1123 *label*, not
13599        // a subdomain — mirroring the `:membros :caixa` floor. The
13600        // strictest floor among the use sites wins.
13601        let mut s = three_member_spec();
13602        s.entrada.as_mut().unwrap().para = "team.cart".into();
13603        let err = s.validate().unwrap_err();
13604        assert!(
13605            matches!(
13606                err,
13607                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13608                    if para == "team.cart" && reason.contains('.')
13609            ),
13610            "got {err:?}"
13611        );
13612    }
13613
13614    #[test]
13615    fn rejects_entrada_para_with_unicode() {
13616        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
13617        // (`xn--…`) before it reaches K8s.
13618        let mut s = three_member_spec();
13619        s.entrada.as_mut().unwrap().para = "café".into();
13620        let err = s.validate().unwrap_err();
13621        assert!(
13622            matches!(
13623                err,
13624                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
13625            ),
13626            "got {err:?}"
13627        );
13628    }
13629
13630    #[test]
13631    fn rejects_entrada_para_with_leading_hyphen() {
13632        // DNS-1123 boundary rule: labels must start and end with an
13633        // alphanumeric. K8s rejects `-cart` outright.
13634        let mut s = three_member_spec();
13635        s.entrada.as_mut().unwrap().para = "-cart".into();
13636        let err = s.validate().unwrap_err();
13637        assert!(
13638            matches!(
13639                err,
13640                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13641                    if para == "-cart" && reason.contains("start and end")
13642            ),
13643            "got {err:?}"
13644        );
13645    }
13646
13647    #[test]
13648    fn rejects_entrada_para_with_trailing_hyphen() {
13649        // Symmetric boundary arm.
13650        let mut s = three_member_spec();
13651        s.entrada.as_mut().unwrap().para = "cart-".into();
13652        let err = s.validate().unwrap_err();
13653        assert!(
13654            matches!(
13655                err,
13656                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13657                    if para == "cart-" && reason.contains("start and end")
13658            ),
13659            "got {err:?}"
13660        );
13661    }
13662
13663    #[test]
13664    fn rejects_entrada_para_too_long() {
13665        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
13666        // bytes per label. K8s rejects longer names at admission on
13667        // every `metadata.name` axis.
13668        let mut s = three_member_spec();
13669        s.entrada.as_mut().unwrap().para = "a".repeat(64);
13670        let err = s.validate().unwrap_err();
13671        assert!(
13672            matches!(
13673                err,
13674                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13675                    if para.len() == 64 && reason.contains("max length")
13676            ),
13677            "got {err:?}"
13678        );
13679    }
13680
13681    #[test]
13682    fn entrada_para_empty_takes_precedence_over_invalid() {
13683        // Order pin: the `EntradaParaEmpty` arm fires before the
13684        // `EntradaParaInvalid` parse-side arm — same empty-first
13685        // cascade `validate_membro_caixa` / `validate_placement_cluster`
13686        // / `validate_contrato_caixa` already establish.
13687        let mut s = three_member_spec();
13688        s.entrada.as_mut().unwrap().para = String::new();
13689        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
13690    }
13691
13692    #[test]
13693    fn entrada_para_shape_fires_before_membership_lookup() {
13694        // The load-bearing pin: an invalid-shape `:para` surfaces its
13695        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
13696        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
13697        // an invalid-shape `:para` could never legitimately match any
13698        // member — the prior `EntradaMemberMissing` diagnostic framed
13699        // a structural impossibility as a graph-membership failure.
13700        let mut s = three_member_spec();
13701        s.entrada.as_mut().unwrap().para = "Cart".into();
13702        let err = s.validate().unwrap_err();
13703        assert!(
13704            matches!(
13705                err,
13706                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
13707            ),
13708            "got {err:?}"
13709        );
13710    }
13711
13712    #[test]
13713    fn entrada_para_shape_fires_before_host_gate() {
13714        // Per-`:entrada` order pin: the `:para` shape gate fires
13715        // before the `:host` gate, mirroring the existing
13716        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
13717        // ordering where the member-lookup arm preceded the host gate.
13718        // The shape gate slots ahead of that, so a malformed `:para`
13719        // surfaces its own diagnostic even when `:host` is also wrong.
13720        let mut s = three_member_spec();
13721        let e = s.entrada.as_mut().unwrap();
13722        e.para = "Cart".into();
13723        e.host = "BAD HOST".into();
13724        let err = s.validate().unwrap_err();
13725        assert!(
13726            matches!(
13727                err,
13728                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
13729            ),
13730            "got {err:?}"
13731        );
13732    }
13733
13734    #[test]
13735    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
13736        // Strict-improvement pin: a well-shaped `:para` that simply
13737        // isn't in `:membros` (a phantom reference — author meant to
13738        // add the member but didn't, or renamed and missed an
13739        // update) still surfaces `EntradaMemberMissing`, unchanged.
13740        // The shape gate only intercepts inputs that could never
13741        // legitimately match a validated member.
13742        let mut s = three_member_spec();
13743        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
13744        let err = s.validate().unwrap_err();
13745        assert!(
13746            matches!(
13747                err,
13748                AplicacaoError::EntradaMemberMissing { ref para }
13749                    if para == "phantom-shim"
13750            ),
13751            "got {err:?}"
13752        );
13753    }
13754
13755    #[test]
13756    fn entrada_para_invalid_diagnostic_carries_offending_para() {
13757        // The diagnostic-shape pin: the error names the offending
13758        // `:para` value verbatim plus a non-empty parser-shaped
13759        // reason, so the author can grep their caixa.lisp for
13760        // `:para "<name>"` and fix it in one edit. Same diagnostic
13761        // shape as `MembroCaixaInvalid` (3f9d7a0),
13762        // `PlacementClusterInvalid` (6c8c00b), and
13763        // `ContratoCaixaInvalid` (8d5af6b).
13764        let mut s = three_member_spec();
13765        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
13766        let err = s.validate().unwrap_err();
13767        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
13768            panic!("expected EntradaParaInvalid, got {err:?}");
13769        };
13770        assert_eq!(para, "BAD_NAME");
13771        assert!(
13772            !reason.is_empty(),
13773            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
13774        );
13775    }
13776
13777    #[test]
13778    fn accepts_canonical_entrada_para_forms() {
13779        // Positive-control sweep covering the DNS-1123 label shapes a
13780        // caixa author is realistically going to write on `:entrada
13781        // :para`. Pin every leg so a future tightening that bans
13782        // (e.g.) digit-start identifiers surfaces here, mirroring
13783        // `accepts_canonical_membro_caixa_forms` and
13784        // `accepts_canonical_contrato_caixa_forms` on the peer name
13785        // axes.
13786        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
13787            let mut s = three_member_spec();
13788            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
13789            s.contratos = vec![contract_http(form, "catalog", "/x")];
13790            s.entrada = Some(Entrada {
13791                host: "checkout.quero.cloud".into(),
13792                para: form.into(),
13793                paths: vec!["/api".into()],
13794                port: 8080,
13795            });
13796            s.validate().unwrap_or_else(|e| {
13797                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
13798            });
13799        }
13800    }
13801
13802    #[test]
13803    fn rejects_replicated_without_clusters() {
13804        let mut s = three_member_spec();
13805        s.placement.clusters = vec![];
13806        assert!(matches!(
13807            s.validate().unwrap_err(),
13808            AplicacaoError::PlacementWithoutClusters { .. }
13809        ));
13810    }
13811
13812    #[test]
13813    fn rejects_sharded_without_key() {
13814        let mut s = three_member_spec();
13815        s.placement.estrategia = PlacementStrategy::Sharded;
13816        s.placement.shard_key = None;
13817        s.placement.clusters = vec!["rio".into()];
13818        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
13819    }
13820
13821    #[test]
13822    fn sharded_with_key_validates() {
13823        let mut s = three_member_spec();
13824        s.placement.estrategia = PlacementStrategy::Sharded;
13825        s.placement.shard_key = Some("$tenantId".into());
13826        s.validate().unwrap();
13827    }
13828
13829    #[test]
13830    fn round_trip_via_json_preserves_shape() {
13831        let s = three_member_spec();
13832        let json = serde_json::to_string(&s.membros).unwrap();
13833        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
13834        assert_eq!(back, s.membros);
13835
13836        let json = serde_json::to_string(&s.contratos).unwrap();
13837        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
13838        assert_eq!(back, s.contratos);
13839
13840        let json = serde_json::to_string(&s.placement).unwrap();
13841        let back: Placement = serde_json::from_str(&json).unwrap();
13842        assert_eq!(back, s.placement);
13843
13844        let json = serde_json::to_string(&s.entrada).unwrap();
13845        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
13846        assert_eq!(back, s.entrada);
13847    }
13848
13849    #[test]
13850    fn rate_limit_round_trip_seconds() {
13851        let policy = MeshPolicy {
13852            rate_limit: Some(RateLimit {
13853                rate: 100,
13854                window: Duration::from_secs(1),
13855            }),
13856            ..Default::default()
13857        };
13858        let json = serde_json::to_string(&policy).unwrap();
13859        assert!(json.contains("\"100/s\""));
13860        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13861        assert_eq!(back.rate_limit.unwrap().rate, 100);
13862        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
13863    }
13864
13865    #[test]
13866    fn rate_limit_round_trip_minutes() {
13867        let policy = MeshPolicy {
13868            rate_limit: Some(RateLimit {
13869                rate: 5000,
13870                window: Duration::from_secs(60),
13871            }),
13872            ..Default::default()
13873        };
13874        let json = serde_json::to_string(&policy).unwrap();
13875        assert!(json.contains("\"5000/m\""));
13876    }
13877
13878    #[test]
13879    fn circuit_breaker_round_trip() {
13880        let policy = MeshPolicy {
13881            circuit_breaker: Some(CircuitBreaker {
13882                max_failures: 5,
13883                window: Duration::from_secs(60),
13884            }),
13885            ..Default::default()
13886        };
13887        let json = serde_json::to_string(&policy).unwrap();
13888        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13889        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
13890        assert_eq!(
13891            back.circuit_breaker.unwrap().window,
13892            Duration::from_secs(60)
13893        );
13894    }
13895
13896    #[test]
13897    fn rejects_http_contrato_without_endpoint() {
13898        let mut s = three_member_spec();
13899        s.contratos.push(WitContract {
13900            de: "cart".into(),
13901            para: "catalog".into(),
13902            wit: "wasi:http/proxy".into(),
13903            endpoint: None,
13904            subject: None,
13905            slot: None,
13906        });
13907        let err = s.validate().unwrap_err();
13908        assert!(matches!(
13909            err,
13910            AplicacaoError::ContratoMissingTarget {
13911                expected: WitTarget::HTTP_FIELD_NAME,
13912                ..
13913            }
13914        ));
13915    }
13916
13917    #[test]
13918    fn rejects_http_contrato_with_subject() {
13919        let mut s = three_member_spec();
13920        s.contratos.push(WitContract {
13921            de: "cart".into(),
13922            para: "catalog".into(),
13923            wit: "wasi:http/proxy".into(),
13924            endpoint: Some("/x".into()),
13925            subject: Some("not.allowed.here".into()),
13926            slot: None,
13927        });
13928        let err = s.validate().unwrap_err();
13929        assert!(matches!(
13930            err,
13931            AplicacaoError::ContratoWrongTarget {
13932                expected: WitTarget::HTTP_FIELD_NAME,
13933                ..
13934            }
13935        ));
13936    }
13937
13938    #[test]
13939    fn rejects_pubsub_contrato_without_subject() {
13940        let mut s = three_member_spec();
13941        s.contratos.push(WitContract {
13942            de: "cart".into(),
13943            para: "catalog".into(),
13944            wit: "nats:pub-sub".into(),
13945            endpoint: None,
13946            subject: None,
13947            slot: None,
13948        });
13949        let err = s.validate().unwrap_err();
13950        assert!(matches!(
13951            err,
13952            AplicacaoError::ContratoMissingTarget {
13953                expected: WitTarget::PUBSUB_FIELD_NAME,
13954                ..
13955            }
13956        ));
13957    }
13958
13959    #[test]
13960    fn rejects_pubsub_contrato_with_endpoint() {
13961        let mut s = three_member_spec();
13962        s.contratos.push(WitContract {
13963            de: "cart".into(),
13964            para: "catalog".into(),
13965            wit: "kafka:topic".into(),
13966            endpoint: Some("/wrong".into()),
13967            subject: Some("topic.x".into()),
13968            slot: None,
13969        });
13970        let err = s.validate().unwrap_err();
13971        assert!(matches!(
13972            err,
13973            AplicacaoError::ContratoWrongTarget {
13974                expected: WitTarget::PUBSUB_FIELD_NAME,
13975                ..
13976            }
13977        ));
13978    }
13979
13980    #[test]
13981    fn rejects_store_contrato_without_slot() {
13982        let mut s = three_member_spec();
13983        s.contratos.push(WitContract {
13984            de: "cart".into(),
13985            para: "catalog".into(),
13986            wit: "wasi:keyvalue/store".into(),
13987            endpoint: None,
13988            subject: None,
13989            slot: None,
13990        });
13991        let err = s.validate().unwrap_err();
13992        assert!(matches!(
13993            err,
13994            AplicacaoError::ContratoMissingTarget {
13995                expected: WitTarget::STORE_FIELD_NAME,
13996                ..
13997            }
13998        ));
13999    }
14000
14001    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
14002
14003    #[test]
14004    fn rejects_http_contrato_with_empty_endpoint() {
14005        // `Some("")` for an HTTP endpoint passes the presence check
14006        // (target() previously returned WitTarget::Http { endpoint: "" })
14007        // but renders as a `path: ""` Cilium L7 rule that matches no
14008        // traffic. Same value-shape footgun closed for :entrada :paths
14009        // entries (eb3456d).
14010        let mut s = three_member_spec();
14011        s.contratos.push(WitContract {
14012            de: "cart".into(),
14013            para: "catalog".into(),
14014            wit: "wasi:http/proxy".into(),
14015            endpoint: Some(String::new()),
14016            subject: None,
14017            slot: None,
14018        });
14019        let err = s.validate().unwrap_err();
14020        assert!(
14021            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
14022                if de == "cart" && para == "catalog"),
14023            "got {err:?}"
14024        );
14025    }
14026
14027    #[test]
14028    fn rejects_http_contrato_with_relative_endpoint() {
14029        // Cilium L7 :path + Gateway API PathPrefix both require a
14030        // leading `/`. Same shape required of :entrada :paths
14031        // (eb3456d). Lifted into target() so every consumer of the
14032        // typed WitTarget view inherits the guarantee.
14033        let mut s = three_member_spec();
14034        s.contratos.push(WitContract {
14035            de: "cart".into(),
14036            para: "catalog".into(),
14037            wit: "wasi:http/proxy".into(),
14038            endpoint: Some("products/:id".into()),
14039            subject: None,
14040            slot: None,
14041        });
14042        let err = s.validate().unwrap_err();
14043        assert!(
14044            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
14045                if endpoint == "products/:id"),
14046            "got {err:?}"
14047        );
14048    }
14049
14050    #[test]
14051    fn rejects_pubsub_contrato_with_empty_subject() {
14052        // NATS / Kafka publish without a subject is a no-op subscribe;
14053        // never the author's intent. Same empty-string rejection as
14054        // :membros :caixa, :placement :clusters entries, :entrada
14055        // :paths entries — every value carried by every typed slot is
14056        // value-shape-checked at validate().
14057        let mut s = three_member_spec();
14058        s.contratos.push(WitContract {
14059            de: "cart".into(),
14060            para: "catalog".into(),
14061            wit: "nats:pub-sub".into(),
14062            endpoint: None,
14063            subject: Some(String::new()),
14064            slot: None,
14065        });
14066        let err = s.validate().unwrap_err();
14067        assert!(
14068            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
14069                if de == "cart" && para == "catalog"),
14070            "got {err:?}"
14071        );
14072    }
14073
14074    #[test]
14075    fn rejects_store_contrato_with_empty_slot() {
14076        // An empty slot template addresses the bucket root, defeating
14077        // the per-key isolation the slot exists for — a footgun on
14078        // `wasi:keyvalue/store` whose closest analog is the empty
14079        // shard-key rejected on :placement Sharded (c7c7799).
14080        let mut s = three_member_spec();
14081        s.contratos.push(WitContract {
14082            de: "cart".into(),
14083            para: "catalog".into(),
14084            wit: "wasi:keyvalue/store".into(),
14085            endpoint: None,
14086            subject: None,
14087            slot: Some(String::new()),
14088        });
14089        let err = s.validate().unwrap_err();
14090        assert!(
14091            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
14092                if de == "cart" && para == "catalog"),
14093            "got {err:?}"
14094        );
14095    }
14096
14097    #[test]
14098    fn http_contrato_root_endpoint_validates() {
14099        // Pin the boundary case: a single-`/` endpoint is the catch-all
14100        // form the Gateway HTTPRoute renderer falls back to when
14101        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
14102        // must remain a valid contrato endpoint too.
14103        let mut s = three_member_spec();
14104        s.contratos.push(contract_http("cart", "catalog", "/"));
14105        s.validate().unwrap();
14106    }
14107
14108    // ── :contratos :endpoint value-shape gate ────────────────────────────
14109    //
14110    // Mirrors the `:entrada :paths` value-shape suite on the peer
14111    // HTTP-path axis. Until this gate landed `WitContract::target()`
14112    // only refused the empty string + the missing-leading-`/` form
14113    // (c4213a4); a structurally invalid endpoint passed validate and
14114    // landed verbatim as a Cilium L7 `path:` rule
14115    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
14116    // traffic or was rejected at apply time by Cilium policy admission.
14117    // Every authoring footgun the K8s Gateway API webhook / Cilium
14118    // policy validator would catch on admission now becomes a caixa-
14119    // build-time `ContratoEndpointInvalid` with the offending
14120    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
14121    // shape as `EntradaPathInvalid` on the sibling axis; same shared
14122    // predicate (`crate::render::is_gateway_api_http_path`) ensures
14123    // drift between the two axes' rule enforcement is a build error
14124    // at the predicate.
14125
14126    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
14127        // Fresh spec per call so the would-be-duplicate edge
14128        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
14129        // `three_member_spec`'s pre-existing
14130        // `(cart, catalog, …, /products/:id)` entry — only the
14131        // endpoint payload differs.
14132        let mut s = three_member_spec();
14133        s.contratos.push(contract_http("cart", "catalog", ep));
14134        s.validate().unwrap_err()
14135    }
14136
14137    #[test]
14138    fn rejects_http_contrato_endpoint_with_query() {
14139        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
14140        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
14141        // rule the L7 matcher would never satisfy.
14142        let err = contrato_endpoint_err("/charge?token=X");
14143        assert!(
14144            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14145                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
14146            "got {err:?}"
14147        );
14148    }
14149
14150    #[test]
14151    fn rejects_http_contrato_endpoint_with_fragment() {
14152        let err = contrato_endpoint_err("/charge#frag");
14153        assert!(
14154            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14155                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
14156            "got {err:?}"
14157        );
14158    }
14159
14160    #[test]
14161    fn rejects_http_contrato_endpoint_with_whitespace() {
14162        let err = contrato_endpoint_err("/foo bar");
14163        assert!(
14164            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14165                if endpoint == "/foo bar" && reason.contains("whitespace")),
14166            "got {err:?}"
14167        );
14168    }
14169
14170    #[test]
14171    fn rejects_http_contrato_endpoint_with_control_char() {
14172        let err = contrato_endpoint_err("/api/\x01bar");
14173        assert!(
14174            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14175                if endpoint == "/api/\x01bar" && reason.contains("control character")),
14176            "got {err:?}"
14177        );
14178    }
14179
14180    #[test]
14181    fn rejects_http_contrato_endpoint_with_non_ascii() {
14182        let err = contrato_endpoint_err("/api/café");
14183        assert!(
14184            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14185                if endpoint == "/api/café" && reason.contains("non-ASCII")),
14186            "got {err:?}"
14187        );
14188    }
14189
14190    #[test]
14191    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
14192        let err = contrato_endpoint_err("/api//cart");
14193        assert!(
14194            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14195                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
14196            "got {err:?}"
14197        );
14198    }
14199
14200    #[test]
14201    fn rejects_http_contrato_endpoint_with_dot_segment() {
14202        let err = contrato_endpoint_err("/api/./cart");
14203        assert!(
14204            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14205                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
14206            "got {err:?}"
14207        );
14208    }
14209
14210    #[test]
14211    fn rejects_http_contrato_endpoint_with_parent_segment() {
14212        // Path-traversal in a contrato endpoint is the canonical
14213        // "L7 rule that the workload's HTTP server's path-resolution
14214        // logic interprets differently than the policy enforcer"
14215        // footgun. Rejected outright at validate time.
14216        let err = contrato_endpoint_err("/api/../etc");
14217        assert!(
14218            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14219                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
14220            "got {err:?}"
14221        );
14222    }
14223
14224    #[test]
14225    fn rejects_http_contrato_endpoint_too_long() {
14226        // 1025-byte endpoint — one over the Gateway API
14227        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
14228        // path matcher has no inherent length limit but the policy
14229        // CR itself rides through the K8s apiserver, which enforces
14230        // ConfigMap-shaped limits; sharing the Gateway API cap is the
14231        // conservative floor.
14232        let big = format!("/api/{}", "a".repeat(1020));
14233        assert_eq!(big.len(), 1025);
14234        let err = contrato_endpoint_err(&big);
14235        assert!(
14236            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14237                if endpoint == &big && reason.contains("max length of 1024")),
14238            "got {err:?}"
14239        );
14240    }
14241
14242    #[test]
14243    fn http_contrato_endpoint_max_length_validates() {
14244        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
14245        // in the cap surfaces here and at
14246        // `rejects_http_contrato_endpoint_too_long` simultaneously,
14247        // mirroring `entrada_path_max_length_validates` on the peer
14248        // axis.
14249        let big = format!("/api/{}", "a".repeat(1019));
14250        assert_eq!(big.len(), 1024);
14251        let mut s = three_member_spec();
14252        s.contratos.push(contract_http("cart", "catalog", &big));
14253        s.validate().unwrap();
14254    }
14255
14256    #[test]
14257    fn http_contrato_endpoint_accepts_canonical_forms() {
14258        // Positive-set sweep: every canonical HTTP-path shape the
14259        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
14260        // plain paths, hidden-file-style `.config` segments distinct
14261        // from the `.` segment, digit-bearing segments, the canonical
14262        // route-template `:param` form, trailing-slash form,
14263        // percent-encoded segments, the `/foo..bar` interior-`..`-
14264        // substring forms that are NOT `..` segments) must remain a
14265        // valid contrato endpoint too. Drift between this list and
14266        // the entrada path positive sweep surfaces at the shared
14267        // `is_gateway_api_http_path` substrate-side suite — one
14268        // source of truth. Uses a fresh `(payment, catalog)` edge so
14269        // none of the swept endpoints collide with the pre-existing
14270        // `(cart, catalog, /products/:id)` / `(cart, payment,
14271        // /charge)` entries in `three_member_spec`.
14272        for ep in [
14273            "/",
14274            "/charge",
14275            "/v1/charge",
14276            "/api/.config",
14277            "/products/:id",
14278            "/api/cart/",
14279            "/api/caf%C3%A9",
14280            "/foo..bar",
14281            "/...",
14282        ] {
14283            let mut s = three_member_spec();
14284            s.contratos.push(contract_http("payment", "catalog", ep));
14285            s.validate()
14286                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
14287        }
14288    }
14289
14290    #[test]
14291    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
14292        // Ordering pin: `ContratoEndpointEmpty` is the more self-
14293        // locating diagnostic on `""` and must lead — the value-
14294        // shape gate is only reached after the empty-check fires.
14295        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
14296        // on the peer axis.
14297        let mut s = three_member_spec();
14298        s.contratos.push(WitContract {
14299            de: "cart".into(),
14300            para: "catalog".into(),
14301            wit: "wasi:http/proxy".into(),
14302            endpoint: Some(String::new()),
14303            subject: None,
14304            slot: None,
14305        });
14306        let err = s.validate().unwrap_err();
14307        assert!(
14308            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
14309            "got {err:?}"
14310        );
14311    }
14312
14313    #[test]
14314    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
14315        // Ordering pin: an endpoint without a leading `/` surfaces the
14316        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
14317        // value-shape gate is only consulted on endpoints that already
14318        // satisfy the absolute-prefix invariant. Mirrors
14319        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
14320        let err = contrato_endpoint_err("bad path");
14321        assert!(
14322            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
14323                if endpoint == "bad path"),
14324            "got {err:?}"
14325        );
14326    }
14327
14328    #[test]
14329    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
14330        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
14331        // `:para` + a non-empty reason flow through verbatim so the
14332        // author can grep their caixa.lisp for the offending contrato
14333        // block and fix it in one edit. Same shape as
14334        // `entrada_path_diagnostic_carries_offending_path`.
14335        let err = contrato_endpoint_err("/api?q=1");
14336        match err {
14337            AplicacaoError::ContratoEndpointInvalid {
14338                de,
14339                para,
14340                endpoint,
14341                reason,
14342            } => {
14343                assert_eq!(de, "cart");
14344                assert_eq!(para, "catalog");
14345                assert_eq!(endpoint, "/api?q=1");
14346                assert!(!reason.is_empty(), "reason field must be non-empty");
14347            }
14348            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
14349        }
14350    }
14351
14352    #[test]
14353    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
14354        // The compounding theorem: every &str inside a WitTarget
14355        // returned by target() is non-empty (and absolute, for Http).
14356        // Renderers downstream of typed_view() can rely on this
14357        // without re-checking — the type system carries the proof.
14358        let http = contract_http("cart", "catalog", "/x");
14359        match http.target().unwrap() {
14360            WitTarget::Http { endpoint } => {
14361                assert!(!endpoint.is_empty());
14362                assert!(endpoint.starts_with('/'));
14363            }
14364            other => panic!("expected Http, got {other:?}"),
14365        }
14366        let nats = WitContract {
14367            de: "a".into(),
14368            para: "b".into(),
14369            wit: "nats:pub-sub".into(),
14370            endpoint: None,
14371            subject: Some("topic.x".into()),
14372            slot: None,
14373        };
14374        match nats.target().unwrap() {
14375            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
14376            other => panic!("expected PubSub, got {other:?}"),
14377        }
14378        let kv = WitContract {
14379            de: "a".into(),
14380            para: "b".into(),
14381            wit: "wasi:keyvalue/store".into(),
14382            endpoint: None,
14383            subject: None,
14384            slot: Some("checkout/$orderId".into()),
14385        };
14386        match kv.target().unwrap() {
14387            WitTarget::Store { slot } => assert!(!slot.is_empty()),
14388            other => panic!("expected Store, got {other:?}"),
14389        }
14390    }
14391
14392    #[test]
14393    fn target_diagnostic_names_offending_endpoint_value() {
14394        // When the malformed endpoint string is non-trivial, the
14395        // diagnostic carries the actual value back to the author —
14396        // not a generic "endpoint malformed" error.
14397        let bad = WitContract {
14398            de: "src".into(),
14399            para: "dst".into(),
14400            wit: "wasi:http/proxy".into(),
14401            endpoint: Some("api/v1/charge".into()),
14402            subject: None,
14403            slot: None,
14404        };
14405        match bad.target().unwrap_err() {
14406            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
14407                assert_eq!(de, "src");
14408                assert_eq!(para, "dst");
14409                assert_eq!(endpoint, "api/v1/charge");
14410            }
14411            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
14412        }
14413    }
14414
14415    #[test]
14416    fn rejects_unknown_wit_with_target_set() {
14417        let mut s = three_member_spec();
14418        s.contratos.push(WitContract {
14419            de: "cart".into(),
14420            para: "catalog".into(),
14421            wit: "custom:exchange".into(),
14422            endpoint: Some("/leaked".into()),
14423            subject: None,
14424            slot: None,
14425        });
14426        let err = s.validate().unwrap_err();
14427        assert!(matches!(
14428            err,
14429            AplicacaoError::ContratoWrongTarget {
14430                expected: WitTarget::CAPABILITY_EXPECTED,
14431                ..
14432            }
14433        ));
14434    }
14435
14436    #[test]
14437    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
14438        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
14439        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
14440        // fourth arm of the same "which payload field name goes in the
14441        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
14442        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14443        // consts cover on the peer HTTP / PubSub / Store arms
14444        // (`wit_target_field_name_pins_per_variant`). Until this lift
14445        // landed the byte-string sat twice — once inline in the
14446        // [`WitContract::target`] Capability-arm rejection at the
14447        // production dispatch, once in `rejects_unknown_wit_with_target_set`
14448        // pinning against the same literal — with no compile-time link
14449        // between them. Same "one canonical declaration, next to the
14450        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
14451        // lift established for the payload-less arm's human-readable
14452        // label axis; this test is the shape peer of
14453        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
14454        // pair (routes-through-const + scalar-value pin) on the
14455        // wrong-target diagnostic-scalar axis.
14456        //
14457        // Fail-before-pass-after was verified locally by mutating the
14458        // const declaration to `"capability"` — the scalar-value pin
14459        // below fires (`"capability" != "none"`) and the routes-through
14460        // assertion below still holds (production and const walk in
14461        // lockstep), which is the correct behavior: a rename on the
14462        // const drifts here first, not at a downstream consumer.
14463        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
14464
14465        let mut s = three_member_spec();
14466        s.contratos.push(WitContract {
14467            de: "cart".into(),
14468            para: "catalog".into(),
14469            wit: "custom:exchange".into(),
14470            endpoint: Some("/leaked".into()),
14471            subject: None,
14472            slot: None,
14473        });
14474        match s.validate().unwrap_err() {
14475            AplicacaoError::ContratoWrongTarget { expected, .. } => {
14476                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
14477            }
14478            other => panic!("expected ContratoWrongTarget, got {other:?}"),
14479        }
14480    }
14481
14482    #[test]
14483    fn unknown_wit_capability_only_validates() {
14484        let mut s = three_member_spec();
14485        s.contratos.push(WitContract {
14486            de: "cart".into(),
14487            para: "catalog".into(),
14488            // A WIT world we haven't yet shaped — accept it as a typed
14489            // capability edge so authors aren't blocked while the WIT
14490            // registry catches up. No payload field may be carried.
14491            wit: "custom:exchange".into(),
14492            endpoint: None,
14493            subject: None,
14494            slot: None,
14495        });
14496        s.validate().unwrap();
14497        let added = s.contratos.last().unwrap();
14498        assert_eq!(added.target().unwrap(), WitTarget::Capability);
14499    }
14500
14501    #[test]
14502    fn target_typed_view_round_trips_each_shape() {
14503        let http = contract_http("cart", "catalog", "/products/:id");
14504        assert_eq!(
14505            http.target().unwrap(),
14506            WitTarget::Http {
14507                endpoint: "/products/:id"
14508            }
14509        );
14510        let nats = WitContract {
14511            de: "a".into(),
14512            para: "b".into(),
14513            wit: "nats:pub-sub".into(),
14514            endpoint: None,
14515            subject: Some("topic.x".into()),
14516            slot: None,
14517        };
14518        assert_eq!(
14519            nats.target().unwrap(),
14520            WitTarget::PubSub { subject: "topic.x" }
14521        );
14522        let kv = WitContract {
14523            de: "a".into(),
14524            para: "b".into(),
14525            wit: "wasi:keyvalue/store".into(),
14526            endpoint: None,
14527            subject: None,
14528            slot: Some("checkout/$orderId".into()),
14529        };
14530        assert_eq!(
14531            kv.target().unwrap(),
14532            WitTarget::Store {
14533                slot: "checkout/$orderId"
14534            }
14535        );
14536    }
14537
14538    #[test]
14539    fn wit_contract_kind_predicates() {
14540        let http = contract_http("a", "b", "/x");
14541        assert!(http.is_http());
14542        assert!(!http.is_pubsub());
14543        assert!(!http.is_store());
14544        assert!(!http.is_capability());
14545
14546        let nats = WitContract {
14547            de: "a".into(),
14548            para: "b".into(),
14549            wit: "nats:pub-sub".into(),
14550            endpoint: None,
14551            subject: Some("topic.x".into()),
14552            slot: None,
14553        };
14554        assert!(nats.is_pubsub());
14555        assert!(!nats.is_http());
14556        assert!(!nats.is_capability());
14557
14558        let kv = WitContract {
14559            de: "a".into(),
14560            para: "b".into(),
14561            wit: "wasi:keyvalue/store".into(),
14562            endpoint: None,
14563            subject: None,
14564            slot: Some("checkout/$orderId".into()),
14565        };
14566        assert!(kv.is_store());
14567        assert!(!kv.is_http());
14568        assert!(!kv.is_capability());
14569
14570        // Fourth arm on the paired closed-set predicate family: the
14571        // payload-less capability edge that projects to the payload-
14572        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
14573        // Extends the 3-arm predicate sweep this test opened to cover
14574        // the closed 4-way partition [`WitContract::is_capability`]
14575        // closes on the pre-projection WIT-shape axis, matched with the
14576        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
14577        // 4-arm predicate set.
14578        let cap = WitContract {
14579            de: "a".into(),
14580            para: "b".into(),
14581            wit: "custom:capability-only".into(),
14582            endpoint: None,
14583            subject: None,
14584            slot: None,
14585        };
14586        assert!(cap.is_capability());
14587        assert!(!cap.is_http());
14588        assert!(!cap.is_pubsub());
14589        assert!(!cap.is_store());
14590    }
14591
14592    // ── :contratos :wit value-shape gate ─────────────────────────────────
14593    //
14594    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
14595    // dispatch-discriminator axis. Until this gate landed
14596    // `WitContract::target()` accepted any non-empty string and
14597    // silently demoted unrecognized shapes to a capability-only L4
14598    // edge — the canonical "I thought I had L7 HTTP routing, got
14599    // L4-only" footgun. Every authoring footgun the WIT registry's
14600    // own grammar rejects (uppercase, hyphen-for-colon typo,
14601    // whitespace, empty package, doubled `@`, …) now becomes a
14602    // caixa-build-time `ContratoWitInvalid` with the offending
14603    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
14604    // as `ContratoEndpointInvalid` on the sibling axis; same shared
14605    // predicate (`crate::render::is_wit_world_ref`) ensures drift
14606    // between any two axes' rule enforcement is a build error at the
14607    // predicate, not piecemeal across renderers.
14608
14609    fn contrato_wit_err(wit: &str) -> AplicacaoError {
14610        // Fresh spec per call so the new contract doesn't collide on
14611        // identity with `three_member_spec`'s pre-existing entries.
14612        // The new edge uses `(payment, catalog)` — a pair the fixture
14613        // doesn't already declare — with no payload field set, so the
14614        // wit-shape gate fires before any payload-shape arm.
14615        let mut s = three_member_spec();
14616        s.contratos.push(WitContract {
14617            de: "payment".into(),
14618            para: "catalog".into(),
14619            wit: wit.into(),
14620            endpoint: None,
14621            subject: None,
14622            slot: None,
14623        });
14624        s.validate().unwrap_err()
14625    }
14626
14627    #[test]
14628    fn rejects_wit_with_uppercase_namespace() {
14629        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
14630        // didn't match the lowercase `wasi:http/` prefix is_http() keys
14631        // off, so the dispatch fell through to the capability arm and
14632        // the contract silently rendered as an L4-only Cilium edge.
14633        // The new gate surfaces the uppercase typo at validate time
14634        // with the offending `:wit` named.
14635        let err = contrato_wit_err("WASI:http/proxy");
14636        assert!(
14637            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14638                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
14639            "got {err:?}"
14640        );
14641    }
14642
14643    #[test]
14644    fn rejects_wit_with_hyphen_for_colon_typo() {
14645        // The canonical "I forgot the `:` separator" typo — pre-gate
14646        // this passed as Capability silently, so the renderer emitted
14647        // an L4-only policy where the author expected L7 HTTP rules.
14648        let err = contrato_wit_err("wasi-http/proxy");
14649        assert!(
14650            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14651                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
14652            "got {err:?}"
14653        );
14654    }
14655
14656    #[test]
14657    fn rejects_wit_with_multiple_colons() {
14658        // Doubled `:` — the namespace/package split has nowhere to
14659        // anchor, so the dispatch silently demotes to Capability.
14660        let err = contrato_wit_err("wasi:http:proxy");
14661        assert!(
14662            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14663                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
14664            "got {err:?}"
14665        );
14666    }
14667
14668    #[test]
14669    fn rejects_wit_with_empty_package() {
14670        // `wasi:` — namespace alone with no package. Pre-gate this
14671        // failed neither the is_http nor is_pubsub nor is_store
14672        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
14673        // a bare `wasi:`), so it silently demoted to Capability.
14674        let err = contrato_wit_err("wasi:");
14675        assert!(
14676            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14677                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
14678            "got {err:?}"
14679        );
14680    }
14681
14682    #[test]
14683    fn rejects_wit_with_underscore() {
14684        // Underscore — WIT identifiers are kebab-case, same rule
14685        // DNS-1123 enforces on its peer axes. The diagnostic carries
14686        // the explicit "use `-` instead" remediation.
14687        let err = contrato_wit_err("wasi:http_proxy");
14688        assert!(
14689            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14690                if wit == "wasi:http_proxy" && reason.contains('_')),
14691            "got {err:?}"
14692        );
14693    }
14694
14695    #[test]
14696    fn rejects_wit_with_whitespace() {
14697        // Whitespace mid-token — the prefix check matches but the
14698        // package-and-onward parse silently demoted to Capability.
14699        let err = contrato_wit_err("wasi:http proxy");
14700        assert!(
14701            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14702                if wit == "wasi:http proxy" && reason.contains("whitespace")),
14703            "got {err:?}"
14704        );
14705    }
14706
14707    #[test]
14708    fn rejects_wit_with_non_ascii() {
14709        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14710        // the package name from a doc with smart quotes / accented
14711        // characters" footgun.
14712        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
14713        assert!(
14714            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14715                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
14716            "got {err:?}"
14717        );
14718    }
14719
14720    #[test]
14721    fn rejects_wit_with_consecutive_hyphens() {
14722        // `pub--sub` — WIT identifiers join words with single hyphens.
14723        let err = contrato_wit_err("nats:pub--sub");
14724        assert!(
14725            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14726                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
14727            "got {err:?}"
14728        );
14729    }
14730
14731    #[test]
14732    fn rejects_wit_with_trailing_at_no_version() {
14733        // `wasi:http/proxy@` — the version-suffix author started to
14734        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
14735        // parser would reject this; surface it at validate time.
14736        let err = contrato_wit_err("wasi:http/proxy@");
14737        assert!(
14738            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14739                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
14740            "got {err:?}"
14741        );
14742    }
14743
14744    #[test]
14745    fn rejects_wit_too_long() {
14746        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
14747        // The legitimate-shape arms all pass (lowercase, single `:`,
14748        // kebab-case identifiers); only the cap arm fires. Surfaces
14749        // the paste-from-binary / accidental-multi-line-blob landing
14750        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14751        // on the peer axis.
14752        let big = format!("wasi:{}", "a".repeat(124));
14753        assert_eq!(big.len(), 129);
14754        let err = contrato_wit_err(&big);
14755        assert!(
14756            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14757                if wit == &big && reason.contains("max length of 128")),
14758            "got {err:?}"
14759        );
14760    }
14761
14762    #[test]
14763    fn wit_max_length_validates() {
14764        // 128-byte WIT reference — exactly the cap. Boundary pin:
14765        // drift in the cap surfaces here and at `rejects_wit_too_long`
14766        // simultaneously, mirroring
14767        // `http_contrato_endpoint_max_length_validates` on the peer
14768        // axis.
14769        let big = format!("wasi:{}", "a".repeat(123));
14770        assert_eq!(big.len(), 128);
14771        let mut s = three_member_spec();
14772        s.contratos.push(WitContract {
14773            de: "payment".into(),
14774            para: "catalog".into(),
14775            wit: big,
14776            endpoint: None,
14777            subject: None,
14778            slot: None,
14779        });
14780        s.validate().unwrap();
14781    }
14782
14783    #[test]
14784    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
14785        // Positive-set sweep through the AplicacaoSpec::validate
14786        // surface (rather than the substrate-side predicate directly)
14787        // — pins every shape the existing test fixtures + the
14788        // checkout-aplicacao example carry, so the gate's accept-set
14789        // matches the substrate's emit-set. Drift between this list
14790        // and `render::tests::wit_world_ref_accepts_canonical_forms`
14791        // surfaces at the substrate layer's positive sweep — one
14792        // source of truth for the rule.
14793        for wit in [
14794            "wasi:http/proxy",
14795            "wasi:keyvalue/store",
14796            "nats:pub-sub",
14797            "kafka:topic",
14798            "custom:exchange",
14799            "pleme:cap/audit",
14800            "wasi:http/proxy@0.2.0",
14801        ] {
14802            // Payload field paired to the dispatched WIT shape so the
14803            // shape-↔-target arm doesn't fire instead of the wit-shape
14804            // arm we're exercising. Routes off the same
14805            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
14806            // `wit_shape_is_store` free functions the production
14807            // `WitContract::is_http` / `is_pubsub` / `is_store`
14808            // methods delegate to (both consult the lifted
14809            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
14810            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
14811            // future prefix addition to the routing accept-set
14812            // reaches this test's payload-dispatch arm by
14813            // construction — no per-test-site drift can hide a
14814            // shape-→-target-slot mismatch that would silently
14815            // demote a canonical `:wit` value to the
14816            // `(None, None, None)` capability-only arm and let the
14817            // `AplicacaoSpec::validate` positive sweep pass on a
14818            // shape it should exercise as HTTP / pub-sub / store.
14819            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
14820                (Some("/x".into()), None, None)
14821            } else if wit_shape_is_pubsub(wit) {
14822                (None, Some("topic.x".into()), None)
14823            } else if wit_shape_is_store(wit) {
14824                (None, None, Some("bucket/$key".into()))
14825            } else {
14826                (None, None, None)
14827            };
14828            let mut s = three_member_spec();
14829            s.contratos.push(WitContract {
14830                de: "payment".into(),
14831                para: "catalog".into(),
14832                wit: wit.into(),
14833                endpoint,
14834                subject,
14835                slot,
14836            });
14837            s.validate()
14838                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
14839        }
14840    }
14841
14842    #[test]
14843    fn wit_shape_predicates_accept_canonical_prefix_set() {
14844        // Positive-set sweep pinning every prefix in
14845        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
14846        // WIT_STORE_SHAPE_PREFIXES against the three free-function
14847        // dispatch predicates. The six prefixes are the load-bearing
14848        // routing keys the substrate's WIT-shape dispatch consults
14849        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
14850        // key/value-store-slot admission); any drift between the
14851        // free-function accept-set and this list surfaces here
14852        // rather than at apply time as a silent
14853        // shape-→-capability-only demotion.
14854        assert!(wit_shape_is_http("wasi:http/proxy"));
14855        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
14856        assert!(wit_shape_is_http("http:incoming"));
14857
14858        assert!(wit_shape_is_pubsub("nats:pub-sub"));
14859        assert!(wit_shape_is_pubsub("kafka:topic"));
14860
14861        assert!(wit_shape_is_store("wasi:keyvalue/store"));
14862        assert!(wit_shape_is_store("kv:cache/session"));
14863    }
14864
14865    #[test]
14866    fn wit_shape_predicates_reject_uncanonical_forms() {
14867        // Negative-set pin: the six canonical prefixes are
14868        // lowercase-only (mirrors the `is_wit_world_ref` substrate
14869        // predicate's lowercase invariant — see its docstring on the
14870        // "I thought I had L7 HTTP routing, got L4-only" footgun).
14871        // The empty string, an uppercase-prefixed form, a hyphen-
14872        // instead-of-colon typo, and a bare kebab identifier all miss
14873        // every shape arm — reachable-by-construction only via the
14874        // `is_wit_world_ref` gate that admission-checks the `:wit`
14875        // value first, but pinned here so any future
14876        // free-function change (e.g. a case-insensitive
14877        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
14878        // this unit level.
14879        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
14880            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
14881            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
14882            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
14883        }
14884    }
14885
14886    #[test]
14887    fn wit_shape_predicates_partition_canonical_set() {
14888        // Every canonical prefix routes to exactly one shape arm —
14889        // the three prefix sets are pairwise disjoint. Pins the
14890        // routing property [`WitContract::target`] relies on: an
14891        // `is_http()` return of `true` guarantees `is_pubsub()` and
14892        // `is_store()` return `false`, so the shape-→-target-slot
14893        // dispatch (endpoint vs subject vs slot) is unambiguous.
14894        // Drift (e.g. a future `"kv:"` moved into the HTTP set
14895        // without removal from the store set) would silently route
14896        // one prefix to two arms and the first-matching-arm order
14897        // becomes load-bearing — this pin surfaces it as a build
14898        // error instead.
14899        for prefix in WIT_HTTP_SHAPE_PREFIXES {
14900            let sample = format!("{prefix}x");
14901            assert!(wit_shape_is_http(&sample));
14902            assert!(!wit_shape_is_pubsub(&sample));
14903            assert!(!wit_shape_is_store(&sample));
14904        }
14905        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
14906            let sample = format!("{prefix}x");
14907            assert!(!wit_shape_is_http(&sample));
14908            assert!(wit_shape_is_pubsub(&sample));
14909            assert!(!wit_shape_is_store(&sample));
14910        }
14911        for prefix in WIT_STORE_SHAPE_PREFIXES {
14912            let sample = format!("{prefix}x");
14913            assert!(!wit_shape_is_http(&sample));
14914            assert!(!wit_shape_is_pubsub(&sample));
14915            assert!(wit_shape_is_store(&sample));
14916        }
14917    }
14918
14919    #[test]
14920    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
14921        // Positive pin: [`wit_shape_matches`] is exactly the
14922        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
14923        // parameterized on the accept-set. Two-prefix accept-set,
14924        // one-prefix accept-set, and empty accept-set (which must
14925        // reject everything, including the empty string — an empty
14926        // `any()` fold returns `false`) all pinned so a future
14927        // reimplementation that swaps `starts_with` for `contains`,
14928        // `==`, or a case-folded comparator surfaces at unit-test
14929        // time.
14930        let two = &["wasi:http/", "http:"];
14931        assert!(wit_shape_matches("wasi:http/proxy", two));
14932        assert!(wit_shape_matches("http:incoming", two));
14933        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
14934
14935        let one = &["nats:"];
14936        assert!(wit_shape_matches("nats:pub-sub", one));
14937        assert!(!wit_shape_matches("kafka:topic", one));
14938
14939        // Empty accept-set matches nothing — the identity element
14940        // for the disjunctive `any()` fold across the prefix set.
14941        // Reachable via a future `wit_shape_is_<name>` const paired
14942        // to a still-empty prefix table on a nascent shape-arm draft.
14943        let empty: &[&str] = &[];
14944        assert!(!wit_shape_matches("wasi:http/proxy", empty));
14945        assert!(!wit_shape_matches("", empty));
14946
14947        // starts_with, not contains: a prefix embedded mid-string
14948        // never matches. Pins the routing invariant [`WitContract::target`]
14949        // relies on (an authored `:wit "custom:wasi:http/"` string
14950        // does not silently route through the HTTP arm just because
14951        // it happens to contain the canonical HTTP prefix).
14952        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
14953    }
14954
14955    #[test]
14956    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
14957        // Equivalence pin: each per-shape predicate is exactly
14958        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
14959        // every canonical prefix + the empty string + one negative
14960        // sample against every peer so a future predicate that grew
14961        // its own inline `iter().any(starts_with)` (rather than
14962        // delegating through the lifted combinator) drifts loudly here
14963        // — the peer-const table's contents must agree with the
14964        // predicate's accept-set by construction.
14965        let samples = [
14966            String::new(),
14967            "wasi:http/proxy".to_string(),
14968            "http:incoming".to_string(),
14969            "nats:pub-sub".to_string(),
14970            "kafka:topic".to_string(),
14971            "wasi:keyvalue/store".to_string(),
14972            "kv:cache/session".to_string(),
14973            "custom-shape".to_string(),
14974            "WASI:HTTP/proxy".to_string(),
14975        ];
14976        for wit in &samples {
14977            assert_eq!(
14978                wit_shape_is_http(wit),
14979                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
14980                "wit_shape_is_http drifted from combinator on {wit:?}",
14981            );
14982            assert_eq!(
14983                wit_shape_is_pubsub(wit),
14984                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
14985                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
14986            );
14987            assert_eq!(
14988                wit_shape_is_store(wit),
14989                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
14990                "wit_shape_is_store drifted from combinator on {wit:?}",
14991            );
14992        }
14993    }
14994
14995    #[test]
14996    fn wit_contract_shape_methods_delegate_to_free_functions() {
14997        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
14998        // `is_store` are `&self` conveniences on top of the free
14999        // functions — for every canonical prefix the method's return
15000        // matches its free-function peer. Sweeps the union of the
15001        // three prefix sets so a future method that grew its own
15002        // inline prefix logic (rather than delegating) drifts loudly
15003        // here on the first prefix the free function accepts and the
15004        // method doesn't.
15005        for shape_set in [
15006            WIT_HTTP_SHAPE_PREFIXES,
15007            WIT_PUBSUB_SHAPE_PREFIXES,
15008            WIT_STORE_SHAPE_PREFIXES,
15009        ] {
15010            for prefix in shape_set {
15011                let c = WitContract {
15012                    de: "cart".into(),
15013                    para: "catalog".into(),
15014                    wit: format!("{prefix}x"),
15015                    endpoint: None,
15016                    subject: None,
15017                    slot: None,
15018                };
15019                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
15020                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
15021                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
15022                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
15023            }
15024        }
15025        // Capability-arm delegation sweep: two representative
15026        // Capability-shaped `:wit` values (a bare non-prefix-matching
15027        // WIT world, the deliberately-shaped empty string
15028        // [`WitContract::is_capability`]'s docstring calls out as
15029        // syntactically Capability). Extends the free-function
15030        // delegation pin onto the fourth arm so a future
15031        // [`WitContract::is_capability`] rewrite that grew an inline
15032        // prefix-set scan (rather than delegating through
15033        // [`wit_shape_is_capability`]) drifts loudly here on the first
15034        // Capability-shaped sample.
15035        for wit in ["custom:capability-only", ""] {
15036            let c = WitContract {
15037                de: "cart".into(),
15038                para: "catalog".into(),
15039                wit: wit.into(),
15040                endpoint: None,
15041                subject: None,
15042                slot: None,
15043            };
15044            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
15045        }
15046    }
15047
15048    #[test]
15049    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
15050        // 4-way partition-witness pin on the raw `&str` axis: for every
15051        // canonical prefix in the three payload-arm accept-sets,
15052        // exactly one of the four [`wit_shape_is_http`] /
15053        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
15054        // [`wit_shape_is_capability`] free functions returns `true` and
15055        // the other three return `false` — the four-arm partition
15056        // witness that locks the free-function WIT-shape-classifier
15057        // family into a partition of the `:contratos :wit` axis
15058        // load-bearing. Peer of the sibling [`WitContract`]-surface
15059        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15060        // partition pin — extends the discipline onto the raw `&str`
15061        // axis so any future arm addition (a hypothetical
15062        // `wasi:sockets/*` transport-layer shape, an `oci:*`
15063        // capability-import carrier per the sibling
15064        // [`wit_shape_matches`] docstring's trajectory bullet) that
15065        // landed on one of the payload-arm free functions without
15066        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
15067        // here as two arms returning `true` simultaneously at
15068        // caixa-core build time rather than a silent per-consumer
15069        // misclassification at renderer emit time.
15070        for shape_set in [
15071            WIT_HTTP_SHAPE_PREFIXES,
15072            WIT_PUBSUB_SHAPE_PREFIXES,
15073            WIT_STORE_SHAPE_PREFIXES,
15074        ] {
15075            for prefix in shape_set {
15076                let wit = format!("{prefix}x");
15077                let hits = [
15078                    wit_shape_is_http(&wit),
15079                    wit_shape_is_pubsub(&wit),
15080                    wit_shape_is_store(&wit),
15081                    wit_shape_is_capability(&wit),
15082                ]
15083                .iter()
15084                .filter(|&&b| b)
15085                .count();
15086                assert_eq!(
15087                    hits,
15088                    1,
15089                    "raw-&str WIT-shape 4-way predicate partition must \
15090                     admit exactly one arm per canonical prefix; got {hits} \
15091                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
15092                     is_capability={})",
15093                    wit_shape_is_http(&wit),
15094                    wit_shape_is_pubsub(&wit),
15095                    wit_shape_is_store(&wit),
15096                    wit_shape_is_capability(&wit),
15097                );
15098            }
15099        }
15100        // Capability-arm sweep on the raw `&str` axis: two
15101        // representative Capability-shaped `:wit` values (a bare non-
15102        // prefix-matching WIT world, the deliberately-shaped empty
15103        // string the pure classifier still admits per
15104        // [`wit_shape_is_capability`]'s docstring). Both must land on
15105        // the fourth arm exclusively so the partition witness holds
15106        // across the full 4-arm closure on the raw `&str` axis.
15107        for wit in ["custom:capability-only", ""] {
15108            let hits = [
15109                wit_shape_is_http(wit),
15110                wit_shape_is_pubsub(wit),
15111                wit_shape_is_store(wit),
15112                wit_shape_is_capability(wit),
15113            ]
15114            .iter()
15115            .filter(|&&b| b)
15116            .count();
15117            assert_eq!(
15118                hits, 1,
15119                "raw-&str WIT-shape 4-way predicate partition must \
15120                 admit exactly one arm on Capability-shaped wit={wit:?}"
15121            );
15122            assert!(
15123                wit_shape_is_capability(wit),
15124                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
15125            );
15126        }
15127    }
15128
15129    #[test]
15130    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
15131        // Composition-witness pin: [`wit_shape_is_capability`] is the
15132        // exact-inverse disjunction of the sibling payload-arm free-
15133        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
15134        // / [`wit_shape_is_store`]. A future reimplementation that
15135        // grew its own prefix-set scan (e.g. inlining a fourth
15136        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
15137        // not own today) rather than delegating to the sibling trio
15138        // would drift loudly here — the composition contract binds the
15139        // fourth-arm free-function predicate to the exact-inverse of
15140        // the three payload-arm free-function predicates, so any
15141        // rebrand of any prefix-set const flows through
15142        // [`wit_shape_is_capability`] by construction without a
15143        // coordinated per-consumer rewrite. Peer of the sibling
15144        // [`WitContract`]-surface
15145        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
15146        // composition pin — extends the discipline onto the raw
15147        // `&str` axis.
15148        let mut cases: Vec<String> = Vec::new();
15149        for shape_set in [
15150            WIT_HTTP_SHAPE_PREFIXES,
15151            WIT_PUBSUB_SHAPE_PREFIXES,
15152            WIT_STORE_SHAPE_PREFIXES,
15153        ] {
15154            for prefix in shape_set {
15155                cases.push(format!("{prefix}x"));
15156            }
15157        }
15158        cases.push("custom:capability-only".to_string());
15159        cases.push(String::new());
15160        for wit in cases {
15161            assert_eq!(
15162                wit_shape_is_capability(&wit),
15163                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
15164                "wit_shape_is_capability must equal \
15165                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
15166                 at wit={wit:?}"
15167            );
15168        }
15169    }
15170
15171    #[test]
15172    fn wit_shape_classifier_family_is_const_fn() {
15173        // Fail-before-pass-after pin on the 4-arm free-function WIT-
15174        // shape classifier family's `const`-eval posture. Each of the
15175        // four peer classifiers ([`wit_shape_is_http`] /
15176        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
15177        // [`wit_shape_is_capability`]) and the underlying combinator
15178        // [`wit_shape_matches`] must be `pub const fn` — any future
15179        // accidental downgrade to non-`const` fails the `const fn`
15180        // wrappers below at caixa-core build time with E0015
15181        // (`cannot call non-const function`), strictly stronger than
15182        // a runtime `assert!` and strictly stronger than the module-
15183        // scope `const _: () = assert!(…)` pins immediately after the
15184        // classifier declarations (those anchor specific accept-set
15185        // truth-table entries; this pin anchors the `const` posture
15186        // itself via `const fn` wrappers that are only well-formed
15187        // when the callee is itself `const fn`).
15188        //
15189        // Verified fail-before-pass-after by locally reverting
15190        // `pub const fn` → `pub fn` on each classifier and observing
15191        // E0015 at every corresponding wrapper call site (build
15192        // error, no test-time surface), then restoring `pub const fn`
15193        // and observing the pin pass at test time. Peer of the
15194        // sibling M3
15195        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
15196        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
15197        // M2
15198        // [`child_spec_restart_accessor_is_const_fn`] /
15199        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
15200        // and M3
15201        // [`placement_estrategia_accessor_is_const_fn`] /
15202        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
15203        // sibling `const`-eval-surface-pass axes.
15204        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
15205            wit_shape_matches(wit, prefixes)
15206        }
15207        const fn http_via_const_fn(wit: &str) -> bool {
15208            wit_shape_is_http(wit)
15209        }
15210        const fn pubsub_via_const_fn(wit: &str) -> bool {
15211            wit_shape_is_pubsub(wit)
15212        }
15213        const fn store_via_const_fn(wit: &str) -> bool {
15214            wit_shape_is_store(wit)
15215        }
15216        const fn capability_via_const_fn(wit: &str) -> bool {
15217            wit_shape_is_capability(wit)
15218        }
15219        // Sweep one canonical accept-set sample per arm plus the
15220        // payload-less/empty capability samples, asserting the
15221        // wrapper and direct dispatches agree byte-for-byte across
15222        // the closed 4-arm partition.
15223        let cases: [(&str, bool, bool, bool, bool); 6] = [
15224            ("wasi:http/proxy", true, false, false, false),
15225            ("http:incoming", true, false, false, false),
15226            ("nats:events", false, true, false, false),
15227            ("kafka:topic", false, true, false, false),
15228            ("wasi:keyvalue/store", false, false, true, false),
15229            ("kv:cache", false, false, true, false),
15230        ];
15231        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
15232            assert_eq!(
15233                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
15234                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
15235                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
15236            );
15237            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
15238            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
15239            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
15240            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
15241            assert_eq!(wit_shape_is_http(wit), is_http);
15242            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
15243            assert_eq!(wit_shape_is_store(wit), is_store);
15244        }
15245        // Payload-less capability arm (the 4th partition arm).
15246        let capability_samples: [&str; 3] =
15247            ["wasi:filesystem/preopens", "custom:capability-only", ""];
15248        for wit in capability_samples {
15249            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
15250            assert!(wit_shape_is_capability(wit));
15251            assert!(!wit_shape_is_http(wit));
15252            assert!(!wit_shape_is_pubsub(wit));
15253            assert!(!wit_shape_is_store(wit));
15254        }
15255    }
15256
15257    // Canonical `(wit, expected)` sweep the four [`WitShape`] pins below
15258    // key off — one accept-set sample per prefix in each of the three
15259    // payload-arm prefix sets [`WIT_HTTP_SHAPE_PREFIXES`] /
15260    // [`WIT_PUBSUB_SHAPE_PREFIXES`] / [`WIT_STORE_SHAPE_PREFIXES`], plus
15261    // three canonical Capability-arm samples (a non-prefix-matching WIT
15262    // world, an empty string, a partial-match probe that lands after
15263    // the accepted prefix boundary). Declared once so a future arm
15264    // addition or prefix-set edit grows the truth table at one
15265    // authored site and every downstream pin picks up the new row by
15266    // construction.
15267    const WIT_SHAPE_CLASSIFY_TRUTH_TABLE: &[(&str, WitShape)] = &[
15268        ("wasi:http/proxy", WitShape::Http),
15269        ("http:incoming", WitShape::Http),
15270        ("nats:events", WitShape::PubSub),
15271        ("kafka:topic", WitShape::PubSub),
15272        ("wasi:keyvalue/store", WitShape::Store),
15273        ("kv:cache", WitShape::Store),
15274        ("wasi:filesystem/preopens", WitShape::Capability),
15275        ("custom:capability-only", WitShape::Capability),
15276        ("", WitShape::Capability),
15277    ];
15278
15279    #[test]
15280    fn wit_shape_all_matches_declaration_order_and_covers_every_arm() {
15281        // Fail-before-pass-after pin on [`WitShape::ALL`]: the slice
15282        // must enumerate every arm exactly once in declaration order
15283        // (`Http` → `PubSub` → `Store` → `Capability`), so downstream
15284        // consumers that walk the shape space through the const slice
15285        // reach every arm and see them in the canonical order the
15286        // paired [`WitShape::classify`] arm-preference dispatches on.
15287        // A future variant addition that forgets to grow the slice
15288        // trips here (the length no longer matches the number of arms
15289        // touched by the `match self` below); a rearrangement of the
15290        // declaration order without updating the slice trips too.
15291        let expected: [WitShape; 4] = [
15292            WitShape::Http,
15293            WitShape::PubSub,
15294            WitShape::Store,
15295            WitShape::Capability,
15296        ];
15297        assert_eq!(WitShape::ALL.len(), expected.len());
15298        assert_eq!(WitShape::ALL, &expected[..]);
15299        // Exhaustive-match witness: touch every arm so a future
15300        // variant addition without a matching `WitShape::ALL` extension
15301        // trips at compile time here on the missing arm.
15302        for arm in WitShape::ALL {
15303            match arm {
15304                WitShape::Http | WitShape::PubSub | WitShape::Store | WitShape::Capability => {}
15305            }
15306        }
15307    }
15308
15309    #[test]
15310    fn wit_shape_classify_pins_the_canonical_truth_table() {
15311        // Pin the [`WitShape::classify`] arm-dispatch against the
15312        // shared truth table [`WIT_SHAPE_CLASSIFY_TRUTH_TABLE`]. A
15313        // future prefix-set edit that reroutes any canonical sample
15314        // onto the wrong arm trips at exactly the offending row.
15315        for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
15316            assert_eq!(
15317                WitShape::classify(wit),
15318                *expected,
15319                "WitShape::classify({wit:?}) drifted from truth table",
15320            );
15321        }
15322    }
15323
15324    #[test]
15325    fn wit_shape_classify_partitions_via_is_variant_predicates() {
15326        // Fail-before-pass-after pin: for every canonical truth-table
15327        // row, the classified arm satisfies exactly one of the four
15328        // [`gen_platform::IsVariant`]-derived arm-discriminator
15329        // predicates ([`WitShape::is_http`] / [`is_pubsub`] /
15330        // [`is_store`] / [`is_capability`]) — the observed 4-slot
15331        // predicate row must equal a one-hot row with the `true` at
15332        // exactly the same index as the declared arm's slot in
15333        // [`WitShape::ALL`]. A future rebind (an `#[is_variant(name =
15334        // "…")]` drift, a manual `impl` shadowing the derive, an arm
15335        // rename that reroutes one arm through the wrong predicate
15336        // lane) trips here at exactly the offending row rather than
15337        // surfacing far from the derive commit.
15338        for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
15339            let arm = WitShape::classify(wit);
15340            let observed = [
15341                arm.is_http(),
15342                arm.is_pubsub(),
15343                arm.is_store(),
15344                arm.is_capability(),
15345            ];
15346            let mut expected_row = [false; 4];
15347            let idx = WitShape::ALL
15348                .iter()
15349                .position(|a| a == expected)
15350                .expect("truth-table arm appears in WitShape::ALL");
15351            expected_row[idx] = true;
15352            assert_eq!(
15353                observed, expected_row,
15354                "WitShape::classify({wit:?}).is_* row must be one-hot at slot {idx}",
15355            );
15356        }
15357    }
15358
15359    #[test]
15360    fn wit_shape_classify_agrees_with_free_predicates() {
15361        // Equivalence pin against the four free classifier predicates
15362        // ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
15363        // [`wit_shape_is_store`] / [`wit_shape_is_capability`]) — after
15364        // this lift the free predicates route through
15365        // `matches!(WitShape::classify(wit), WitShape::<arm>)`, so this
15366        // pin proves the delegation preserves each predicate's
15367        // accept-set on the canonical truth table. A future accidental
15368        // reintroduction of an open-coded free-predicate body (or a
15369        // classify-side arm reorder that shifts arm preference in a
15370        // way that breaks disjointness) trips here at the offending
15371        // row rather than at a downstream consumer.
15372        for (wit, _expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
15373            let arm = WitShape::classify(wit);
15374            assert_eq!(arm.is_http(), wit_shape_is_http(wit));
15375            assert_eq!(arm.is_pubsub(), wit_shape_is_pubsub(wit));
15376            assert_eq!(arm.is_store(), wit_shape_is_store(wit));
15377            assert_eq!(arm.is_capability(), wit_shape_is_capability(wit));
15378        }
15379    }
15380
15381    #[test]
15382    fn wit_shape_as_str_display_and_asref_route_through_one_source() {
15383        // Fail-before-pass-after pin on the canonical-projection triple
15384        // [`WitShape::as_str`] / [`std::fmt::Display for WitShape`] /
15385        // [`AsRef<str> for WitShape`]: every arm's `Display`-formatted
15386        // and `AsRef<str>`-borrowed output must byte-equal its
15387        // `as_str` output. Same discipline the sibling
15388        // [`crate::CaixaKind`] / [`crate::dialeto::CaixaDialeto`] /
15389        // [`PlacementStrategy`] / [`RateLimitUnit`] canonical-projection
15390        // triples carry — a future accidental hand-rolled `Display`
15391        // body that diverges from `as_str` trips here.
15392        let expected: &[(WitShape, &str)] = &[
15393            (WitShape::Http, "http"),
15394            (WitShape::PubSub, "pubsub"),
15395            (WitShape::Store, "store"),
15396            (WitShape::Capability, "capability"),
15397        ];
15398        for (arm, want) in expected {
15399            assert_eq!(arm.as_str(), *want, "WitShape::as_str({arm:?}) drifted");
15400            assert_eq!(
15401                format!("{arm}"),
15402                *want,
15403                "Display for WitShape drifted from as_str at {arm:?}",
15404            );
15405            assert_eq!(
15406                AsRef::<str>::as_ref(arm),
15407                *want,
15408                "AsRef<str> for WitShape drifted from as_str at {arm:?}",
15409            );
15410        }
15411    }
15412
15413    #[test]
15414    fn wit_shape_classify_is_const_fn() {
15415        // Fail-before-pass-after pin on [`WitShape::classify`]'s
15416        // `const`-eval posture. The classifier must be `pub const fn`
15417        // — any future accidental downgrade to non-`const` fails the
15418        // wrapper below with E0015 at caixa-core build time, strictly
15419        // stronger than a runtime `assert!`. Peer of the sibling
15420        // [`wit_shape_classifier_family_is_const_fn`] pin on the
15421        // free-function classifier family.
15422        const fn classify_via_const_fn(wit: &str) -> WitShape {
15423            WitShape::classify(wit)
15424        }
15425        // Compile-time truth-table pin: every canonical row's
15426        // classification is reachable at const-eval time, so any
15427        // downstream `const`-context consumer (a module-scope
15428        // `const _: () = assert!(matches!(WitShape::classify(<lit>),
15429        // WitShape::<arm>))` invariant pin on a typed fixture, a
15430        // future `const fn` per-`:contratos :wit` arm-resolver over a
15431        // static wit literal) reaches the classifier through one
15432        // dispatch on the substrate primitive without an intermediate
15433        // non-`const` step.
15434        const _: () = assert!(matches!(
15435            classify_via_const_fn("wasi:http/proxy"),
15436            WitShape::Http
15437        ));
15438        const _: () = assert!(matches!(
15439            classify_via_const_fn("nats:events"),
15440            WitShape::PubSub
15441        ));
15442        const _: () = assert!(matches!(
15443            classify_via_const_fn("wasi:keyvalue/store"),
15444            WitShape::Store
15445        ));
15446        const _: () = assert!(matches!(classify_via_const_fn(""), WitShape::Capability));
15447        // Also assert const `as_str` routes through the const `classify`
15448        // on the same const path.
15449        const _: () = assert!(matches!(
15450            classify_via_const_fn("wasi:http/proxy").as_str().as_bytes(),
15451            b"http"
15452        ));
15453    }
15454
15455    #[test]
15456    fn wit_shape_from_wire_accepts_every_as_str_output() {
15457        // Fail-before-pass-after per-arm accept pin on the newly lifted
15458        // [`WitShape::from_wire`] reverse projection: every arm in
15459        // [`WitShape::ALL`] must parse back through `from_wire` when fed
15460        // its own [`WitShape::as_str`] output, landing on
15461        // `Some(same_variant)`. A regression that hand-rolled either
15462        // side's per-arm match without threading through the shared
15463        // four-string closed set would silently disagree on any future
15464        // arm rename (or a new arm the WIT-shape space grows — a
15465        // hypothetical `wasi:sockets/*` transport-layer shape, an
15466        // `oci:*` capability-import carrier per the sibling
15467        // [`wit_shape_matches`] docstring's trajectory bullet) and this
15468        // pin flags it at caixa-core build time rather than at a
15469        // downstream `feira app graph --by-wit-shape` consumer's silent
15470        // tag misclassification.
15471        //
15472        // Peer of the sibling
15473        // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_accepts_every_variant_slug_output`
15474        // (1e4cc81) /
15475        // `caixa_theme::style::tests::semantic_from_wire_accepts_every_as_str_output`
15476        // (e7bca7b) /
15477        // `caixa_lint::diagnostic::tests::fix_safety_from_wire_accepts_every_as_str_output`
15478        // (bd505a1) /
15479        // `caixa_lint::diagnostic::tests::severity_from_wire_accepts_every_as_str_output`
15480        // (5afff0e) /
15481        // `caixa_arch::report::tests::arch_verdict_from_wire_accepts_every_as_str_output`
15482        // (6afe564) /
15483        // `caixa_arch::invariants::tests::invariant_kind_from_wire_accepts_every_as_str_output`
15484        // (b9e4e61) round-trip pins on the peer caixa-provedor /
15485        // caixa-theme / caixa-lint / caixa-arch closed-set-enum
15486        // reverse-projection axes, and of the sibling
15487        // `crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`
15488        // (2aa6d23) /
15489        // `crate::dialeto::tests::caixa_dialeto_from_wire_accepts_every_as_str_output`
15490        // (d0e65ea) /
15491        // `placement_strategy_from_wire_accepts_every_lifted_constant`
15492        // (18c7342) /
15493        // `crate::dep::tests::dep_list_round_trips_through_as_str_and_from_wire`
15494        // (45ee563) /
15495        // `crate::render::tests::path_shape_violation_from_wire_accepts_every_as_str_output`
15496        // (aebd9c6) round-trip pins on the sibling caixa-core closed-
15497        // set typed-enum reverse-projection axes.
15498        for &variant in WitShape::ALL {
15499            let wire = variant.as_str();
15500            let parsed = WitShape::from_wire(wire).unwrap_or_else(|| {
15501                panic!(
15502                    "WitShape::from_wire({wire:?}) must accept every \
15503                     WitShape::as_str output — got None for the wire \
15504                     byte-string of {variant:?}"
15505                )
15506            });
15507            assert_eq!(
15508                parsed, variant,
15509                "WitShape::from_wire(WitShape::{variant:?}.as_str()) must \
15510                 return WitShape::{variant:?} — the (as_str, from_wire) \
15511                 pair must form a total round-trip on the closed four-arm \
15512                 WitShape arm-set",
15513            );
15514        }
15515        // Pin the exact per-arm accept-set so a future rebrand of the
15516        // census-label byte-strings ("http" / "pubsub" / "store" /
15517        // "capability") surfaces at this pin rather than at a downstream
15518        // consumer's silent tag drift.
15519        assert_eq!(WitShape::from_wire("http"), Some(WitShape::Http));
15520        assert_eq!(WitShape::from_wire("pubsub"), Some(WitShape::PubSub));
15521        assert_eq!(WitShape::from_wire("store"), Some(WitShape::Store));
15522        assert_eq!(
15523            WitShape::from_wire("capability"),
15524            Some(WitShape::Capability),
15525        );
15526    }
15527
15528    #[test]
15529    fn wit_shape_from_wire_rejects_unknown_byte_strings() {
15530        // Rejection pin on the [`WitShape::from_wire`] parser's
15531        // accept-set: any string outside the four-arm
15532        // [`WitShape::as_str`] output set must return [`None`]. A future
15533        // accidental widening of the accept-set (a case-insensitive
15534        // match that accepts `"HTTP"` / `"Http"`, a silent acceptance of
15535        // the PascalCase Debug-derived shapes `"Http"` / `"PubSub"` /
15536        // `"Store"` / `"Capability"` on the wire axis, a Levenshtein-
15537        // forgiving arm-lookup that admits typos, a silent absorption of
15538        // the sibling raw `:contratos :wit` identifiers [`Self::classify`]
15539        // consumes on the peer classifier axis — `"wasi:http/proxy"`,
15540        // `"nats:events"`, `"wasi:keyvalue/store"`, `"kafka:topic"`,
15541        // `"kv:cache"`, `"http:incoming"` — a silent absorption of the
15542        // paired [`WitTarget::label`] short-form tags every downstream
15543        // renderer already handles on the post-validation axis) would
15544        // silently drift the parser's accept-set from the emitter's — a
15545        // downstream re-loader that bound a prior emission's
15546        // [`Self::as_str`] output back to the typed enum through this
15547        // parser would then bind a malformed byte-string to a
15548        // plausibly-wrong typed arm the caller does not route through
15549        // any fallback, silently misclassifying the reloaded row.
15550        //
15551        // The raw `:contratos :wit` identifier vectors are load-bearing:
15552        // [`WitShape::classify`] is a *total* function on every `&str`
15553        // (falling through to [`WitShape::Capability`] on unknown
15554        // prefixes), so a caller who confuses the two axes and routes a
15555        // raw WIT identifier through [`from_wire`] instead of
15556        // [`classify`] must observe [`None`] here rather than a plausibly-
15557        // wrong `Some(WitShape::Capability)` silently — the peer axes
15558        // carry different accept-sets by design.
15559        //
15560        // Peer of the sibling
15561        // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_rejects_unknown_byte_strings`
15562        // (1e4cc81) /
15563        // `caixa_theme::style::tests::semantic_from_wire_rejects_unknown_byte_strings`
15564        // (e7bca7b) /
15565        // `caixa_lint::diagnostic::tests::fix_safety_from_wire_rejects_unknown_byte_strings`
15566        // (bd505a1) /
15567        // `caixa_lint::diagnostic::tests::severity_from_wire_rejects_unknown_byte_strings`
15568        // (5afff0e) /
15569        // `caixa_arch::report::tests::arch_verdict_from_wire_rejects_unknown_byte_strings`
15570        // (6afe564) /
15571        // `caixa_arch::invariants::tests::invariant_kind_from_wire_rejects_unknown_byte_strings`
15572        // (b9e4e61) rejection pins on the peer caixa-provedor /
15573        // caixa-theme / caixa-lint / caixa-arch axes, and of the sibling
15574        // `caixa_kind_from_wire_rejects_unknown_byte_strings` (2aa6d23),
15575        // `caixa_dialeto_from_wire_rejects_unknown_byte_strings`
15576        // (d0e65ea),
15577        // `placement_strategy_from_wire_rejects_unknown_byte_strings`
15578        // (18c7342),
15579        // `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
15580        // (45ee563), and
15581        // `path_shape_violation_from_wire_rejects_unknown_byte_strings`
15582        // (aebd9c6) rejection pins on the sibling caixa-core axes.
15583        for bad in [
15584            "",
15585            " ",
15586            "http ",
15587            " http",
15588            "HTTP",
15589            "Http",
15590            "PUBSUB",
15591            "PubSub",
15592            "pub_sub",
15593            "pub-sub",
15594            "STORE",
15595            "Store",
15596            "CAPABILITY",
15597            "Capability",
15598            "kv",
15599            "nats",
15600            "kafka",
15601            "wasi:http/proxy",
15602            "wasi:http/",
15603            "http:",
15604            "http:incoming",
15605            "nats:events",
15606            "kafka:topic",
15607            "wasi:keyvalue/store",
15608            "wasi:keyvalue/",
15609            "kv:cache",
15610            "kv:",
15611            "oci:capability",
15612            "wasi:sockets/tcp",
15613            "\u{200b}http",
15614            "http\u{200b}",
15615        ] {
15616            assert!(
15617                WitShape::from_wire(bad).is_none(),
15618                "WitShape::from_wire({bad:?}) must reject byte-strings \
15619                 outside the four-arm WitShape::as_str output set — got \
15620                 {:?}",
15621                WitShape::from_wire(bad),
15622            );
15623        }
15624    }
15625
15626    #[test]
15627    fn wit_shape_from_wire_and_classify_partition_the_axis() {
15628        // Cross-axis discipline pin: [`WitShape::classify`] is a total
15629        // function on the raw `:contratos :wit` identifier axis (every
15630        // `&str` classifies), while [`WitShape::from_wire`] is a partial
15631        // function on the census-label axis (the four
15632        // [`WitShape::as_str`] outputs and nothing else). The two axes
15633        // meet on exactly zero strings by construction — the four
15634        // census labels (`"http"` / `"pubsub"` / `"store"` /
15635        // `"capability"`) are not prefix-matched by any of
15636        // [`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
15637        // [`WIT_STORE_SHAPE_PREFIXES`], so on the shared four-string
15638        // census-label set:
15639        //
15640        //   * [`WitShape::from_wire`] returns `Some(<matching arm>)`
15641        //     per [`WitShape::as_str`]'s output;
15642        //   * [`WitShape::classify`] falls through to the
15643        //     [`WitShape::Capability`] catch-all fallback (since none of
15644        //     the payload-arm prefix sets begin with `"http"` /
15645        //     `"pubsub"` / `"store"` / `"capability"`).
15646        //
15647        // A future WIT-prefix set edit that accidentally started with
15648        // one of the four census labels (a hypothetical
15649        // `"http"` prefix directly, a `"pubsub://"` scheme addition, a
15650        // `"store:"` capability-carrier extension) would silently
15651        // collide the two axes on the same string — [`from_wire`] would
15652        // still yield the census-label arm while [`classify`] would
15653        // route the payload-arm dispatch through the accidental overlap.
15654        // Locking the partition here means such a prefix-set edit
15655        // trips this pin at caixa-core build time before the collision
15656        // becomes observable at any downstream consumer.
15657        for &variant in WitShape::ALL {
15658            let label = variant.as_str();
15659            // The census-label axis half — [`from_wire`] resolves to
15660            // the emitter's arm identity.
15661            assert_eq!(
15662                WitShape::from_wire(label),
15663                Some(variant),
15664                "WitShape::from_wire({label:?}) must resolve to the \
15665                 emitter's arm identity on the census-label axis",
15666            );
15667            // The raw-classifier axis half — [`classify`] falls through
15668            // to [`WitShape::Capability`] on every census label under
15669            // the current prefix set. Any future overlap trips here.
15670            assert_eq!(
15671                WitShape::classify(label),
15672                WitShape::Capability,
15673                "WitShape::classify({label:?}) must fall through to \
15674                 WitShape::Capability on every census label — a match \
15675                 to any payload arm here means a payload-prefix set \
15676                 has silently collided the census-label axis with the \
15677                 raw-classifier axis",
15678            );
15679        }
15680    }
15681
15682    #[test]
15683    fn wit_shape_try_from_str_routes_through_from_wire_accessor() {
15684        // Fail-before-pass-after byte-parity pin on the newly lifted
15685        // `impl TryFrom<&str> for WitShape` — asserts the standard-
15686        // library trait impl and the substrate-primitive
15687        // [`WitShape::from_wire`] `Option<Self>` accessor resolve to the
15688        // same four-arm census-label accept-set across every arm the
15689        // exhaustive [`WitShape::ALL`] slice enumerates. Any future
15690        // silent detour that routes the trait impl through a divergent
15691        // projection (a per-arm inline `match s { "http" =>
15692        // Ok(Self::Http), … }` re-inlining that opens a compile-time
15693        // link to the un-lifted arm-literal, a stray attribute drift
15694        // that silently splits the wire byte-string from every consumer
15695        // that reaches for this typed dispatch) trips at caixa-core test
15696        // time under `assert_eq!` rather than at a downstream
15697        // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
15698        // every one of the four arms [`WitShape::ALL`] carries so no
15699        // arm's projection is covered only by the sibling method-named
15700        // `from_wire` path.
15701        //
15702        // Peer of the sibling
15703        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
15704        // (3c83606),
15705        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
15706        // (bf33136),
15707        // [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
15708        // (6fd00cd),
15709        // [`crate::supervisor::tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
15710        // (5b828ed), and
15711        // [`crate::supervisor::tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
15712        // (6fdd0d9) round-trip pins on the sibling caixa-core closed-
15713        // set typed-enum trait-idiomatic reverse-projection axes.
15714        for &variant in WitShape::ALL {
15715            let wire = variant.as_str();
15716            assert_eq!(
15717                <WitShape as TryFrom<&str>>::try_from(wire),
15718                Ok(variant),
15719                "TryFrom<&str> impl on WitShape must round-trip \
15720                 WitShape::{variant:?}.as_str() = {wire:?} back to \
15721                 Ok(WitShape::{variant:?}) — divergence from \
15722                 WitShape::from_wire signals a silent detour off the \
15723                 substrate-primitive accessor"
15724            );
15725            assert_eq!(
15726                <WitShape as TryFrom<&str>>::try_from(wire).ok(),
15727                WitShape::from_wire(wire),
15728                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
15729                 WitShape::from_wire on the same input"
15730            );
15731        }
15732    }
15733
15734    #[test]
15735    fn wit_shape_try_from_str_rejects_unknown_byte_strings() {
15736        // Rejection witness on the `impl TryFrom<&str> for WitShape` —
15737        // sweeps a candidate set of byte-strings outside the four-arm
15738        // census-label wire accept-set the sibling [`WitShape::as_str`]
15739        // emits and asserts every one lands on `Err(())`, so a future
15740        // accidental widening of the trait impl's accept-set (a stray
15741        // additional `_ if s.eq_ignore_ascii_case("http") => Ok(…)`
15742        // case-fold path, a silent inclusion of a PascalCase rebrand of
15743        // the wire byte-string that would collide the two-axis split the
15744        // sibling `wit_shape_from_wire_rejects_unknown_byte_strings` pin
15745        // makes load-bearing, a silent overlap with the raw WIT
15746        // identifier accept-set the paired [`WitShape::classify`] total
15747        // function consumes on the sibling axis that the
15748        // `wit_shape_from_wire_and_classify_partition_the_axis` cross-
15749        // axis discipline pin locks the accept-sets against) trips at
15750        // caixa-core test time. The candidate set includes the empty
15751        // string, whitespace-only padding, PascalCase rebrand candidates
15752        // (`"Http"`, `"PubSub"`), snake_case rebrand candidates
15753        // (`"pub_sub"`), uppercase rebrand candidates (`"HTTP"`,
15754        // `"CAPABILITY"`), kebab-case rebrand candidates (`"pub-sub"`),
15755        // trailing/leading-whitespace-padded canonical scalars, the
15756        // trailing-newline shape, English-rebrand candidates
15757        // (`"messaging"`, `"cache"`), raw `:contratos :wit` identifiers
15758        // the sibling [`WitShape::classify`] axis consumes
15759        // (`"wasi:http/proxy"`, `"nats:events"`,
15760        // `"wasi:keyvalue/store"`) that must not silently leak across
15761        // the two-axis partition, the residual `"?"` and JSON-quoted
15762        // `"\"http\""` shape.
15763        //
15764        // Peer of the sibling
15765        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
15766        // (3c83606),
15767        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_rejects_unknown_byte_strings`]
15768        // (bf33136),
15769        // [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
15770        // (6fd00cd),
15771        // [`crate::supervisor::tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
15772        // (5b828ed), and
15773        // [`crate::supervisor::tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
15774        // (6fdd0d9) rejection witnesses.
15775        let rejected: &[&str] = &[
15776            "",
15777            " ",
15778            "\n",
15779            "\t",
15780            "Http",
15781            "HTTP",
15782            "PubSub",
15783            "PUBSUB",
15784            "Store",
15785            "STORE",
15786            "Capability",
15787            "CAPABILITY",
15788            "pub-sub",
15789            "pub_sub",
15790            "pubSub",
15791            "http ",
15792            " http",
15793            " store ",
15794            "capability\n",
15795            "http/",
15796            "messaging",
15797            "cache",
15798            "wasi:http/proxy",
15799            "wasi:keyvalue/store",
15800            "nats:events",
15801            "?",
15802            "\"http\"",
15803        ];
15804        for &input in rejected {
15805            assert_eq!(
15806                <WitShape as TryFrom<&str>>::try_from(input),
15807                Err(()),
15808                "TryFrom<&str> impl on WitShape must reject the \
15809                 non-wire byte-string {input:?} — silent acceptance \
15810                 signals an accept-set widening off the paired \
15811                 WitShape::from_wire resolver, or a cross-axis leak \
15812                 from the raw-identifier axis WitShape::classify consumes"
15813            );
15814        }
15815    }
15816
15817    #[test]
15818    fn wit_shape_try_from_str_and_from_wire_partition_the_accept_set() {
15819        // Cross-axis partition pin locking the newly lifted
15820        // `impl TryFrom<&str> for WitShape` and the substrate-primitive
15821        // [`WitShape::from_wire`] accessor to the same `Option<Self>`
15822        // output on every input — the two axes converge on the same
15823        // partition of `&str` by construction, and this pin asserts
15824        // that convergence directly rather than only through
15825        // [`WitShape::ALL`]'s per-arm sweep. Any future divergence (a
15826        // stray case-fold path on the trait axis that widens acceptance
15827        // past what `from_wire` admits, a silent per-arm short-circuit
15828        // that returns `Err(())` on an input `from_wire` accepts) trips
15829        // here under `assert_eq!` on every input in the sweep.
15830        //
15831        // Sweeps the four accepted census labels plus a representative
15832        // rejection set covering the same categories the sibling
15833        // `wit_shape_try_from_str_rejects_unknown_byte_strings` pin
15834        // enumerates, so a regression on either axis surfaces at the
15835        // partition pin rather than at a downstream consumer's silent
15836        // observation split.
15837        //
15838        // Peer of the sibling
15839        // [`crate::supervisor::tests::restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
15840        // (5b828ed) and
15841        // [`crate::supervisor::tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
15842        // (6fdd0d9) cross-axis partition pins.
15843        let inputs: &[&str] = &[
15844            "http",
15845            "pubsub",
15846            "store",
15847            "capability",
15848            "",
15849            " ",
15850            "Http",
15851            "PubSub",
15852            "HTTP",
15853            "pub-sub",
15854            "http ",
15855            "wasi:http/proxy",
15856            "wasi:keyvalue/store",
15857            "nats:events",
15858            "messaging",
15859            "?",
15860        ];
15861        for &input in inputs {
15862            assert_eq!(
15863                <WitShape as TryFrom<&str>>::try_from(input).ok(),
15864                WitShape::from_wire(input),
15865                "TryFrom<&str> and from_wire must agree on WitShape \
15866                 for {input:?} — the trait-idiomatic and method-named \
15867                 axes must partition the accept-set identically"
15868            );
15869        }
15870    }
15871
15872    #[test]
15873    fn wit_shape_from_into_static_str_routes_through_as_str_accessor() {
15874        // Fail-before-pass-after byte-parity pin on the newly lifted
15875        // `impl From<WitShape> for &'static str` — asserts the standard-
15876        // library trait impl and the substrate-primitive
15877        // [`WitShape::as_str`] `pub const fn` accessor resolve to the
15878        // same four-arm census-label emit-set across every arm the
15879        // exhaustive [`WitShape::ALL`] slice enumerates. Any future
15880        // silent detour that routes the trait impl through a divergent
15881        // projection (a per-arm inline `match shape { Http => "http", …
15882        // }` re-inlining that opens a compile-time link to the un-lifted
15883        // arm-literal outside the paired [`WitShape::as_str`] dispatch,
15884        // an accidental swap onto the sibling raw-identifier axis
15885        // [`WitShape::classify`] consumes that would collide the two-axis
15886        // wire/classifier split the sibling
15887        // `wit_shape_from_wire_and_classify_partition_the_axis` pin makes
15888        // load-bearing) trips at caixa-core test time under `assert_eq!`
15889        // rather than at a downstream `impl Into<&'static str>`-bound
15890        // consumer's silent split. Sweeps every one of the four arms
15891        // [`WitShape::ALL`] carries so no arm's projection is covered
15892        // only by the sibling method-named `as_str` /
15893        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
15894        // `<&'static str as From<WitShape>>::from` output in four
15895        // `const`-shape bindings against the paired [`WitShape::as_str`]
15896        // `pub const fn` accessor to make the `'static` lifetime promise
15897        // a build-time invariant — a future accidental downgrade of any
15898        // of the four arms' inline census-label byte-strings to a non-
15899        // `&'static str` (a `String::leak()`-produced return, a
15900        // `Box::leak`-cast, an intermediate lifetime-erasing helper)
15901        // trips at caixa-core build time rather than at a downstream
15902        // `'static`-bound consumer.
15903        //
15904        // Peer of the sibling
15905        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
15906        // (523157d),
15907        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
15908        // (9fb37d0),
15909        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
15910        // (edb827b),
15911        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
15912        // (c189a6f), and
15913        // [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
15914        // (afa3562) pins on the sibling closed-set typed-enum forward-
15915        // projection axes — extends the trait-idiomatic forward-
15916        // projection axis onto the sixth closed-set fieldless typed
15917        // enum on the caixa surface (the second M3-mesh-primitive-
15918        // defining slot enum, the `:contratos :wit` census-label axis
15919        // the caixa-mesh renderer keys off end-to-end).
15920        const HTTP: &str = WitShape::Http.as_str();
15921        const PUBSUB: &str = WitShape::PubSub.as_str();
15922        const STORE: &str = WitShape::Store.as_str();
15923        const CAPABILITY: &str = WitShape::Capability.as_str();
15924        for &variant in WitShape::ALL {
15925            let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
15926            let via_method: &'static str = variant.as_str();
15927            assert_eq!(
15928                via_trait, via_method,
15929                "From<WitShape> for &'static str impl must round-trip \
15930                 WitShape::{variant:?} to the same census-label \
15931                 byte-string WitShape::as_str returns — divergence \
15932                 signals a silent detour off the substrate-primitive \
15933                 accessor"
15934            );
15935            let via_into: &'static str = variant.into();
15936            assert_eq!(
15937                via_into, via_method,
15938                "Into<&'static str>::into on WitShape::{variant:?} must \
15939                 byte-equal WitShape::as_str on the same input — the \
15940                 blanket-derived Into shape must resolve to the same \
15941                 as_str dispatch as the explicit From impl"
15942            );
15943        }
15944        assert_eq!(
15945            [HTTP, PUBSUB, STORE, CAPABILITY],
15946            ["http", "pubsub", "store", "capability"],
15947            "const-context WitShape::as_str must resolve to the four \
15948             canonical census-label byte-strings — a future accidental \
15949             downgrade of any arm to a non-const or non-static byte-\
15950             string breaks the `&'static str`-lifetime promise the \
15951             paired From<WitShape> for &'static str impl carries by \
15952             construction"
15953        );
15954    }
15955
15956    #[test]
15957    fn wit_shape_from_into_static_str_and_as_str_partition_the_emit_set() {
15958        // Cross-axis partition pin: the paired trait-idiomatic
15959        // `From<WitShape> for &'static str` forward projection and the
15960        // method-named [`WitShape::as_str`] forward projection must
15961        // resolve identically on *every* arm, not just the ones named
15962        // in the primary byte-parity pin above. Sweeps every
15963        // [`WitShape::ALL`] arm and asserts the trait's `From::from`
15964        // output byte-equals the method-named accessor's return-value
15965        // on each, locking the two forward-projection paths together by
15966        // construction so any future detour (a stray `From` special-case
15967        // that lands on a divergent per-arm literal outside the paired
15968        // `as_str` dispatch, a hypothetical rebrand touching one axis
15969        // without the other) trips at caixa-core test time.
15970        //
15971        // Peer of the sibling forward-projection partition pins
15972        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
15973        // (523157d),
15974        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
15975        // (9fb37d0),
15976        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
15977        // (edb827b),
15978        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
15979        // (c189a6f), and
15980        // [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
15981        // (afa3562) — extends the round-trip discipline onto the sixth
15982        // closed-set typed enum on the caixa surface, closing the two-
15983        // way `Self ↔ &'static str` round-trip on the trait-idiomatic
15984        // pair (`From<Self> for &'static str` + `TryFrom<&str> for
15985        // Self`) as well as the pre-existing method-named pair
15986        // (`as_str` + `from_wire`).
15987        for &variant in WitShape::ALL {
15988            let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
15989            let via_method: &'static str = variant.as_str();
15990            assert_eq!(
15991                via_trait, via_method,
15992                "From<WitShape> for &'static str and WitShape::as_str \
15993                 must resolve identically on WitShape::{variant:?} — \
15994                 divergence signals the two forward-projection paths \
15995                 have drifted onto different emit-sets"
15996            );
15997        }
15998        // Round-trip witness: every arm's forward `From` output re-parses
15999        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
16000        // to the original variant. Closes the two-way `WitShape ↔
16001        // &'static str` round-trip on the trait-idiomatic axis pair
16002        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
16003        // axis pair requires — the emit-side [`WitShape::as_str`] and
16004        // the parse-side [`WitShape::from_wire`] dispatch on the same
16005        // four inline census-label byte-strings by construction), and
16006        // in the same way the peer [`PlacementStrategy`] axis pair
16007        // (afa3562) closes on its three-arm surface — mirroring the
16008        // pre-existing method-named `as_str` + `from_wire` round-trip
16009        // on the substrate-primitive axis pair.
16010        for &variant in WitShape::ALL {
16011            let emitted: &'static str = variant.into();
16012            let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
16013            assert_eq!(
16014                re_parsed,
16015                Ok(variant),
16016                "trait-idiomatic axis pair must round-trip \
16017                 WitShape::{variant:?} through `.into::<&'static \
16018                 str>()` and back through `TryFrom<&str>` — a break \
16019                 signals the forward-emit and reverse-parse axes have \
16020                 drifted onto different vocabularies"
16021            );
16022        }
16023    }
16024
16025    #[test]
16026    fn wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor() {
16027        // Fail-before-pass-after byte-parity pin on the newly lifted
16028        // `impl From<&WitShape> for &'static str` — asserts the
16029        // borrowed-input standard-library trait impl and the
16030        // substrate-primitive [`WitShape::as_str`] `pub const fn`
16031        // accessor resolve to the same four-arm census-label emit-set
16032        // across every arm the exhaustive [`WitShape::ALL`] slice
16033        // enumerates. Rust's `From` trait does not auto-derive the
16034        // borrowed-input sibling from a paired owned-input impl (no
16035        // `impl<T, U> From<&T> for U where T: Copy, U: From<T>`
16036        // blanket in `core`), so the borrowed-input axis is a distinct
16037        // trait-idiomatic surface that a `.iter().map(Into::into)`
16038        // shape over [`WitShape::ALL`] (whose iterator yields
16039        // `&WitShape`, not `WitShape`) reaches through this impl and
16040        // no other — the paired owned-input [`From<WitShape>`] impl
16041        // requires an explicit `.copied()` / dereference before the
16042        // trait fires. Materializes the `<&'static str as
16043        // From<&WitShape>>::from` output in a `const`-shape binding to
16044        // make the `'static` lifetime promise a build-time invariant.
16045        // Peer of the sibling
16046        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
16047        // (64aa742) /
16048        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
16049        // (5ab993a) /
16050        // [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
16051        // (807b0b5) /
16052        // [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
16053        // (e941836) /
16054        // [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
16055        // (842c7f3) /
16056        // [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
16057        // (4d941d8) pins on the sibling closed-set typed-enum
16058        // borrowed-input forward-projection axes — extends the
16059        // borrowed-input axis onto the second M3-mesh-primitive-
16060        // defining closed-set typed enum on the caixa surface (the
16061        // `:contratos :wit` census-label axis the caixa-mesh renderer
16062        // keys off end-to-end for per-edge programs.yaml fan-out).
16063        const HTTP: &str = WitShape::Http.as_str();
16064        const PUBSUB: &str = WitShape::PubSub.as_str();
16065        const STORE: &str = WitShape::Store.as_str();
16066        const CAPABILITY: &str = WitShape::Capability.as_str();
16067        for variant in WitShape::ALL {
16068            let via_trait: &'static str = <&'static str as From<&WitShape>>::from(variant);
16069            let via_method: &'static str = variant.as_str();
16070            assert_eq!(
16071                via_trait, via_method,
16072                "From<&WitShape> for &'static str impl must round-trip \
16073                 &WitShape::{variant:?} to the same census-label \
16074                 byte-string WitShape::as_str returns — divergence \
16075                 signals a silent detour off the substrate-primitive \
16076                 accessor"
16077            );
16078            let via_into: &'static str = variant.into();
16079            assert_eq!(
16080                via_into, via_method,
16081                "Into<&'static str>::into on &WitShape::{variant:?} \
16082                 must byte-equal WitShape::as_str on the same input — \
16083                 the blanket-derived Into shape must resolve to the \
16084                 same as_str dispatch as the explicit From impl"
16085            );
16086        }
16087        assert_eq!(
16088            [HTTP, PUBSUB, STORE, CAPABILITY],
16089            ["http", "pubsub", "store", "capability"],
16090            "const-context WitShape::as_str must resolve to the four \
16091             canonical census-label byte-strings — the borrowed-input \
16092             From<&WitShape> for &'static str impl inherits its \
16093             `'static` lifetime promise from the same accessor the \
16094             owned-input sibling routes through"
16095        );
16096    }
16097
16098    #[test]
16099    fn wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
16100        // Cross-axis partition pin: the paired trait-idiomatic
16101        // owned-input `From<WitShape> for &'static str` (56998ec
16102        // campaign-shape) and borrowed-input `From<&WitShape> for
16103        // &'static str` (this lift) forward projections must resolve
16104        // identically on every arm, locking the two input-shape paths
16105        // together so any future detour trips at caixa-core test time.
16106        // Then a witness that a `.iter().map(Into::into)` pipe over
16107        // [`WitShape::ALL`] (whose iterator yields `&WitShape`)
16108        // materializes the four-arm accept-set through the borrowed-
16109        // input axis alone — the exact shape a future M4 admission-
16110        // webhook rejection body's accepted-set enumeration, a future
16111        // substrate-wide per-arm diagnostic column, or a
16112        // `HashMap::<&'static str, WitShape>::from_iter(
16113        //     WitShape::ALL.iter().map(|s| (s.into(), *s)))`-style
16114        // per-shape lookup reaches through — closing the two-way
16115        // owned/borrowed input-shape symmetry on the M3 slot enum's
16116        // forward-projection trait-idiomatic axis. Peer of the sibling
16117        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
16118        // (64aa742) /
16119        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
16120        // (5ab993a) /
16121        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
16122        // (807b0b5) /
16123        // [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
16124        // (e941836) /
16125        // [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
16126        // (842c7f3) /
16127        // [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
16128        // (4d941d8) partition pins on the sibling closed-set typed-
16129        // enum discriminator axes — extends the borrowed-input axis
16130        // discipline onto the second M3-mesh-primitive-defining
16131        // closed-set typed enum on the caixa surface (the `:contratos
16132        // :wit` census-label axis). Also closes the direct two-way
16133        // `&Self → &'static str → Self` round-trip via the paired
16134        // [`TryFrom<&str>`] axis — unlike the peer [`crate::CaixaKind`]
16135        // axis pair (whose forward `From` emits lowercase Portuguese
16136        // diagnostic bytes while the reverse `TryFrom` parses
16137        // `PascalCase` wire bytes, forcing the round-trip through an
16138        // intermediate wire-vocab hop), the [`WitShape::as_str`] emit
16139        // and [`WitShape::from_wire`] parse share the same census-
16140        // label vocabulary by construction, so the borrowed-input
16141        // forward axis and the reverse axis compose directly.
16142        for &variant in WitShape::ALL {
16143            let owned: &'static str = <&'static str as From<WitShape>>::from(variant);
16144            let borrowed: &'static str = <&'static str as From<&WitShape>>::from(&variant);
16145            assert_eq!(
16146                owned, borrowed,
16147                "From<WitShape> and From<&WitShape> for &'static str \
16148                 must resolve identically on WitShape::{variant:?} — \
16149                 divergence signals the owned-input and borrowed-input \
16150                 forward-projection paths have drifted onto different \
16151                 emit-sets"
16152            );
16153        }
16154        let via_iter: Vec<&'static str> = WitShape::ALL.iter().map(Into::into).collect();
16155        let via_method: Vec<&'static str> = WitShape::ALL.iter().map(|s| s.as_str()).collect();
16156        assert_eq!(
16157            via_iter, via_method,
16158            "`.iter().map(Into::into)` over WitShape::ALL must \
16159             byte-equal `.iter().map(|s| s.as_str())` on every arm — \
16160             the borrowed-input `From<&WitShape> for &'static str` \
16161             axis is what makes the `.iter().map(Into::into)` shape \
16162             route through the substrate-primitive `WitShape::as_str` \
16163             accessor rather than through a per-call-site `.copied()` \
16164             / dereference detour"
16165        );
16166        for variant in WitShape::ALL {
16167            let emitted: &'static str = variant.into();
16168            let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
16169            assert_eq!(
16170                re_parsed,
16171                Ok(*variant),
16172                "trait-idiomatic borrowed-input forward-projection + \
16173                 reverse-projection axis pair must round-trip \
16174                 &WitShape::{variant:?} through `.into::<&'static \
16175                 str>()` (via the borrowed-input axis) and back \
16176                 through `TryFrom<&str>` — a break signals the \
16177                 borrowed-input forward-emit and reverse-parse axes \
16178                 have drifted onto different vocabularies"
16179            );
16180        }
16181    }
16182
16183    #[test]
16184    fn wit_shape_classify_matches_wit_contract_target_arm_on_valid_inputs() {
16185        // Cross-surface equivalence pin: for every canonical
16186        // truth-table row that also validates cleanly through
16187        // [`WitContract::target`], the pre-projection [`WitShape`] arm
16188        // matches the post-projection [`WitTarget`] arm — the pre- and
16189        // post-validation classifications agree on the arm identity
16190        // even though the payload-carrying view carries additional
16191        // per-arm information. A future edit that reroutes
16192        // `WitContract::target`'s HTTP/pubsub/store dispatch through a
16193        // different predicate than the [`WitShape::classify`] the free
16194        // predicates now route through would trip here at the offending
16195        // row rather than at a downstream renderer.
16196        //
16197        // The Capability arm is excluded from the paired sweep: an
16198        // arbitrary Capability-classified string need not pass
16199        // [`crate::render::is_wit_world_ref`]'s value-shape gate, so
16200        // `WitContract::target` would raise `ContratoWitInvalid`
16201        // rather than return `WitTarget::Capability`; the arm-identity
16202        // agreement lives in the payload-arm rows.
16203        //
16204        // Per-row shape: `(wit, endpoint, subject, slot)` — one row per
16205        // payload arm with its shape's canonical payload field filled
16206        // and the peer fields `None`. Named type-alias closes the
16207        // `clippy::type_complexity` warning the raw tuple triggers.
16208        type WitTargetArmRow = (
16209            &'static str,
16210            Option<&'static str>,
16211            Option<&'static str>,
16212            Option<&'static str>,
16213        );
16214        let cases: [WitTargetArmRow; 6] = [
16215            ("wasi:http/proxy", Some("/x"), None, None),
16216            ("http:incoming", Some("/x"), None, None),
16217            ("nats:events", None, Some("subject.x"), None),
16218            ("kafka:topic", None, Some("subject.x"), None),
16219            ("wasi:keyvalue/store", None, None, Some("bucket/x")),
16220            ("kv:cache", None, None, Some("bucket/x")),
16221        ];
16222        for (wit, endpoint, subject, slot) in cases {
16223            let c = WitContract {
16224                de: "cart".into(),
16225                para: "catalog".into(),
16226                wit: wit.to_string(),
16227                endpoint: endpoint.map(str::to_string),
16228                subject: subject.map(str::to_string),
16229                slot: slot.map(str::to_string),
16230            };
16231            let target = c.target().unwrap_or_else(|e| {
16232                panic!("expected target() to validate for wit={wit:?}, got: {e}")
16233            });
16234            let shape = WitShape::classify(wit);
16235            // Match arm-for-arm — the raw &str classifier and the
16236            // validated payload view must agree on which arm carries
16237            // the edge.
16238            let agree = matches!(
16239                (shape, target),
16240                (WitShape::Http, WitTarget::Http { .. })
16241                    | (WitShape::PubSub, WitTarget::PubSub { .. })
16242                    | (WitShape::Store, WitTarget::Store { .. })
16243                    | (WitShape::Capability, WitTarget::Capability)
16244            );
16245            assert!(
16246                agree,
16247                "WitShape::classify({wit:?}) and WitContract::target arm-identity disagree",
16248            );
16249        }
16250    }
16251
16252    #[test]
16253    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
16254        // Composition-witness pin: [`wit_shape_matches`] agrees with
16255        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
16256        // dispatch (the prior non-`const` implementation) across
16257        // boundary lengths — empty `wit`, empty prefix, one-byte
16258        // slack, prefix longer than `wit`, one-byte trailing slack.
16259        // The rewrite to a byte-level manual starts_with loop (the
16260        // enabler for the `pub const fn` posture) must not change any
16261        // truth-table entry on the canonical accept-set — this pin
16262        // sweeps a targeted boundary corpus and asserts byte-for-byte
16263        // agreement, locking the const-fn rewrite's semantics against
16264        // the prior iterator body by construction.
16265        let prefixes = &["wasi:http/", "http:"][..];
16266        let cases: [(&str, bool); 12] = [
16267            ("wasi:http/proxy", true),
16268            ("wasi:http/", true), // exact-length match on prefix
16269            ("wasi:http", false), // one byte short
16270            ("http:", true),
16271            ("http:incoming", true),
16272            ("http", false), // one byte short
16273            ("", false),
16274            ("wasi:https/proxy", false),
16275            ("nats:events", false),
16276            ("HTTPS:", false), // uppercase — no case-fold in classifier
16277            ("wasi:HTTP/proxy", false),
16278            ("wasi:http", false),
16279        ];
16280        for (wit, expected) in cases {
16281            assert_eq!(
16282                wit_shape_matches(wit, prefixes),
16283                expected,
16284                "wit_shape_matches disagrees with reference at wit={wit:?}",
16285            );
16286            // Byte-equal to the iterator body it replaced.
16287            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
16288            assert_eq!(
16289                wit_shape_matches(wit, prefixes),
16290                via_iter,
16291                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
16292            );
16293        }
16294        // Empty prefix set → always false regardless of `wit`.
16295        let empty: &[&str] = &[];
16296        assert!(!wit_shape_matches("", empty));
16297        assert!(!wit_shape_matches("wasi:http/proxy", empty));
16298        // Empty prefix inside a non-empty set → always true (every
16299        // string starts with the empty string, matching the
16300        // iterator body's semantics on `str::starts_with("")`).
16301        let contains_empty: &[&str] = &["nats:", ""];
16302        assert!(wit_shape_matches("", contains_empty));
16303        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
16304    }
16305
16306    #[test]
16307    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
16308        // 4-way partition-witness pin: for every canonical prefix in
16309        // the payload-arm accept-sets, exactly one of the four
16310        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
16311        // [`WitContract::is_store`] / [`WitContract::is_capability`]
16312        // predicates returns `true` and the other three return `false`
16313        // — the four-arm partition witness that locks the substrate's
16314        // WIT-shape-space closure on the pre-projection axis load-
16315        // bearing. A future arm addition (a hypothetical fourth
16316        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
16317        // shape) that landed on one of the payload-arm predicates
16318        // without shrinking [`WitContract::is_capability`]'s accept-set
16319        // would surface here as two arms returning `true` simultaneously
16320        // — a partition-witness break the pin catches at caixa-core
16321        // build time rather than a silent per-consumer misclassification
16322        // at renderer emit time. Peer of the sibling `WitTarget`-side
16323        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
16324        // partition-witness pin on the post-projection payload-scalar
16325        // arm-set — extends the discipline onto the pre-projection
16326        // 4-arm shape-space.
16327        for shape_set in [
16328            WIT_HTTP_SHAPE_PREFIXES,
16329            WIT_PUBSUB_SHAPE_PREFIXES,
16330            WIT_STORE_SHAPE_PREFIXES,
16331        ] {
16332            for prefix in shape_set {
16333                let c = WitContract {
16334                    de: "cart".into(),
16335                    para: "catalog".into(),
16336                    wit: format!("{prefix}x"),
16337                    endpoint: None,
16338                    subject: None,
16339                    slot: None,
16340                };
16341                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
16342                    .iter()
16343                    .filter(|&&b| b)
16344                    .count();
16345                assert_eq!(
16346                    hits,
16347                    1,
16348                    "WitContract WIT-shape 4-way predicate partition must \
16349                     admit exactly one arm per canonical prefix; got {hits} \
16350                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
16351                     is_capability={})",
16352                    c.wit,
16353                    c.is_http(),
16354                    c.is_pubsub(),
16355                    c.is_store(),
16356                    c.is_capability(),
16357                );
16358            }
16359        }
16360        // Capability-arm sweep: two representative capability shapes
16361        // (a bare WIT world outside the three payload-arm prefix sets,
16362        // and the deliberately-shaped empty string that
16363        // [`crate::render::is_wit_world_ref`] rejects at
16364        // [`WitContract::target`] time but which the pure classifier
16365        // still admits — see the method docstring's "purely syntactic
16366        // classification" note). Both must land on the fourth arm
16367        // exclusively, so the partition witness holds across the full
16368        // 4-arm closure.
16369        for wit in ["custom:capability-only", ""] {
16370            let c = WitContract {
16371                de: "cart".into(),
16372                para: "catalog".into(),
16373                wit: wit.into(),
16374                endpoint: None,
16375                subject: None,
16376                slot: None,
16377            };
16378            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
16379                .iter()
16380                .filter(|&&b| b)
16381                .count();
16382            assert_eq!(
16383                hits, 1,
16384                "WitContract WIT-shape 4-way predicate partition must \
16385                 admit exactly one arm on Capability-shaped wit={wit:?}"
16386            );
16387            assert!(
16388                c.is_capability(),
16389                "wit={wit:?} must project onto the Capability arm"
16390            );
16391        }
16392    }
16393
16394    #[test]
16395    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
16396        // Composition-witness pin: [`WitContract::is_capability`] is the
16397        // exact-inverse disjunction of the sibling payload-arm predicate
16398        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
16399        // [`WitContract::is_store`]. A future reimplementation that
16400        // grew its own prefix-set scan (e.g. inlining a fourth
16401        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
16402        // own today) rather than delegating to the sibling trio would
16403        // drift loudly here — the composition contract binds the
16404        // fourth-arm predicate to the exact-inverse of the three
16405        // payload-arm predicates, so any rebrand of any prefix-set const
16406        // flows through this method by construction without a
16407        // coordinated per-consumer rewrite. Sweeps the union of the
16408        // three payload-arm prefix sets plus two Capability-shaped
16409        // shapes (a bare non-prefix-matching WIT world, the deliberately-
16410        // empty string the pure classifier still admits per the method
16411        // docstring's "purely syntactic classification" note).
16412        let mut cases: Vec<String> = Vec::new();
16413        for shape_set in [
16414            WIT_HTTP_SHAPE_PREFIXES,
16415            WIT_PUBSUB_SHAPE_PREFIXES,
16416            WIT_STORE_SHAPE_PREFIXES,
16417        ] {
16418            for prefix in shape_set {
16419                cases.push(format!("{prefix}x"));
16420            }
16421        }
16422        cases.push("custom:capability-only".to_string());
16423        cases.push(String::new());
16424        for wit in cases {
16425            let c = WitContract {
16426                de: "cart".into(),
16427                para: "catalog".into(),
16428                wit: wit.clone(),
16429                endpoint: None,
16430                subject: None,
16431                slot: None,
16432            };
16433            assert_eq!(
16434                c.is_capability(),
16435                !c.is_http() && !c.is_pubsub() && !c.is_store(),
16436                "WitContract::is_capability must equal \
16437                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
16438            );
16439        }
16440    }
16441
16442    #[test]
16443    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
16444        // Cross-projection-witness pin: whenever [`WitContract::target`]
16445        // succeeds, the pre-projection [`WitContract::is_capability`]
16446        // classification agrees with the post-projection
16447        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
16448        // predicate — the 4-arm typed partition on the substrate's
16449        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
16450        // partition on the pre-projection axis line up by construction.
16451        // A future divergence between the two axes (a peer
16452        // [`WitTarget`] variant addition that landed on the typed-view
16453        // surface without a peer prefix-set + [`WitContract`] predicate
16454        // extension, or vice versa) would surface here at caixa-core
16455        // build time rather than a silent per-consumer split at renderer
16456        // emit time. Peer of the sibling pre-/post-projection
16457        // agreement pins the payload-carrier trio
16458        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
16459        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
16460        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
16461        // post-projection — b11bb49 trio lift) already carry across the
16462        // three payload arms — this pin closes the pair on the fourth
16463        // payload-less arm.
16464        let http = WitContract {
16465            de: "cart".into(),
16466            para: "catalog".into(),
16467            wit: "wasi:http/proxy".into(),
16468            endpoint: Some("/x".into()),
16469            subject: None,
16470            slot: None,
16471        };
16472        assert!(!http.is_capability());
16473        assert!(!http.target().unwrap().is_capability());
16474
16475        let nats = WitContract {
16476            de: "cart".into(),
16477            para: "catalog".into(),
16478            wit: "nats:pub-sub".into(),
16479            endpoint: None,
16480            subject: Some("events.x".into()),
16481            slot: None,
16482        };
16483        assert!(!nats.is_capability());
16484        assert!(!nats.target().unwrap().is_capability());
16485
16486        let kv = WitContract {
16487            de: "cart".into(),
16488            para: "catalog".into(),
16489            wit: "wasi:keyvalue/store".into(),
16490            endpoint: None,
16491            subject: None,
16492            slot: Some("checkout/$orderId".into()),
16493        };
16494        assert!(!kv.is_capability());
16495        assert!(!kv.target().unwrap().is_capability());
16496
16497        let cap = WitContract {
16498            de: "cart".into(),
16499            para: "catalog".into(),
16500            wit: "custom:capability-only".into(),
16501            endpoint: None,
16502            subject: None,
16503            slot: None,
16504        };
16505        assert!(cap.is_capability());
16506        assert!(cap.target().unwrap().is_capability());
16507    }
16508
16509    #[test]
16510    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
16511        // Fail-before-pass-after pin on the [`WitContract`] pre-
16512        // projection accessor family's `const`-eval-surface posture.
16513        // Each of the three per-`:contratos` byte-string scalar
16514        // accessors ([`WitContract::source`] / [`WitContract::destination`]
16515        // / [`WitContract::world_ref`], each projecting through
16516        // `String::as_str` — const-stable since Rust 1.87, well within
16517        // the workspace MSRV) and each of the four peer WIT-shape
16518        // predicates ([`WitContract::is_http`] /
16519        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
16520        // [`WitContract::is_capability`], each composing
16521        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
16522        // free-function classifier family the sibling
16523        // [`wit_shape_classifier_family_is_const_fn`] pin already
16524        // anchors on the raw `&str → bool` axis) must be `pub const fn`
16525        // — any future accidental downgrade to non-`const` fails the
16526        // `const fn` wrappers below at caixa-core build time with E0015
16527        // (`cannot call non-const function`), strictly stronger than a
16528        // runtime `assert!` and strictly stronger than a
16529        // module-scope `const _: () = assert!(…)` pin (which cannot be
16530        // formed on a `&WitContract` fixture because the type's
16531        // `String` / `Option<String>` carriers rule out `const`-context
16532        // construction; the `const fn` wrapper is the load-bearing
16533        // shape that side-steps the destructor-in-const restriction on
16534        // the value axis while still pinning the `const`-fn posture on
16535        // the callee).
16536        //
16537        // Peer of the sibling free-function classifier pin
16538        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
16539        // raw `&str → bool` axis — this pin extends the same
16540        // `const`-eval-surface discipline onto the peer method surface
16541        // that composes through those free-function classifiers, and
16542        // simultaneously onto the underlying per-`:contratos`
16543        // byte-string scalar-accessor trio each predicate reads
16544        // through. Sibling of the peer M3
16545        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
16546        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
16547        // M2
16548        // [`child_spec_restart_accessor_is_const_fn`] /
16549        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
16550        // and M3
16551        // [`placement_estrategia_accessor_is_const_fn`] /
16552        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
16553        // sibling `const`-eval-surface-pass axes.
16554        const fn source_via_const_fn(c: &WitContract) -> &str {
16555            c.source()
16556        }
16557        const fn destination_via_const_fn(c: &WitContract) -> &str {
16558            c.destination()
16559        }
16560        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
16561            c.world_ref()
16562        }
16563        const fn is_http_via_const_fn(c: &WitContract) -> bool {
16564            c.is_http()
16565        }
16566        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
16567            c.is_pubsub()
16568        }
16569        const fn is_store_via_const_fn(c: &WitContract) -> bool {
16570            c.is_store()
16571        }
16572        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
16573            c.is_capability()
16574        }
16575        // Sweep one canonical accept-set sample per WIT-shape arm plus
16576        // a payload-less capability sample, asserting the wrapper and
16577        // direct dispatches agree byte-for-byte across the closed
16578        // 4-arm partition on both the scalar-accessor trio and the
16579        // WIT-shape-predicate family.
16580        for (wit, is_http, is_pubsub, is_store, is_capability) in [
16581            ("wasi:http/proxy", true, false, false, false),
16582            ("http:incoming", true, false, false, false),
16583            ("nats:events", false, true, false, false),
16584            ("kafka:topic", false, true, false, false),
16585            ("wasi:keyvalue/store", false, false, true, false),
16586            ("kv:cache", false, false, true, false),
16587            ("custom:capability-only", false, false, false, true),
16588            ("", false, false, false, true),
16589        ] {
16590            let c = WitContract {
16591                de: "cart".into(),
16592                para: "catalog".into(),
16593                wit: wit.into(),
16594                endpoint: None,
16595                subject: None,
16596                slot: None,
16597            };
16598            assert_eq!(source_via_const_fn(&c), c.source());
16599            assert_eq!(destination_via_const_fn(&c), c.destination());
16600            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
16601            assert_eq!(is_http_via_const_fn(&c), c.is_http());
16602            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
16603            assert_eq!(is_store_via_const_fn(&c), c.is_store());
16604            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
16605            assert_eq!(c.source(), "cart");
16606            assert_eq!(c.destination(), "catalog");
16607            assert_eq!(c.world_ref(), wit);
16608            assert_eq!(c.is_http(), is_http);
16609            assert_eq!(c.is_pubsub(), is_pubsub);
16610            assert_eq!(c.is_store(), is_store);
16611            assert_eq!(c.is_capability(), is_capability);
16612        }
16613    }
16614
16615    #[test]
16616    fn wit_contract_identity_projection_accessor_is_const_fn() {
16617        // Fail-before-pass-after pin on the [`WitContract::identity`]
16618        // six-arm composite-projection accessor's `const`-eval-surface
16619        // posture. The accessor projects the typed edge's six identity
16620        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
16621        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
16622        // every callee is itself `pub const fn` ([`WitContract::source`]
16623        // / [`WitContract::destination`] / [`WitContract::world_ref`]
16624        // through `String::as_str`, const-stable since Rust 1.87;
16625        // [`WitContract::endpoint`] / [`WitContract::subject`] /
16626        // [`WitContract::slot`] through the sibling `match &self
16627        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
16628        // 0650f64 closed the const-eval surface on) and the tuple
16629        // constructor from borrowed-reference / `Option`-of-borrowed-
16630        // reference arms is trivially const. Any future accidental
16631        // downgrade fails the `identity_via_const_fn` wrapper at
16632        // caixa-core build time with E0015 (`cannot call non-const
16633        // method`), strictly stronger than a runtime `assert!` and
16634        // strictly stronger than a module-scope `const _: () =
16635        // assert!(…)` pin (which cannot be formed on a `&WitContract`
16636        // fixture because the type's `String` / `Option<String>`
16637        // carriers rule out `const`-context value construction; the
16638        // `const fn` wrapper is the load-bearing shape that side-steps
16639        // the destructor-in-const restriction on the value axis while
16640        // still pinning the `const`-fn posture on the callee — mirror
16641        // of the sibling
16642        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16643        // pin's discipline verbatim on the peer scalar-accessor
16644        // surface).
16645        //
16646        // Peer of the sibling
16647        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16648        // (279823b) pin on the six per-`:contratos` scalar-accessor
16649        // callees this composite-projection reads through — where that
16650        // pin anchors the const-eval surface at the six individual
16651        // scalar-accessor arms, this pin extends the same posture onto
16652        // the composite six-tuple projection every consumer that dedups
16653        // typed edges on the [`ContratoIdentity`] axis keys off (the
16654        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
16655        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
16656        // materializer's per-edge identity-based admission webhook; a
16657        // future L7 policy-emitter that shards CNPs by identity-tuple
16658        // rather than by name). Same fail-before-pass-after wrapper
16659        // discipline as the peer M2 / M3 accessor-family pins on the
16660        // sibling `const`-eval-surface passes.
16661        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
16662            c.identity()
16663        }
16664        // Sweep one canonical WIT-shape sample per payload-carrier arm
16665        // plus a payload-less capability sample so the pin exercises
16666        // both `Some(_)`-carrying and `None`-carrying arms on all three
16667        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
16668        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
16669        // with the direct method call on every arm of the closed WIT-
16670        // shape partition.
16671        for (wit, endpoint, subject, slot) in [
16672            ("wasi:http/proxy", Some("/checkout"), None, None),
16673            ("http:incoming", Some("/api"), None, None),
16674            ("nats:events", None, Some("orders.placed"), None),
16675            ("kafka:topic", None, Some("orders.stream"), None),
16676            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
16677            ("kv:cache", None, None, Some("session/{token}")),
16678            ("custom:capability-only", None, None, None),
16679        ] {
16680            let c = WitContract {
16681                de: "cart".into(),
16682                para: "catalog".into(),
16683                wit: wit.into(),
16684                endpoint: endpoint.map(str::to_string),
16685                subject: subject.map(str::to_string),
16686                slot: slot.map(str::to_string),
16687            };
16688            assert_eq!(identity_via_const_fn(&c), c.identity());
16689            assert_eq!(
16690                c.identity(),
16691                ("cart", "catalog", wit, endpoint, subject, slot,),
16692            );
16693        }
16694    }
16695
16696    #[test]
16697    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
16698        // Fail-before-pass-after pin on the four M3 mesh-slot
16699        // `String → &str` scalar accessors ([`Membro::nome`] /
16700        // [`Membro::versao_requirement`] on the per-`:membros` axis,
16701        // [`Entrada::hostname`] / [`Entrada::destination`] on the
16702        // per-`:entrada` axis) — each projects the typed slot's
16703        // [`String`] storage through the `pub const fn`
16704        // [`String::as_str`] (const-stable since Rust 1.87, well
16705        // within the workspace MSRV) and any future accidental
16706        // downgrade to non-`const` fails the corresponding
16707        // `<name>_via_const_fn` wrapper at caixa-core build time with
16708        // E0015 (`cannot call non-const method`), strictly stronger
16709        // than a runtime `assert!` and strictly stronger than a
16710        // module-scope `const _: () = assert!(…)` pin (which cannot
16711        // be formed on `&Membro` / `&Entrada` fixtures because the
16712        // types' `String` carriers rule out `const`-context value
16713        // construction; the `const fn` wrapper is the load-bearing
16714        // shape that side-steps the destructor-in-const restriction
16715        // on the value axis while still pinning the `const`-fn
16716        // posture on the callee — mirror of the sibling
16717        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16718        // (279823b) pin on the per-`:contratos` axis). Peer of the
16719        // sibling per-M2/M3/universal-axis `String → &str` accessor
16720        // family pins on the sibling `const`-eval-surface passes
16721        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
16722        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
16723        // typed-newtype wrapper,
16724        // [`crate::supervisor::ChildSpec::nome`] /
16725        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
16726        // M2 supervisor-tree axis,
16727        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
16728        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
16729        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
16730        // axis, and the sibling per-`:contratos`
16731        // [`WitContract::source`] / [`WitContract::destination`] /
16732        // [`WitContract::world_ref`] trio at 279823b).
16733        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
16734            m.nome()
16735        }
16736        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
16737            m.versao_requirement()
16738        }
16739        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
16740            e.hostname()
16741        }
16742        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
16743            e.destination()
16744        }
16745        for (caixa, versao) in [
16746            ("cart", "^0.1"),
16747            ("catalog-v2", "~0.2.3"),
16748            ("checkout", "*"),
16749        ] {
16750            let m = Membro {
16751                caixa: caixa.into(),
16752                versao: versao.into(),
16753            };
16754            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
16755            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
16756            assert_eq!(m.nome(), caixa);
16757            assert_eq!(m.versao_requirement(), versao);
16758        }
16759        for (host, para) in [
16760            ("cart.example.com", "cart"),
16761            ("api.checkout.io", "checkout"),
16762        ] {
16763            let e = Entrada {
16764                host: host.into(),
16765                para: para.into(),
16766                paths: vec![],
16767                port: DEFAULT_SERVICO_PORT,
16768            };
16769            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
16770            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
16771            assert_eq!(e.hostname(), host);
16772            assert_eq!(e.destination(), para);
16773        }
16774    }
16775
16776    #[test]
16777    fn m3_option_string_scalar_accessor_family_is_const_fn() {
16778        // Fail-before-pass-after pin on the five M3 mesh-slot
16779        // `Option<String> → Option<&str>` scalar accessors
16780        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
16781        // [`WitContract::slot`] on the per-`:contratos` HTTP /
16782        // pub-sub / key-value payload-carrier trio,
16783        // [`Placement::shard_key`] / [`Placement::affinity`] on the
16784        // per-`:placement` Akka-sharding-key + Adaptive-compression-
16785        // hint pair). Each accessor destructures the typed slot's
16786        // `Option<String>` storage through the `match &self.<field> {
16787        // Some(s) => Some(s.as_str()), None => None }` shape —
16788        // routing through [`String::as_str`] (const-stable since Rust
16789        // 1.87, well within the workspace MSRV) rather than the
16790        // non-const [`Option::as_deref`] the pre-lift bodies carried
16791        // — and any future accidental downgrade to non-`const` fails
16792        // the corresponding `<name>_via_const_fn` wrapper at
16793        // caixa-core build time with E0015 (`cannot call non-const
16794        // method`), strictly stronger than a runtime `assert!` and
16795        // strictly stronger than a module-scope `const _: () =
16796        // assert!(…)` pin (which cannot be formed on `&WitContract`
16797        // / `&Placement` fixtures because the types' `String` /
16798        // `Option<String>` carriers rule out `const`-context value
16799        // construction; the `const fn` wrapper is the load-bearing
16800        // shape that side-steps the destructor-in-const restriction
16801        // on the value axis while still pinning the `const`-fn
16802        // posture on the callee — mirror of the sibling
16803        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16804        // (279823b) and
16805        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
16806        // (29c5d7e) pins on the peer `String → &str` axes at the same
16807        // structs).
16808        //
16809        // Peer of the sibling per-`Caixa` `Option<String> →
16810        // Option<&str>` accessor family pin
16811        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
16812        // on the top-level manifest's optional universal-axis surface
16813        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
16814        // `:restart-window`).
16815        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
16816            w.endpoint()
16817        }
16818        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
16819            w.subject()
16820        }
16821        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
16822            w.slot()
16823        }
16824        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
16825            p.shard_key()
16826        }
16827        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
16828            p.affinity()
16829        }
16830        // Sweep every closed shape-arm partition on the
16831        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
16832        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
16833        // pair None), key-value (`:slot` Some, sibling pair None),
16834        // and Capability (all three None) so each accessor's
16835        // Some/None arm carries a pin through the const dispatch.
16836        for (wit, endpoint, subject, slot) in [
16837            ("wasi:http/proxy", Some("/api"), None, None),
16838            ("nats:pub-sub", None, Some("orders.paid"), None),
16839            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
16840            ("custom:capability-only", None, None, None),
16841        ] {
16842            let c = WitContract {
16843                de: "cart".into(),
16844                para: "catalog".into(),
16845                wit: wit.into(),
16846                endpoint: endpoint.map(str::to_string),
16847                subject: subject.map(str::to_string),
16848                slot: slot.map(str::to_string),
16849            };
16850            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
16851            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
16852            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
16853            assert_eq!(c.endpoint(), endpoint);
16854            assert_eq!(c.subject(), subject);
16855            assert_eq!(c.slot(), slot);
16856        }
16857        // Sweep both `Some`/`None` arms on each per-`:placement`
16858        // optional-scalar so the shard-key + affinity pair carries a
16859        // const-dispatch pin on both arms.
16860        for (shard_key, affinity) in [
16861            (Some("tenantId"), Some("data-locality")),
16862            (Some("$tenantId"), None),
16863            (None, Some("low-latency")),
16864            (None, None),
16865        ] {
16866            let p = Placement {
16867                estrategia: PlacementStrategy::default(),
16868                clusters: vec![],
16869                affinity: affinity.map(str::to_string),
16870                shard_key: shard_key.map(str::to_string),
16871            };
16872            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
16873            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
16874            assert_eq!(p.shard_key(), shard_key);
16875            assert_eq!(p.affinity(), affinity);
16876        }
16877    }
16878
16879    #[test]
16880    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
16881        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
16882        // composite `Vec → &[String]` slice-return accessors on
16883        // [`Placement::clusters`] and [`Entrada::paths`]. Each
16884        // destructures the typed slot's `Vec<String>` storage through
16885        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
16886        // 1.66, well within the workspace MSRV) — any future accidental
16887        // downgrade to non-`const` fails the corresponding
16888        // `<name>_via_const_fn` wrapper at caixa-core build time with
16889        // E0015 (`cannot call non-const method`), strictly stronger
16890        // than a runtime `assert!`. Sibling of the peer
16891        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
16892        // pin on the outer-`AplicacaoSpec` reference-return family
16893        // (`:membros` / `:contratos` slice-return + `:politicas` /
16894        // `:placement` / `:entrada` composite-reference), and of the
16895        // peer M2 slice-return axis pins
16896        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
16897        // (on `SupervisorSpec::children`) and
16898        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
16899        // (on `UpgradeFromEntry::instructions`). Together the four
16900        // pins close the last unlifted reference-return accessor
16901        // family across the substrate primitive.
16902        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
16903            p.clusters()
16904        }
16905        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
16906            e.paths()
16907        }
16908        // Sweep both the empty-Vec (no author-declared entries) and
16909        // the populated-Vec arms on every slice-return accessor so
16910        // each carries a const-dispatch pin on both arms.
16911        let p_empty = Placement {
16912            estrategia: PlacementStrategy::default(),
16913            clusters: vec![],
16914            affinity: None,
16915            shard_key: None,
16916        };
16917        let p_full = Placement {
16918            estrategia: PlacementStrategy::default(),
16919            clusters: vec!["prod-a".into(), "prod-b".into()],
16920            affinity: None,
16921            shard_key: None,
16922        };
16923        assert_eq!(
16924            placement_clusters_via_const_fn(&p_empty),
16925            p_empty.clusters()
16926        );
16927        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
16928        assert!(p_empty.clusters().is_empty());
16929        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
16930        let e_empty = Entrada {
16931            host: "web.example.com".into(),
16932            para: "web".into(),
16933            paths: vec![],
16934            port: DEFAULT_SERVICO_PORT,
16935        };
16936        let e_full = Entrada {
16937            host: "web.example.com".into(),
16938            para: "web".into(),
16939            paths: vec!["/api".into(), "/health".into()],
16940            port: DEFAULT_SERVICO_PORT,
16941        };
16942        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
16943        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
16944        assert!(e_empty.paths().is_empty());
16945        assert_eq!(e_full.paths(), &["/api", "/health"]);
16946    }
16947
16948    #[test]
16949    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
16950        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
16951        // reference-return accessors — the two `Vec → &[T]` slice-
16952        // return accessors on [`AplicacaoSpec::membros`] and
16953        // [`AplicacaoSpec::contratos`] (each routes through the
16954        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
16955        // 1.66), the two `&Composite` composite-reference accessors
16956        // on [`AplicacaoSpec::politicas`] and
16957        // [`AplicacaoSpec::placement`] (each routes through a raw
16958        // `&self.<field>` borrow, trivially const), and the one
16959        // `Option<&Composite>` optional-composite-reference accessor
16960        // on [`AplicacaoSpec::entrada`] (routes through the
16961        // `pub const fn` [`Option::as_ref`], const-stable since Rust
16962        // 1.83). Any future accidental downgrade to non-`const` fails
16963        // the corresponding `<name>_via_const_fn` wrapper at caixa-
16964        // core build time with E0015 (`cannot call non-const
16965        // method`), strictly stronger than a runtime `assert!`.
16966        // Sibling of the peer inner-composite pin
16967        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
16968        // on the `Placement::clusters` + `Entrada::paths` slice-
16969        // return pair, and of the peer M2 axis pins on
16970        // [`crate::supervisor::SupervisorSpec::children`] and
16971        // [`crate::upgrade::UpgradeFromEntry::instructions`].
16972        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
16973            s.membros()
16974        }
16975        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
16976            s.contratos()
16977        }
16978        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
16979            s.politicas()
16980        }
16981        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
16982            s.placement()
16983        }
16984        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
16985            s.entrada()
16986        }
16987        // Construct both a minimal "no :entrada" (internal-only
16988        // mesh) and a full "with :entrada" (external-gateway)
16989        // fixture so the family pins both the `None`-arm (author-
16990        // omitted `:entrada`) and the `Some`-arm (author-declared
16991        // `:entrada`) on the optional-composite axis.
16992        let membro = Membro {
16993            caixa: "web".into(),
16994            versao: "^0.1".into(),
16995        };
16996        let entrada_full = Entrada {
16997            host: "web.example.com".into(),
16998            para: "web".into(),
16999            paths: vec!["/api".into()],
17000            port: DEFAULT_SERVICO_PORT,
17001        };
17002        let internal_only = AplicacaoSpec {
17003            membros: vec![membro.clone()],
17004            contratos: vec![],
17005            politicas: MeshPolicy::default(),
17006            placement: Placement::default(),
17007            entrada: None,
17008        };
17009        let with_entrada = AplicacaoSpec {
17010            membros: vec![membro],
17011            contratos: vec![],
17012            politicas: MeshPolicy::default(),
17013            placement: Placement::default(),
17014            entrada: Some(entrada_full),
17015        };
17016        assert_eq!(
17017            aplicacao_membros_via_const_fn(&internal_only),
17018            internal_only.membros()
17019        );
17020        assert_eq!(
17021            aplicacao_membros_via_const_fn(&with_entrada),
17022            with_entrada.membros()
17023        );
17024        assert_eq!(
17025            aplicacao_contratos_via_const_fn(&internal_only),
17026            internal_only.contratos()
17027        );
17028        assert!(std::ptr::eq(
17029            aplicacao_politicas_via_const_fn(&internal_only),
17030            internal_only.politicas(),
17031        ));
17032        assert!(std::ptr::eq(
17033            aplicacao_placement_via_const_fn(&internal_only),
17034            internal_only.placement(),
17035        ));
17036        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
17037        match (
17038            aplicacao_entrada_via_const_fn(&with_entrada),
17039            with_entrada.entrada(),
17040        ) {
17041            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
17042            _ => panic!(
17043                "aplicacao_entrada_via_const_fn must agree with \
17044                 AplicacaoSpec::entrada on the Some-arm reference"
17045            ),
17046        }
17047    }
17048
17049    #[test]
17050    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
17051        // Load-bearing contract pin: on every canonical
17052        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
17053        // [`WitContract::target_projected`] returns byte-equal to
17054        // [`WitContract::target`]`().unwrap()` — the post-validation
17055        // projection accessor is a thin panicking wrapper over the
17056        // pre-validation validator, no extra work in the projection
17057        // path. Any future divergence (a validator-side normalization
17058        // the projection doesn't route through, an accessor-side
17059        // caching layer the validator doesn't populate) would surface
17060        // here at caixa-core build time rather than a silent per-consumer
17061        // split at renderer emit time. Sweeps the closed 4-arm
17062        // [`WitTarget`] partition ([`WitTarget::Http`] /
17063        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
17064        // [`WitTarget::Capability`]) so every arm carries a byte-equality
17065        // pin on the two-accessor pair.
17066        for (wit, endpoint, subject, slot) in [
17067            ("wasi:http/proxy", Some("/x"), None, None),
17068            ("nats:pub-sub", None, Some("events.x"), None),
17069            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
17070            ("custom:capability-only", None, None, None),
17071        ] {
17072            let c = WitContract {
17073                de: "cart".into(),
17074                para: "catalog".into(),
17075                wit: wit.into(),
17076                endpoint: endpoint.map(str::to_string),
17077                subject: subject.map(str::to_string),
17078                slot: slot.map(str::to_string),
17079            };
17080            assert_eq!(
17081                c.target_projected(),
17082                c.target().unwrap(),
17083                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
17084            );
17085        }
17086    }
17087
17088    #[test]
17089    #[should_panic(expected = "validated by typed_view")]
17090    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
17091        // Panic-path pin: [`WitContract::target_projected`] threads the
17092        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
17093        // through its expect-panic when called on a contract whose
17094        // (`:wit`, payload) shape has not been crossed by
17095        // [`AplicacaoSpec::validate`] — a contract with a structurally-
17096        // invalid `:wit` (hyphen-for-colon typo) that would surface
17097        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
17098        // A future rebrand on the panic-message axis would land at one
17099        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
17100        // and this pin's [`should_panic(expected = …)`] literal would
17101        // migrate alongside — the pin catches drift between the const
17102        // and the accessor's `expect(…)` call by construction.
17103        let c = WitContract {
17104            de: "cart".into(),
17105            para: "catalog".into(),
17106            // Hyphen-for-colon typo: `WitContract::target` returns
17107            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
17108            // driving the [`WitContract::target_projected`] expect-panic.
17109            wit: "wasi-http/proxy".into(),
17110            endpoint: Some("/x".into()),
17111            subject: None,
17112            slot: None,
17113        };
17114        let _ = c.target_projected();
17115    }
17116
17117    #[test]
17118    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
17119        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
17120        // carries the exact byte-string the two prior open-coded
17121        // `.target().expect("validated by typed_view")` production
17122        // consumers threaded through inline before this lift converged
17123        // them onto [`WitContract::target_projected`] — the caixa-mesh
17124        // per-`(:de, :para)` CNP L7 introspection branch at
17125        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
17126        // graph` per-`:contratos` payload-column printer at
17127        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
17128        // byte-string load-bearing so a well-meaning const-side rebrand
17129        // that didn't carry a matched pin migration would surface here
17130        // at caixa-core build time rather than a silent per-consumer
17131        // panic-message drift at cluster-apply time. Peer of the
17132        // sibling [`WitTarget::CAPABILITY_LABEL`] /
17133        // [`WitTarget::CAPABILITY_EXPECTED`] /
17134        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
17135        // the paired payload-less-arm scalar-const family.
17136        assert_eq!(
17137            WitContract::PROJECTED_INVARIANT_MSG,
17138            "validated by typed_view"
17139        );
17140    }
17141
17142    #[test]
17143    fn empty_wit_takes_precedence_over_invalid() {
17144        // Ordering pin: `EmptyWit` is the more self-locating
17145        // diagnostic on `""` and must lead — the value-shape gate is
17146        // only reached after the empty-check fires. Mirrors
17147        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
17148        // the peer payload axis.
17149        let mut s = three_member_spec();
17150        s.contratos.push(WitContract {
17151            de: "payment".into(),
17152            para: "catalog".into(),
17153            wit: String::new(),
17154            endpoint: None,
17155            subject: None,
17156            slot: None,
17157        });
17158        let err = s.validate().unwrap_err();
17159        assert!(
17160            matches!(err, AplicacaoError::EmptyWit { .. }),
17161            "got {err:?}"
17162        );
17163    }
17164
17165    #[test]
17166    fn wit_invalid_fires_before_payload_shape_arm() {
17167        // Ordering pin: a malformed `:wit` surfaces *its own*
17168        // diagnostic (which names the offending wit verbatim) before
17169        // any payload-field check — a contrato whose wit is
17170        // structurally invalid AND carries a wrong target field
17171        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
17172        // because the dispatch on the wit is what decides which
17173        // payload field is "right" in the first place. Without this
17174        // ordering, the author would see "wrong target field" for a
17175        // wit that hasn't even been parsed, which doesn't name the
17176        // root cause.
17177        let mut s = three_member_spec();
17178        s.contratos.push(WitContract {
17179            de: "payment".into(),
17180            para: "catalog".into(),
17181            // Hyphen-for-colon typo + endpoint set: pre-gate this
17182            // raised `ContratoWrongTarget { expected: "none" }` (the
17183            // Capability arm rejecting the endpoint), masking the
17184            // real authoring mistake (the wit isn't `wasi:http/proxy`).
17185            wit: "wasi-http/proxy".into(),
17186            endpoint: Some("/x".into()),
17187            subject: None,
17188            slot: None,
17189        });
17190        let err = s.validate().unwrap_err();
17191        assert!(
17192            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
17193                if wit == "wasi-http/proxy"),
17194            "got {err:?}"
17195        );
17196    }
17197
17198    #[test]
17199    fn wit_invalid_diagnostic_carries_offending_wit() {
17200        // Diagnostic-shape pin — the offending `:wit` + `:de` +
17201        // `:para` + a non-empty reason flow through verbatim so the
17202        // author can grep their caixa.lisp for the offending contrato
17203        // block and fix it in one edit. Same shape as
17204        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
17205        let err = contrato_wit_err("WASI:HTTP/proxy");
17206        match err {
17207            AplicacaoError::ContratoWitInvalid {
17208                de,
17209                para,
17210                wit,
17211                reason,
17212            } => {
17213                assert_eq!(de, "payment");
17214                assert_eq!(para, "catalog");
17215                assert_eq!(wit, "WASI:HTTP/proxy");
17216                assert!(!reason.is_empty(), "reason field must be non-empty");
17217            }
17218            other => panic!("expected ContratoWitInvalid, got {other:?}"),
17219        }
17220    }
17221
17222    // ── :contratos :subject value-shape gate ─────────────────────────────
17223    //
17224    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
17225    // suites on the peer payload axes. Until this gate landed
17226    // `WitContract::target()` only refused the empty string; a
17227    // structurally invalid subject silently passed validate and the
17228    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
17229    // Subject'` on publish / subscribe, or as a silent message drop,
17230    // far from the source caixa.lisp. Every authoring footgun the
17231    // NATS server's subject parser would catch on admission now
17232    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
17233    // offending `:subject` + `:de` + `:para` named verbatim. Same
17234    // diagnostic shape as `ContratoEndpointInvalid` /
17235    // `ContratoWitInvalid` on the peer payload axes; same shared
17236    // predicate (`crate::render::is_nats_subject`) ensures drift
17237    // between any two axes' rule enforcement is a build error at the
17238    // predicate, not piecemeal across renderers.
17239
17240    fn contrato_subject_err(subject: &str) -> AplicacaoError {
17241        // Fresh spec per call so the new contract doesn't collide on
17242        // identity with `three_member_spec`'s pre-existing entries.
17243        // The new edge uses `(payment, catalog)` — a pair the fixture
17244        // doesn't already declare — with `:wit "nats:pub-sub"` and the
17245        // varying `:subject`, so the subject-shape gate fires cleanly
17246        // after the wit-shape gate (which `"nats:pub-sub"` passes).
17247        let mut s = three_member_spec();
17248        s.contratos.push(WitContract {
17249            de: "payment".into(),
17250            para: "catalog".into(),
17251            wit: "nats:pub-sub".into(),
17252            endpoint: None,
17253            subject: Some(subject.into()),
17254            slot: None,
17255        });
17256        s.validate().unwrap_err()
17257    }
17258
17259    #[test]
17260    fn rejects_pubsub_contrato_subject_with_whitespace() {
17261        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
17262        // landed at the NATS server as a malformed subject the parser
17263        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
17264        // source caixa.lisp.
17265        let err = contrato_subject_err("foo bar");
17266        assert!(
17267            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17268                if subject == "foo bar" && reason.contains("whitespace")),
17269            "got {err:?}"
17270        );
17271    }
17272
17273    #[test]
17274    fn rejects_pubsub_contrato_subject_with_control_char() {
17275        let err = contrato_subject_err("foo\x01bar");
17276        assert!(
17277            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17278                if subject == "foo\x01bar" && reason.contains("control character")),
17279            "got {err:?}"
17280        );
17281    }
17282
17283    #[test]
17284    fn rejects_pubsub_contrato_subject_with_non_ascii() {
17285        // Un-percent-encoded non-ASCII byte — the canonical "I copied
17286        // the subject from a doc with smart quotes / accented
17287        // characters" footgun.
17288        let err = contrato_subject_err("foo.caf\u{e9}");
17289        assert!(
17290            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17291                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
17292            "got {err:?}"
17293        );
17294    }
17295
17296    #[test]
17297    fn rejects_pubsub_contrato_subject_with_leading_dot() {
17298        // Empty leading token — NATS rejects.
17299        let err = contrato_subject_err(".foo");
17300        assert!(
17301            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17302                if subject == ".foo" && reason.contains("must not start with `.`")),
17303            "got {err:?}"
17304        );
17305    }
17306
17307    #[test]
17308    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
17309        // Empty trailing token — NATS rejects. The remediation
17310        // (use `>` instead) is in the reason string.
17311        let err = contrato_subject_err("foo.");
17312        assert!(
17313            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17314                if subject == "foo." && reason.contains("must not end with `.`")),
17315            "got {err:?}"
17316        );
17317    }
17318
17319    #[test]
17320    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
17321        // The canonical "I forgot to fill in the middle segment"
17322        // typo — `"foo..bar"`. NATS rejects empty tokens.
17323        let err = contrato_subject_err("foo..bar");
17324        assert!(
17325            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17326                if subject == "foo..bar" && reason.contains("consecutive `.`")),
17327            "got {err:?}"
17328        );
17329    }
17330
17331    #[test]
17332    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
17333        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
17334        // as the final segment. Pre-gate this passed as a typed edge
17335        // and surfaced at runtime as a NATS subscribe rejection.
17336        let err = contrato_subject_err("foo.>.bar");
17337        assert!(
17338            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17339                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
17340            "got {err:?}"
17341        );
17342    }
17343
17344    #[test]
17345    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
17346        // `foo*.bar` — NATS wildcards are standalone tokens. The
17347        // remediation is in the reason string.
17348        let err = contrato_subject_err("foo*.bar");
17349        assert!(
17350            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17351                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
17352            "got {err:?}"
17353        );
17354    }
17355
17356    #[test]
17357    fn rejects_pubsub_contrato_subject_with_invalid_char() {
17358        // `foo,bar` — comma is not a valid NATS subject character.
17359        // Pinned separately from the wildcard arms so the invalid-
17360        // character diagnostic is in force.
17361        let err = contrato_subject_err("foo,bar");
17362        assert!(
17363            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17364                if subject == "foo,bar" && reason.contains("invalid character")),
17365            "got {err:?}"
17366        );
17367    }
17368
17369    #[test]
17370    fn rejects_pubsub_contrato_subject_too_long() {
17371        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
17372        // The legitimate-shape arms all pass (one all-`a` token, no
17373        // `.`, no wildcards); only the cap arm fires. Surfaces the
17374        // paste-from-binary / accidental-multi-line-blob landing
17375        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
17376        // on the peer axis.
17377        let big = "a".repeat(257);
17378        assert_eq!(big.len(), 257);
17379        let err = contrato_subject_err(&big);
17380        assert!(
17381            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
17382                if subject == &big && reason.contains("max length of 256")),
17383            "got {err:?}"
17384        );
17385    }
17386
17387    #[test]
17388    fn pubsub_contrato_subject_max_length_validates() {
17389        // 256-byte subject — exactly the cap. Boundary pin: drift in
17390        // the cap surfaces here and at
17391        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
17392        // mirroring `http_contrato_endpoint_max_length_validates` and
17393        // `wit_max_length_validates` on the peer axes.
17394        let big = "a".repeat(256);
17395        assert_eq!(big.len(), 256);
17396        let mut s = three_member_spec();
17397        s.contratos.push(WitContract {
17398            de: "payment".into(),
17399            para: "catalog".into(),
17400            wit: "nats:pub-sub".into(),
17401            endpoint: None,
17402            subject: Some(big),
17403            slot: None,
17404        });
17405        s.validate().unwrap();
17406    }
17407
17408    #[test]
17409    fn pubsub_contrato_subject_accepts_canonical_forms() {
17410        // Positive-set sweep: every canonical NATS subject shape the
17411        // substrate-side `is_nats_subject` predicate accepts (the
17412        // multi-dot `events.order.charged`, the snake_case / kebab-
17413        // case / mixed-case tokens, the digit-bearing tokens, the
17414        // single-token wildcard `*` at every segment position, and
17415        // the trailing `>` multi-token wildcard) must remain a valid
17416        // contrato subject too. Drift between this list and the
17417        // substrate-side `nats_subject_accepts_canonical_forms` sweep
17418        // surfaces at the shared predicate — one source of truth.
17419        // Uses a fresh `(payment, catalog)` edge so none of the swept
17420        // subjects collide with the pre-existing entries in
17421        // `three_member_spec`.
17422        for subject in [
17423            "checkout.events.charge.failed",
17424            "rio.events.order.charged",
17425            "orders",
17426            "orders.123",
17427            "snake_case.token",
17428            "kebab-case.token",
17429            "MixedCase.Token",
17430            "orders.*.charged",
17431            "*.events.*",
17432            "orders.>",
17433        ] {
17434            let mut s = three_member_spec();
17435            s.contratos.push(WitContract {
17436                de: "payment".into(),
17437                para: "catalog".into(),
17438                wit: "nats:pub-sub".into(),
17439                endpoint: None,
17440                subject: Some(subject.into()),
17441                slot: None,
17442            });
17443            s.validate()
17444                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
17445        }
17446    }
17447
17448    #[test]
17449    fn contrato_subject_empty_takes_precedence_over_invalid() {
17450        // Ordering pin: `ContratoSubjectEmpty` is the more self-
17451        // locating diagnostic on `""` and must lead — the value-shape
17452        // gate is only reached after the empty-check fires. Mirrors
17453        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
17454        // the peer payload axis.
17455        let mut s = three_member_spec();
17456        s.contratos.push(WitContract {
17457            de: "payment".into(),
17458            para: "catalog".into(),
17459            wit: "nats:pub-sub".into(),
17460            endpoint: None,
17461            subject: Some(String::new()),
17462            slot: None,
17463        });
17464        let err = s.validate().unwrap_err();
17465        assert!(
17466            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
17467            "got {err:?}"
17468        );
17469    }
17470
17471    #[test]
17472    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
17473        // Diagnostic-shape pin — the offending `:subject` + `:de` +
17474        // `:para` + a non-empty reason flow through verbatim so the
17475        // author can grep their caixa.lisp for the offending contrato
17476        // block and fix it in one edit. Same shape as
17477        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
17478        // and `wit_invalid_diagnostic_carries_offending_wit`.
17479        let err = contrato_subject_err("foo..bar");
17480        match err {
17481            AplicacaoError::ContratoSubjectInvalid {
17482                de,
17483                para,
17484                subject,
17485                reason,
17486            } => {
17487                assert_eq!(de, "payment");
17488                assert_eq!(para, "catalog");
17489                assert_eq!(subject, "foo..bar");
17490                assert!(!reason.is_empty(), "reason field must be non-empty");
17491            }
17492            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
17493        }
17494    }
17495
17496    #[test]
17497    fn target_view_pubsub_subject_passes_through_to_typed_view() {
17498        // The compounding theorem on the pub-sub axis: every
17499        // `WitTarget::PubSub { subject }` returned by `target()` carries
17500        // a NATS-server-accepted subject. Renderers downstream of
17501        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
17502        // NATS Stream/Consumer CR emitter, the future `feira app graph`
17503        // view's subject labeller) can rely on this without re-checking
17504        // — the type system carries the proof. Mirrors
17505        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
17506        // on the peer axes.
17507        let nats = WitContract {
17508            de: "a".into(),
17509            para: "b".into(),
17510            wit: "nats:pub-sub".into(),
17511            endpoint: None,
17512            subject: Some("orders.events.*.charged".into()),
17513            slot: None,
17514        };
17515        match nats.target().unwrap() {
17516            WitTarget::PubSub { subject } => {
17517                assert_eq!(subject, "orders.events.*.charged");
17518            }
17519            other => panic!("expected PubSub, got {other:?}"),
17520        }
17521    }
17522
17523    // ── :contratos :slot value-shape gate ────────────────────────────────
17524    //
17525    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
17526    // (63e18a0) value-shape suites on the peer payload axes. Until this
17527    // gate landed `WitContract::target()` only refused the empty string
17528    // for the Store arm; a structurally invalid slot (raw whitespace,
17529    // control character, non-ASCII byte, paste-from-binary multi-line
17530    // blob) silently passed validate and surfaced at runtime as a
17531    // per-backend kv write rejection or a silent next-read corruption,
17532    // far from the source caixa.lisp with no field naming which
17533    // `:contratos` edge carried the typo. Every authoring footgun the
17534    // kv backend intersection-floor would catch on write now becomes a
17535    // caixa-build-time `ContratoSlotInvalid` with the offending
17536    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
17537    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
17538    // peer payload axes; same shared predicate
17539    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
17540    // any two axes' rule enforcement is a build error at the
17541    // predicate, not piecemeal across renderers. Closes the typed
17542    // payload-axis value-shape trajectory across all three legs of the
17543    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
17544
17545    fn contrato_slot_err(slot: &str) -> AplicacaoError {
17546        // Fresh spec per call so the new contract doesn't collide on
17547        // identity with `three_member_spec`'s pre-existing entries
17548        // and doesn't close a synchronous cycle the cycle detector
17549        // would reject before the slot-shape gate fires. The new edge
17550        // uses `(payment, catalog)` — a pair the fixture doesn't
17551        // already declare in either direction (the fixture carries
17552        // `cart -> catalog` and `cart -> payment`, so `payment ->
17553        // catalog` doesn't form a cycle on the sync subgraph) — with
17554        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
17555        // slot-shape gate fires cleanly after the wit-shape gate
17556        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
17557        // peer `contrato_subject_err` helper uses (63e18a0).
17558        let mut s = three_member_spec();
17559        s.contratos.push(WitContract {
17560            de: "payment".into(),
17561            para: "catalog".into(),
17562            wit: "wasi:keyvalue/store".into(),
17563            endpoint: None,
17564            subject: None,
17565            slot: Some(slot.into()),
17566        });
17567        s.validate().unwrap_err()
17568    }
17569
17570    #[test]
17571    fn rejects_store_contrato_slot_with_whitespace() {
17572        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
17573        // silently landed at the kv backend with whitespace whose
17574        // runtime behavior varies unpredictably across backends (etcd
17575        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
17576        // rejects on write). Now caught at the source caixa.lisp.
17577        let err = contrato_slot_err("check out/$order");
17578        assert!(
17579            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17580                if slot == "check out/$order" && reason.contains("whitespace")),
17581            "got {err:?}"
17582        );
17583    }
17584
17585    #[test]
17586    fn rejects_store_contrato_slot_with_tab() {
17587        // Tab byte arm-pinned separately from the space arm so a
17588        // future relaxation that admits one but not the other surfaces
17589        // here.
17590        let err = contrato_slot_err("check\tout");
17591        assert!(
17592            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17593                if slot == "check\tout" && reason.contains("whitespace")),
17594            "got {err:?}"
17595        );
17596    }
17597
17598    #[test]
17599    fn rejects_store_contrato_slot_with_control_char() {
17600        // SOH (0x01) — distinct from the whitespace arm. Redis admits
17601        // and corrupts on RESP protocol framing; DynamoDB rejects on
17602        // write.
17603        let err = contrato_slot_err("checkout/\x01order");
17604        assert!(
17605            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17606                if slot == "checkout/\x01order" && reason.contains("control character")),
17607            "got {err:?}"
17608        );
17609    }
17610
17611    #[test]
17612    fn rejects_store_contrato_slot_with_newline() {
17613        // Embedded newline — the canonical "the paste-from-binary slug
17614        // spans multiple lines" footgun. Distinct from the whitespace
17615        // arm because `\n` is a control character (0x0A).
17616        let err = contrato_slot_err("checkout\norder");
17617        assert!(
17618            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17619                if slot == "checkout\norder" && reason.contains("control character")),
17620            "got {err:?}"
17621        );
17622    }
17623
17624    #[test]
17625    fn rejects_store_contrato_slot_with_non_ascii() {
17626        // Un-percent-encoded non-ASCII byte — the canonical "I copied
17627        // the slot from a doc with accented characters" footgun. Each
17628        // kv backend re-encodes non-ASCII differently (etcd preserves
17629        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
17630        // rejects), so the typed slot's value set is the intersection-
17631        // floor every backend admits identically (printable ASCII).
17632        let err = contrato_slot_err("ch\u{e9}ckout/$order");
17633        assert!(
17634            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17635                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
17636            "got {err:?}"
17637        );
17638    }
17639
17640    #[test]
17641    fn rejects_store_contrato_slot_too_long() {
17642        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
17643        // legitimate-shape arms all pass (a single all-`a` token, no
17644        // separators); only the cap arm fires. Surfaces the paste-
17645        // from-binary / accidental-multi-line-blob landing footgun.
17646        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
17647        // `rejects_http_contrato_endpoint_too_long` on the peer
17648        // payload axes.
17649        let big = "a".repeat(513);
17650        assert_eq!(big.len(), 513);
17651        let err = contrato_slot_err(&big);
17652        assert!(
17653            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17654                if slot == &big && reason.contains("max length of 512")),
17655            "got {err:?}"
17656        );
17657    }
17658
17659    #[test]
17660    fn store_contrato_slot_max_length_validates() {
17661        // 512-byte slot — exactly the cap. Boundary pin: drift in the
17662        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
17663        // simultaneously, mirroring
17664        // `pubsub_contrato_subject_max_length_validates` and
17665        // `http_contrato_endpoint_max_length_validates` on the peer
17666        // payload axes.
17667        let big = "a".repeat(512);
17668        assert_eq!(big.len(), 512);
17669        let mut s = three_member_spec();
17670        s.contratos.push(WitContract {
17671            de: "payment".into(),
17672            para: "catalog".into(),
17673            wit: "wasi:keyvalue/store".into(),
17674            endpoint: None,
17675            subject: None,
17676            slot: Some(big),
17677        });
17678        s.validate().unwrap();
17679    }
17680
17681    #[test]
17682    fn store_contrato_slot_accepts_canonical_forms() {
17683        // Positive-set sweep: every canonical kv slot template the
17684        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
17685        // (single-token identifiers, path-namespaced `$`-templates,
17686        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
17687        // snake_case / kebab-case / MixedCase tokens, digit-bearing
17688        // tokens, percent-encoded fragments) must remain valid
17689        // contrato slots too. Drift between this list and the
17690        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
17691        // surfaces at the shared predicate — one source of truth.
17692        // Uses a fresh `(payment, catalog)` edge so none of the swept
17693        // slots collide with the pre-existing entries in
17694        // `three_member_spec`.
17695        for slot in [
17696            "checkout",
17697            "checkout/$orderId",
17698            "users:{tenant}/{id}",
17699            "session.<sid>",
17700            "session.tokens.<sid>",
17701            "snake_case_key",
17702            "kebab-case-key",
17703            "MixedCase",
17704            "shard0",
17705            "v2/key",
17706            "users/caf%C3%A9",
17707        ] {
17708            let mut s = three_member_spec();
17709            s.contratos.push(WitContract {
17710                de: "payment".into(),
17711                para: "catalog".into(),
17712                wit: "wasi:keyvalue/store".into(),
17713                endpoint: None,
17714                subject: None,
17715                slot: Some(slot.into()),
17716            });
17717            s.validate()
17718                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
17719        }
17720    }
17721
17722    #[test]
17723    fn contrato_slot_empty_takes_precedence_over_invalid() {
17724        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
17725        // diagnostic on `""` and must lead — the value-shape gate is
17726        // only reached after the empty-check fires. Mirrors
17727        // `contrato_subject_empty_takes_precedence_over_invalid` and
17728        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
17729        // the peer payload axes.
17730        let mut s = three_member_spec();
17731        s.contratos.push(WitContract {
17732            de: "payment".into(),
17733            para: "catalog".into(),
17734            wit: "wasi:keyvalue/store".into(),
17735            endpoint: None,
17736            subject: None,
17737            slot: Some(String::new()),
17738        });
17739        let err = s.validate().unwrap_err();
17740        assert!(
17741            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
17742            "got {err:?}"
17743        );
17744    }
17745
17746    #[test]
17747    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
17748        // Diagnostic-shape pin — the offending `:slot` + `:de` +
17749        // `:para` + a non-empty reason flow through verbatim so the
17750        // author can grep their caixa.lisp for the offending contrato
17751        // block and fix it in one edit. Same shape as
17752        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
17753        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
17754        // on the peer payload axes.
17755        let err = contrato_slot_err("check out/$order");
17756        match err {
17757            AplicacaoError::ContratoSlotInvalid {
17758                de,
17759                para,
17760                slot,
17761                reason,
17762            } => {
17763                assert_eq!(de, "payment");
17764                assert_eq!(para, "catalog");
17765                assert_eq!(slot, "check out/$order");
17766                assert!(!reason.is_empty(), "reason field must be non-empty");
17767            }
17768            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
17769        }
17770    }
17771
17772    #[test]
17773    fn target_view_store_slot_passes_through_to_typed_view() {
17774        // The compounding theorem on the store axis: every
17775        // `WitTarget::Store { slot }` returned by `target()` carries a
17776        // kv-backend-accepted slot template. Renderers downstream of
17777        // `typed_view()` (the future per-Servico `:capabilities
17778        // wasi:keyvalue/store` axis emitter, the future `feira app
17779        // graph` view's slot labeller, the future kv-provider CR
17780        // materializer) can rely on this without re-checking — the
17781        // type system carries the proof. Mirrors
17782        // `target_view_pubsub_subject_passes_through_to_typed_view` on
17783        // the peer payload axis.
17784        let store = WitContract {
17785            de: "a".into(),
17786            para: "b".into(),
17787            wit: "wasi:keyvalue/store".into(),
17788            endpoint: None,
17789            subject: None,
17790            slot: Some("checkout/$orderId".into()),
17791        };
17792        match store.target().unwrap() {
17793            WitTarget::Store { slot } => {
17794                assert_eq!(slot, "checkout/$orderId");
17795            }
17796            other => panic!("expected Store, got {other:?}"),
17797        }
17798    }
17799
17800    #[test]
17801    fn rejects_self_loop_in_synchronous_contratos() {
17802        // A synchronous self-edge (`cart → cart` over HTTP) is now
17803        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
17804        // "this edge is degenerate" diagnostic — rather than incidentally
17805        // by the cycle detector framing it as a `["cart", "cart"]`
17806        // multi-node deadlock.
17807        let mut s = three_member_spec();
17808        s.contratos.push(contract_http("cart", "cart", "/loop"));
17809        let err = s.validate().unwrap_err();
17810        match err {
17811            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
17812                assert_eq!(caixa, "cart");
17813                assert_eq!(wit, "wasi:http/proxy");
17814            }
17815            other => panic!("expected ContratoSelfLoop, got {other:?}"),
17816        }
17817    }
17818
17819    #[test]
17820    fn rejects_self_loop_in_pubsub_contratos() {
17821        // The cycle detector excludes pub-sub edges (acyclic by
17822        // construction), so before the explicit gate a `nats:pub-sub`
17823        // self-edge silently validated and rendered a self-allow CNP.
17824        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
17825        let mut s = three_member_spec();
17826        s.contratos.push(WitContract {
17827            de: "payment".into(),
17828            para: "payment".into(),
17829            wit: "nats:pub-sub".into(),
17830            endpoint: None,
17831            subject: Some("rio.events.payment".into()),
17832            slot: None,
17833        });
17834        let err = s.validate().unwrap_err();
17835        match err {
17836            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
17837                assert_eq!(caixa, "payment");
17838                assert_eq!(wit, "nats:pub-sub");
17839            }
17840            other => panic!("expected ContratoSelfLoop, got {other:?}"),
17841        }
17842    }
17843
17844    #[test]
17845    fn self_loop_fires_before_payload_shape_check() {
17846        // The structural "this edge can't exist" error precedes the
17847        // narrower payload-shape diagnostics: a self-edge carrying an
17848        // otherwise-malformed endpoint still reports ContratoSelfLoop,
17849        // not ContratoEndpointInvalid.
17850        let mut s = three_member_spec();
17851        s.contratos.push(WitContract {
17852            de: "cart".into(),
17853            para: "cart".into(),
17854            wit: "wasi:http/proxy".into(),
17855            endpoint: Some("not-absolute".into()),
17856            subject: None,
17857            slot: None,
17858        });
17859        match s.validate().unwrap_err() {
17860            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
17861            other => panic!("expected ContratoSelfLoop, got {other:?}"),
17862        }
17863    }
17864
17865    #[test]
17866    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
17867        // A self-edge naming a non-member reports the more fundamental
17868        // ContratoMemberMissing first (the member doesn't exist), so the
17869        // self-loop gate is reached only once both endpoints resolve.
17870        let mut s = three_member_spec();
17871        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
17872        match s.validate().unwrap_err() {
17873            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
17874            other => panic!("expected ContratoMemberMissing, got {other:?}"),
17875        }
17876    }
17877
17878    #[test]
17879    fn rejects_two_node_synchronous_cycle() {
17880        let mut s = three_member_spec();
17881        // existing edges: cart → catalog, cart → payment
17882        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
17883        s.contratos
17884            .push(contract_http("catalog", "cart", "/refresh"));
17885        let err = s.validate().unwrap_err();
17886        match err {
17887            AplicacaoError::ContratoCycle { cycle } => {
17888                // Cycle traversal should mention both endpoints, with
17889                // the back-edge target appearing as both first and last
17890                // element to close the loop.
17891                assert!(cycle.len() >= 3);
17892                assert_eq!(cycle.first(), cycle.last());
17893                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
17894                assert!(body.contains("cart"));
17895                assert!(body.contains("catalog"));
17896            }
17897            other => panic!("expected ContratoCycle, got {other:?}"),
17898        }
17899    }
17900
17901    #[test]
17902    fn rejects_three_node_synchronous_cycle() {
17903        let mut s = three_member_spec();
17904        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
17905        s.contratos = vec![
17906            contract_http("catalog", "cart", "/x"),
17907            contract_http("cart", "payment", "/y"),
17908            contract_http("payment", "catalog", "/z"),
17909        ];
17910        let err = s.validate().unwrap_err();
17911        match err {
17912            AplicacaoError::ContratoCycle { cycle } => {
17913                assert_eq!(cycle.first(), cycle.last());
17914                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
17915                assert_eq!(body.len(), 3);
17916                assert!(body.contains("cart"));
17917                assert!(body.contains("catalog"));
17918                assert!(body.contains("payment"));
17919            }
17920            other => panic!("expected ContratoCycle, got {other:?}"),
17921        }
17922    }
17923
17924    #[test]
17925    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
17926        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
17927        // "acyclic by construction" — so a cycle whose closing edge
17928        // is pub-sub should NOT raise ContratoCycle.
17929        let mut s = three_member_spec();
17930        s.contratos = vec![
17931            contract_http("catalog", "cart", "/x"),
17932            contract_http("cart", "payment", "/y"),
17933            // Closing edge is pub-sub — async; not a sync deadlock.
17934            WitContract {
17935                de: "payment".into(),
17936                para: "catalog".into(),
17937                wit: "nats:pub-sub".into(),
17938                endpoint: None,
17939                subject: Some("checkout.events.charge.completed".into()),
17940                slot: None,
17941            },
17942        ];
17943        s.validate().expect("pub-sub edge breaks the sync cycle");
17944    }
17945
17946    #[test]
17947    fn store_edge_counts_as_synchronous_for_cycle_detection() {
17948        // wasi:keyvalue/store is request/response; a cycle through one
17949        // *is* a sync deadlock, just like HTTP.
17950        let mut s = three_member_spec();
17951        s.contratos = vec![
17952            contract_http("catalog", "cart", "/x"),
17953            WitContract {
17954                de: "cart".into(),
17955                para: "catalog".into(),
17956                wit: "wasi:keyvalue/store".into(),
17957                endpoint: None,
17958                subject: None,
17959                slot: Some("session/$id".into()),
17960            },
17961        ];
17962        let err = s.validate().unwrap_err();
17963        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
17964    }
17965
17966    #[test]
17967    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
17968        // Capability-only edges (unknown WIT shape, no payload) default
17969        // to synchronous — safer; authors with truly async capability
17970        // semantics can model them as pub-sub explicitly.
17971        let mut s = three_member_spec();
17972        s.contratos = vec![
17973            contract_http("catalog", "cart", "/x"),
17974            WitContract {
17975                de: "cart".into(),
17976                para: "catalog".into(),
17977                wit: "custom:exchange".into(),
17978                endpoint: None,
17979                subject: None,
17980                slot: None,
17981            },
17982        ];
17983        let err = s.validate().unwrap_err();
17984        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
17985    }
17986
17987    #[test]
17988    fn long_acyclic_chain_validates() {
17989        // A long sync chain (no back-edges) must validate even when
17990        // every node is reachable from the first.
17991        let mut s = three_member_spec();
17992        s.membros = vec![
17993            membro("a", "^0.1"),
17994            membro("b", "^0.1"),
17995            membro("c", "^0.1"),
17996            membro("d", "^0.1"),
17997            membro("e", "^0.1"),
17998        ];
17999        s.contratos = vec![
18000            contract_http("a", "b", "/1"),
18001            contract_http("b", "c", "/2"),
18002            contract_http("c", "d", "/3"),
18003            contract_http("d", "e", "/4"),
18004        ];
18005        s.entrada.as_mut().unwrap().para = "a".into();
18006        s.validate().unwrap();
18007    }
18008
18009    #[test]
18010    fn diamond_acyclic_validates() {
18011        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
18012        let mut s = three_member_spec();
18013        s.membros = vec![
18014            membro("a", "^0.1"),
18015            membro("b", "^0.1"),
18016            membro("c", "^0.1"),
18017            membro("d", "^0.1"),
18018        ];
18019        s.contratos = vec![
18020            contract_http("a", "b", "/1"),
18021            contract_http("a", "c", "/2"),
18022            contract_http("b", "d", "/3"),
18023            contract_http("c", "d", "/4"),
18024        ];
18025        s.entrada.as_mut().unwrap().para = "a".into();
18026        s.validate().unwrap();
18027    }
18028
18029    // ── duplicate-`:contratos` build-error gate ──────────────────────────
18030
18031    #[test]
18032    fn rejects_duplicate_http_contrato() {
18033        // Fail-before-pass-after pin: the fixture's `cart → catalog`
18034        // HTTP edge appears once. Push an identical entry — same
18035        // (de, para, wit, endpoint) — and validate() must reject it.
18036        // Until this gate landed the typed surface accepted the
18037        // duplicate silently and caixa-mesh's `cilium_network_policies`
18038        // emitted two ``CiliumNetworkPolicy`` objects with identical
18039        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
18040        // admission rejects on `kubectl apply` far from the source.
18041        let mut s = three_member_spec();
18042        s.contratos
18043            .push(contract_http("cart", "catalog", "/products/:id"));
18044        let err = s.validate().unwrap_err();
18045        assert!(
18046            matches!(
18047                err,
18048                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
18049                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
18050            ),
18051            "got {err:?}"
18052        );
18053    }
18054
18055    #[test]
18056    fn rejects_duplicate_pubsub_contrato() {
18057        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
18058        // edges with identical (de, para, subject) are degenerate;
18059        // pin that the typed surface refuses both at validate time.
18060        let mut s = three_member_spec();
18061        let pubsub = WitContract {
18062            de: "payment".into(),
18063            para: "cart".into(),
18064            wit: "nats:pub-sub".into(),
18065            endpoint: None,
18066            subject: Some("checkout.events.charge.failed".into()),
18067            slot: None,
18068        };
18069        s.contratos.push(pubsub.clone());
18070        s.contratos.push(pubsub);
18071        let err = s.validate().unwrap_err();
18072        assert!(
18073            matches!(
18074                err,
18075                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
18076                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
18077            ),
18078            "got {err:?}"
18079        );
18080    }
18081
18082    #[test]
18083    fn rejects_duplicate_store_contrato() {
18084        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
18085        // edges with identical (de, para, slot) collapse to one mesh-
18086        // policy edge; pin the build error.
18087        let mut s = three_member_spec();
18088        let store = WitContract {
18089            de: "cart".into(),
18090            para: "payment".into(),
18091            wit: "wasi:keyvalue/store".into(),
18092            endpoint: None,
18093            subject: None,
18094            slot: Some("checkout/$orderId".into()),
18095        };
18096        // Drop the conflicting HTTP `cart → payment` edge from the
18097        // fixture so the duplicate-store pair is the only one
18098        // distinguishable on this pair.
18099        s.contratos
18100            .retain(|c| !(c.de == "cart" && c.para == "payment"));
18101        s.contratos.push(store.clone());
18102        s.contratos.push(store);
18103        let err = s.validate().unwrap_err();
18104        assert!(
18105            matches!(
18106                err,
18107                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
18108                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
18109            ),
18110            "got {err:?}"
18111        );
18112    }
18113
18114    #[test]
18115    fn rejects_duplicate_capability_contrato() {
18116        // Same gate on the pure-capability axis (no payload selector).
18117        // Two contracts with identical (de, para, wit) and no
18118        // endpoint/subject/slot are duplicate edges; pin so a future
18119        // `target_label` change can't accidentally collapse the
18120        // capability arm into a None-shaped key that compares equal
18121        // to a populated one.
18122        let mut s = three_member_spec();
18123        let capability = WitContract {
18124            de: "cart".into(),
18125            para: "catalog".into(),
18126            wit: "pleme:cap/audit".into(),
18127            endpoint: None,
18128            subject: None,
18129            slot: None,
18130        };
18131        s.contratos.push(capability.clone());
18132        s.contratos.push(capability);
18133        let err = s.validate().unwrap_err();
18134        match err {
18135            AplicacaoError::ContratoDuplicate {
18136                de,
18137                para,
18138                wit,
18139                target,
18140            } => {
18141                assert_eq!(de, "cart");
18142                assert_eq!(para, "catalog");
18143                assert_eq!(wit, "pleme:cap/audit");
18144                assert!(
18145                    target.contains("capability"),
18146                    "capability-edge duplicate diagnostic must surface the \
18147                     no-payload shape (got target = {target:?})"
18148                );
18149            }
18150            other => panic!("expected ContratoDuplicate, got {other:?}"),
18151        }
18152    }
18153
18154    #[test]
18155    fn accepts_distinct_http_paths_between_same_pair() {
18156        // Negative pin: two HTTP contracts cart → catalog at distinct
18157        // endpoints (`/products/:id` and `/search`) are *not*
18158        // duplicates — they're distinct typed edges differing on the
18159        // payload axis. The duplicate-gate must not over-match here,
18160        // since the cart-calls-catalog-on-multiple-paths shape is the
18161        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
18162        // example: cart calls catalog at /products/:id, payment at
18163        // /charge — same shape extends to two paths on one para).
18164        let mut s = three_member_spec();
18165        s.contratos
18166            .push(contract_http("cart", "catalog", "/search"));
18167        s.validate()
18168            .expect("distinct endpoints between same (de, para) must validate");
18169    }
18170
18171    #[test]
18172    fn accepts_same_endpoint_on_different_pairs() {
18173        // Negative pin: the same `/charge` endpoint reused on two
18174        // different (de, para) pairs is two distinct edges, not a
18175        // duplicate. Pinning this shape so the gate's identity key
18176        // includes both `de` and `para` (not just `(wit, endpoint)`).
18177        let mut s = three_member_spec();
18178        s.contratos
18179            .push(contract_http("payment", "catalog", "/charge"));
18180        s.validate()
18181            .expect("same endpoint reused on distinct (de, para) must validate");
18182    }
18183
18184    #[test]
18185    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
18186        // Pin the diagnostic shape: the duplicate-edge error names
18187        // *which* target field carried the conflict, so the author
18188        // doesn't have to re-grep the source caixa.lisp to find it.
18189        // Same self-locating diagnostic discipline as
18190        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
18191        let mut s = three_member_spec();
18192        s.contratos
18193            .push(contract_http("cart", "catalog", "/products/:id"));
18194        let err = s.validate().unwrap_err();
18195        let msg = format!("{err}");
18196        assert!(
18197            msg.contains("\"/products/:id\""),
18198            "duplicate-contrato diagnostic must name the offending \
18199             :endpoint payload (got: {msg:?})"
18200        );
18201        assert!(
18202            msg.contains("cart") && msg.contains("catalog"),
18203            "diagnostic must name both endpoints of the duplicate edge \
18204             (got: {msg:?})"
18205        );
18206    }
18207
18208    #[test]
18209    fn duplicate_contrato_gate_runs_after_membership_check() {
18210        // Order pin: a duplicate contract whose `:de` is *also* not in
18211        // `:membros` surfaces the membership error first — the
18212        // missing-member diagnostic is more locating than the
18213        // duplicate-edge one (the author has to fix the membership
18214        // before the duplicate is meaningful). Same ordering
18215        // discipline as `membros_validation_runs_before_contratos_membership_check`.
18216        let mut s = three_member_spec();
18217        s.contratos.push(contract_http("phantom", "catalog", "/x"));
18218        s.contratos.push(contract_http("phantom", "catalog", "/x"));
18219        let err = s.validate().unwrap_err();
18220        assert!(
18221            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
18222            "membership-missing must fire before duplicate-edge (got {err:?})"
18223        );
18224    }
18225
18226    #[test]
18227    fn duplicate_contrato_gate_runs_after_target_shape_check() {
18228        // Order pin: a contract with a malformed target (e.g. an HTTP
18229        // wit world with an empty :endpoint) surfaces the target-shape
18230        // error first, not the duplicate one. Even when two such
18231        // malformed entries are identical, the per-contract `target()`
18232        // check fires inside the loop *before* the duplicate-key
18233        // insert, so the diagnostic remains the most-locating one.
18234        let mut s = three_member_spec();
18235        let malformed = WitContract {
18236            de: "cart".into(),
18237            para: "catalog".into(),
18238            wit: "wasi:http/proxy".into(),
18239            endpoint: Some(String::new()),
18240            subject: None,
18241            slot: None,
18242        };
18243        s.contratos.push(malformed.clone());
18244        s.contratos.push(malformed);
18245        let err = s.validate().unwrap_err();
18246        assert!(
18247            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
18248            "endpoint-empty must fire before duplicate-edge (got {err:?})"
18249        );
18250    }
18251
18252    #[test]
18253    fn wit_target_label_pins_per_variant_format() {
18254        // Label format is the single source of truth every duplicate-
18255        // `:contratos` diagnostic + every future `feira app graph`
18256        // consumer routes through. Pin the shape per variant so a
18257        // future edit to `WitTarget::label` (e.g. a JSON emitter that
18258        // strips the leading `:`, or a rename from `endpoint` →
18259        // `path`) surfaces as a red-red test rather than as a silent
18260        // downstream diagnostic drift. Together with the exhaustive
18261        // `match` on `WitTarget` inside `label()`, adding a future
18262        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
18263        // peer, per-edge WIT registry variants) is a compile error at
18264        // the label site — not a fall-through into the `Capability`
18265        // "no payload" default the prior raw-field-probe helper
18266        // silently landed on.
18267        assert_eq!(
18268            WitTarget::Http {
18269                endpoint: "/charge",
18270            }
18271            .label(),
18272            "\
18273:endpoint \"/charge\""
18274        );
18275        assert_eq!(
18276            WitTarget::PubSub {
18277                subject: "events.checkout.paid",
18278            }
18279            .label(),
18280            "\
18281:subject \"events.checkout.paid\""
18282        );
18283        assert_eq!(
18284            WitTarget::Store {
18285                slot: "checkout/$order",
18286            }
18287            .label(),
18288            "\
18289:slot \"checkout/$order\""
18290        );
18291        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
18292        // Capability-arm label routes through the lifted
18293        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
18294        // declaration per arm, next to the variant" discipline the
18295        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
18296        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
18297        // consts already carry extends to the payload-less arm; the
18298        // byte-string equality pin below plus this label-routes-
18299        // through-the-const pin make a future rebrand on either the
18300        // const declaration or the `label()` template a build error
18301        // here rather than a downstream consumer surprise.
18302        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
18303        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
18304    }
18305
18306    #[test]
18307    fn wit_target_display_routes_through_label_helper() {
18308        // Fail-before-pass-after pin on the fourth (and only remaining)
18309        // typed-shape-discriminator axis to converge onto the
18310        // three-path-convergence discipline the sibling M3
18311        // [`PlacementStrategy`] (0a2f653) and M2
18312        // [`crate::supervisor::RestartStrategy`] /
18313        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
18314        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
18315        // through [`WitTarget::label`], so every consumer reaching for
18316        // `format!("{v}")` on a typed payload target lands on the same
18317        // stable author-facing byte-string [`WitTarget::label`] returns
18318        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
18319        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
18320        // `:contratos` gate seeds via [`WitTarget::label`] at
18321        // aplicacao.rs:5491 already threads through.
18322        //
18323        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
18324        // through to the `Debug` derive's structural output
18325        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
18326        // rather than the [`WitTarget::label`] helper's stable byte-
18327        // string (`:endpoint "/charge"` — the author-facing `:contratos`
18328        // keyword form). Every future consumer that reaches for
18329        // `format!("{target}")` — the canonical shape every user-facing
18330        // pretty-print site on the sibling typed-enum axes
18331        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
18332        // [`crate::supervisor::RestartPolicy`]) already uses — would
18333        // silently land under a different byte-string than the
18334        // [`WitTarget::label`] callers that the duplicate-`:contratos`
18335        // diagnostic already threads through, with the mismatch
18336        // surfacing as a downstream diagnostic / graph / audit line
18337        // reading one spelling while the substrate's own gate emitted
18338        // another.
18339        //
18340        // Pin the routing here so a future
18341        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
18342        // that hand-rolls the per-arm formatting instead of delegating
18343        // to [`WitTarget::label`] fails at caixa-core build time.
18344        for variant in [
18345            WitTarget::Http {
18346                endpoint: "/charge",
18347            },
18348            WitTarget::PubSub {
18349                subject: "events.checkout.paid",
18350            },
18351            WitTarget::Store {
18352                slot: "checkout/$order",
18353            },
18354            WitTarget::Capability,
18355        ] {
18356            assert_eq!(
18357                variant.to_string(),
18358                variant.label(),
18359                "WitTarget::{variant:?} Display must route through \
18360                 WitTarget::label (single source of truth: the lifted \
18361                 payload_pair 4-arm dispatch the label helper already \
18362                 threads through)"
18363            );
18364        }
18365    }
18366
18367    #[test]
18368    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
18369        // Consumer-side pin on the three-path convergence:
18370        // [`std::fmt::Display`] agrees byte-for-byte with the
18371        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
18372        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
18373        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
18374        // Pre-lift the two paths were structurally independent — the
18375        // substrate-side gate reached for `target_view.label()` while a
18376        // future downstream diagnostic / graph / audit line reaching
18377        // for `format!("{target}")` would silently land on the `Debug`
18378        // derive's structural output. Pin the two paths byte-for-byte
18379        // here so any future variant addition (M4 `Rest`/`Grpc` split
18380        // of [`WitTarget::Http`], `Queue`-shaped peer of
18381        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
18382        // match error at [`WitTarget::payload_pair`] rather than a
18383        // silent per-consumer dispatch miss.
18384        for variant in [
18385            WitTarget::Http {
18386                endpoint: "/charge",
18387            },
18388            WitTarget::PubSub {
18389                subject: "events.checkout.paid",
18390            },
18391            WitTarget::Store {
18392                slot: "checkout/$order",
18393            },
18394            WitTarget::Capability,
18395        ] {
18396            assert_eq!(
18397                format!("{variant}"),
18398                variant.label(),
18399                "WitTarget::{variant:?} Display byte-string must match \
18400                 the AplicacaoError::ContratoDuplicate `target:` carrier \
18401                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
18402                 seeds via WitTarget::label — three-path convergence: \
18403                 Display + label + payload_pair all resolve to the same \
18404                 per-arm byte-string"
18405            );
18406        }
18407    }
18408
18409    #[test]
18410    fn wit_target_payload_pair_pins_per_variant() {
18411        // Pin the per-arm `(field-name, payload)` pair single-sourced
18412        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
18413        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
18414        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
18415        // and [`WitTarget::field_name`] (returns the first component)
18416        // route through. Until this lift landed [`WitTarget::label`]
18417        // dispatched on the same three arms with a per-arm
18418        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
18419        // paired [`WitTarget::HTTP_FIELD_NAME`] /
18420        // [`WitTarget::PUBSUB_FIELD_NAME`] /
18421        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
18422        // canonical "same shape, written N times" duplication
18423        // THEORY.md §I.3.5 promotes to a build-time concern. A future
18424        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
18425        // [`WitTarget::Http`], `Queue`-shaped peer of
18426        // [`WitTarget::Store`]) is one match-arm edit at
18427        // [`WitTarget::payload_pair`], visible here as a compile-time
18428        // exhaustiveness error on both this pin and the label-format
18429        // pin above.
18430        assert_eq!(
18431            WitTarget::Http {
18432                endpoint: "/charge"
18433            }
18434            .payload_pair(),
18435            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
18436        );
18437        assert_eq!(
18438            WitTarget::PubSub {
18439                subject: "events.x",
18440            }
18441            .payload_pair(),
18442            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
18443        );
18444        assert_eq!(
18445            WitTarget::Store {
18446                slot: "checkout/$order",
18447            }
18448            .payload_pair(),
18449            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
18450        );
18451        assert_eq!(WitTarget::Capability.payload_pair(), None);
18452    }
18453
18454    #[test]
18455    fn wit_target_field_name_pins_per_variant() {
18456        // Pin the per-arm author-facing `:contratos` payload field
18457        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
18458        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
18459        // + returned by [`WitTarget::field_name`]. Every downstream
18460        // consumer (the [`WitContract::target`] gate's `expected:`
18461        // scalar, the [`WitTarget::label`] template's keyword prefix,
18462        // the `feira app graph` verb's `endpoint=…` prefix) routes
18463        // through the same three peer consts, so a rename on the
18464        // author-surface `(defcaixa … :contratos ((:de … :para …
18465        // :wit … :endpoint …)))` field lands in exactly one place.
18466        assert_eq!(
18467            WitTarget::Http {
18468                endpoint: "/charge"
18469            }
18470            .field_name(),
18471            Some(WitTarget::HTTP_FIELD_NAME),
18472        );
18473        assert_eq!(
18474            WitTarget::PubSub {
18475                subject: "events.x",
18476            }
18477            .field_name(),
18478            Some(WitTarget::PUBSUB_FIELD_NAME),
18479        );
18480        assert_eq!(
18481            WitTarget::Store {
18482                slot: "checkout/$order",
18483            }
18484            .field_name(),
18485            Some(WitTarget::STORE_FIELD_NAME),
18486        );
18487        // Capability arm carries no payload field — the diagnostic
18488        // never reports `expected: "capability"` because the gate's
18489        // Capability arm accepts no payload at all (it fires the
18490        // "expected: none" WrongTarget error instead), so the field-
18491        // name method returns None here rather than a placeholder.
18492        assert_eq!(WitTarget::Capability.field_name(), None);
18493
18494        // Peer const scalar values pinned so a rename on either side
18495        // (author-surface field name in the `(defcaixa …)` DSL, or
18496        // the diagnostic's `expected:` scalar) can't drift without
18497        // failing here first.
18498        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
18499        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
18500        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
18501    }
18502
18503    #[test]
18504    fn wit_target_payload_pins_per_variant() {
18505        // Pin the per-arm payload scalar single-sourced onto the
18506        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
18507        // [`WitTarget::payload`] — the peer per-half projection to
18508        // [`WitTarget::field_name`] on the paired sub-selector axis. The
18509        // three payload-carrying arms round-trip their author-declared
18510        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
18511        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
18512        // the payload-less [`WitTarget::Capability`] arm returns `None`.
18513        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
18514        // (c6ec2af) pin on the Component-0 projection axis, extended
18515        // onto the Component-1 projection axis so both per-half readers
18516        // on the paired dispatch carry their own byte-shape pin.
18517        assert_eq!(
18518            WitTarget::Http {
18519                endpoint: "/charge",
18520            }
18521            .payload(),
18522            Some("/charge"),
18523        );
18524        assert_eq!(
18525            WitTarget::PubSub {
18526                subject: "events.x",
18527            }
18528            .payload(),
18529            Some("events.x"),
18530        );
18531        assert_eq!(
18532            WitTarget::Store {
18533                slot: "checkout/$order",
18534            }
18535            .payload(),
18536            Some("checkout/$order"),
18537        );
18538        assert_eq!(WitTarget::Capability.payload(), None);
18539    }
18540
18541    #[test]
18542    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
18543        // Per-variant equivalence pin: for every arm of [`WitTarget`],
18544        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
18545        // byte-for-byte. Guards the drift surface where a future refactor
18546        // that split one accessor off the shared match onto its own
18547        // dispatch — a well-meaning "inline the pair back into per-half
18548        // fields for one crate-internal caller who only wanted one half"
18549        // or a scratch `impl` shadowing the derived projection — would
18550        // silently desynchronize [`WitTarget::payload`] from the
18551        // authoritative [`WitTarget::payload_pair`] dispatch, and every
18552        // downstream consumer that thinks "the payload half of the pair"
18553        // would drift from the diagnostic / graph consumers reading the
18554        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
18555        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
18556        // per-half projection pin (`gitrefspec_ref_pair_projects_
18557        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
18558        // FluxCD source-controller `spec.ref.<field>` axis — same "one
18559        // paired dispatch, both per-half projections agree byte-for-
18560        // byte" discipline extended onto the M3 `:contratos` payload-
18561        // arm surface.
18562        for variant in [
18563            WitTarget::Http {
18564                endpoint: "/charge",
18565            },
18566            WitTarget::PubSub {
18567                subject: "events.checkout.paid",
18568            },
18569            WitTarget::Store {
18570                slot: "checkout/$order",
18571            },
18572            WitTarget::Capability,
18573        ] {
18574            let via_projection = variant.payload();
18575            let via_pair = variant.payload_pair().map(|(_, p)| p);
18576            assert_eq!(
18577                via_projection, via_pair,
18578                "WitTarget::{variant:?} payload() must equal \
18579                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
18580                 regression that splits the two per-half projections off \
18581                 their shared match would silently desynchronize the \
18582                 payload accessor from the paired dispatch every \
18583                 diagnostic / graph consumer reads through",
18584            );
18585        }
18586    }
18587
18588    #[test]
18589    fn wit_target_http_endpoint_pins_per_variant() {
18590        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
18591        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
18592        // substrate-primitive per-arm post-projection accessor every
18593        // L7-HTTP-facing consumer routes through, sibling to the peer
18594        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
18595        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
18596        // arm round-trips its author-declared endpoint verbatim as
18597        // `Some("/charge")`; the three sibling arms
18598        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
18599        // [`WitTarget::Capability`]) each return `None` because they
18600        // carry no HTTP endpoint by definition. Same fail-before-pass-
18601        // after per-variant discipline as the sibling
18602        // `wit_target_payload_pins_per_variant` (5d6dc92) /
18603        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
18604        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
18605        // the peer pan-arm / per-half projection axes — extended onto
18606        // the per-arm HTTP-shape post-projection axis so a future
18607        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
18608        // [`WitTarget::Http`], a `Queue`-shaped peer of
18609        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
18610        // error on the sibling [`WitTarget::http_endpoint`] match arms
18611        // whose payload the L7-HTTP-shape accept-set is meant to bound.
18612        assert_eq!(
18613            WitTarget::Http {
18614                endpoint: "/charge",
18615            }
18616            .http_endpoint(),
18617            Some("/charge"),
18618        );
18619        assert_eq!(
18620            WitTarget::PubSub {
18621                subject: "events.checkout.paid",
18622            }
18623            .http_endpoint(),
18624            None,
18625        );
18626        assert_eq!(
18627            WitTarget::Store {
18628                slot: "checkout/$order",
18629            }
18630            .http_endpoint(),
18631            None,
18632        );
18633        assert_eq!(WitTarget::Capability.http_endpoint(), None);
18634    }
18635
18636    #[test]
18637    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
18638        // Per-variant coherence pin: for every arm of [`WitTarget`],
18639        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
18640        // arm (both project the same author-declared request-path
18641        // scalar), and returns `None` on every sibling arm regardless of
18642        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
18643        // Store carry their own payload the pan-arm accessor surfaces,
18644        // but that payload is not an HTTP endpoint — the per-arm
18645        // accessor must not leak it through the HTTP-shape channel).
18646        // Guards the drift surface where a future refactor that
18647        // conflated the per-arm HTTP projection with the pan-arm
18648        // [`WitTarget::payload`] projection — a well-meaning "one
18649        // accessor for the L7 branch, one for the graph" collapse that
18650        // routes both through the same 4-arm dispatch — would silently
18651        // widen the L7-HTTP-shape accept-set onto pub-sub / store
18652        // payloads at the caixa-mesh L7 emit branch, admitting a
18653        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
18654        // rule with the operator-side apply-time symptom (Cilium's
18655        // eBPF data-plane rejects every ingress edge whose L7 filter
18656        // doesn't match the wire-format HTTP request line) far from
18657        // the source refactor. Sibling to the peer
18658        // `wit_target_payload_matches_payload_pair_second_component_
18659        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
18660        // extended onto the per-arm HTTP specialization axis so both
18661        // the pan-arm and the per-arm projections carry their own
18662        // byte-shape coherence witness against the substrate's typed
18663        // arm-family accept-set.
18664        for variant in [
18665            WitTarget::Http {
18666                endpoint: "/charge",
18667            },
18668            WitTarget::PubSub {
18669                subject: "events.checkout.paid",
18670            },
18671            WitTarget::Store {
18672                slot: "checkout/$order",
18673            },
18674            WitTarget::Capability,
18675        ] {
18676            let per_arm = variant.http_endpoint();
18677            let pan_arm = variant.payload();
18678            if variant.is_http() {
18679                assert_eq!(
18680                    per_arm, pan_arm,
18681                    "WitTarget::{variant:?} http_endpoint() must equal \
18682                     payload() on the Http arm — a per-arm-vs-pan-arm \
18683                     split would silently drift the L7 emit branch's \
18684                     path-scalar source from the graph verb's payload \
18685                     scalar source",
18686                );
18687            } else {
18688                assert_eq!(
18689                    per_arm, None,
18690                    "WitTarget::{variant:?} http_endpoint() must return \
18691                     None on non-Http arms — a leak that surfaced a \
18692                     pub-sub :subject or a key/value :slot through the \
18693                     HTTP-endpoint accessor would silently widen the \
18694                     Cilium L7 HTTP `path:` rule accept-set onto \
18695                     protocol shapes Cilium's eBPF data-plane can't \
18696                     introspect",
18697                );
18698            }
18699        }
18700    }
18701
18702    #[test]
18703    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
18704        // Per-variant coherence pin: for every arm of [`WitTarget`],
18705        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
18706        // drift surface where a future extension of the
18707        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
18708        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
18709        // accessor to cover both peers) landed without a paired
18710        // extension of the [`gen_platform::IsVariant`]-derived
18711        // `is_http()` predicate's accept-set, or vice versa — a
18712        // regression that split the "which arms count as HTTP-shaped
18713        // for L7-path emission?" answer between two dispatch surfaces
18714        // the substrate ships. Sibling to the peer
18715        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
18716        // on the paired dispatch axis — extended onto the per-arm
18717        // predicate-vs-accessor coherence axis so the gen-platform
18718        // IsVariant predicate and the substrate-lifted per-arm
18719        // accessor carry one shared answer to "is this the HTTP arm?".
18720        for variant in [
18721            WitTarget::Http {
18722                endpoint: "/charge",
18723            },
18724            WitTarget::PubSub {
18725                subject: "events.checkout.paid",
18726            },
18727            WitTarget::Store {
18728                slot: "checkout/$order",
18729            },
18730            WitTarget::Capability,
18731        ] {
18732            assert_eq!(
18733                variant.http_endpoint().is_some(),
18734                variant.is_http(),
18735                "WitTarget::{variant:?} http_endpoint().is_some() must \
18736                 equal is_http() — a drift would split the L7 emit \
18737                 branch's arm-set gate from the substrate-derived \
18738                 shape-discrimination predicate on the same axis",
18739            );
18740        }
18741    }
18742
18743    #[test]
18744    fn wit_target_pubsub_subject_pins_per_variant() {
18745        // Fail-before-pass-after pin: the substrate-canonical per-arm
18746        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
18747        // is the single dispatch every future pub-sub-facing consumer
18748        // routes through, sibling to the peer [`WitContract::subject`]
18749        // (63e18a0) pre-projection scalar accessor on the raw-field
18750        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
18751        // post-projection per-arm accessor on the sibling HTTP-shape
18752        // axis. The [`WitTarget::PubSub`] arm round-trips its
18753        // author-declared subject verbatim as
18754        // `Some("events.checkout.paid")`; the three sibling arms each
18755        // return `None` because they carry no NATS-shaped subject by
18756        // definition. Same fail-before-pass-after per-variant discipline
18757        // as the sibling `wit_target_http_endpoint_pins_per_variant`
18758        // pin on the peer per-arm axis — extended onto the per-arm
18759        // pub-sub-shape post-projection axis so a future [`WitTarget`]
18760        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
18761        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
18762        // compile-time exhaustiveness error on the sibling
18763        // [`WitTarget::pubsub_subject`] match arms whose payload the
18764        // pub-sub-shape accept-set is meant to bound.
18765        assert_eq!(
18766            WitTarget::PubSub {
18767                subject: "events.checkout.paid",
18768            }
18769            .pubsub_subject(),
18770            Some("events.checkout.paid"),
18771        );
18772        assert_eq!(
18773            WitTarget::Http {
18774                endpoint: "/charge",
18775            }
18776            .pubsub_subject(),
18777            None,
18778        );
18779        assert_eq!(
18780            WitTarget::Store {
18781                slot: "checkout/$order",
18782            }
18783            .pubsub_subject(),
18784            None,
18785        );
18786        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
18787    }
18788
18789    #[test]
18790    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
18791        // Per-variant coherence pin: for every arm of [`WitTarget`],
18792        // `.pubsub_subject()` equals `.payload()` on the
18793        // [`WitTarget::PubSub`] arm (both project the same
18794        // author-declared subject scalar), and returns `None` on every
18795        // sibling arm regardless of whether [`WitTarget::payload`]
18796        // itself returns `Some` (Http / Store carry their own payload
18797        // the pan-arm accessor surfaces, but that payload is not a
18798        // pub-sub subject — the per-arm accessor must not leak it
18799        // through the pub-sub-shape channel). Sibling to the peer
18800        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
18801        // coherence pin on the per-arm HTTP-shape axis — extended onto
18802        // the per-arm pub-sub specialization axis so both per-arm
18803        // projections carry their own byte-shape coherence witness
18804        // against the substrate's typed arm-family accept-set.
18805        for variant in [
18806            WitTarget::Http {
18807                endpoint: "/charge",
18808            },
18809            WitTarget::PubSub {
18810                subject: "events.checkout.paid",
18811            },
18812            WitTarget::Store {
18813                slot: "checkout/$order",
18814            },
18815            WitTarget::Capability,
18816        ] {
18817            let per_arm = variant.pubsub_subject();
18818            let pan_arm = variant.payload();
18819            if variant.is_pubsub() {
18820                assert_eq!(
18821                    per_arm, pan_arm,
18822                    "WitTarget::{variant:?} pubsub_subject() must equal \
18823                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
18824                     split would silently drift the pub-sub-shape emit \
18825                     branch's subject-scalar source from the graph verb's \
18826                     payload scalar source",
18827                );
18828            } else {
18829                assert_eq!(
18830                    per_arm, None,
18831                    "WitTarget::{variant:?} pubsub_subject() must return \
18832                     None on non-PubSub arms — a leak that surfaced an \
18833                     HTTP :endpoint or a key/value :slot through the \
18834                     pub-sub-subject accessor would silently widen the \
18835                     downstream NATS-shape accept-set onto protocol \
18836                     shapes NATS servers can't route",
18837                );
18838            }
18839        }
18840    }
18841
18842    #[test]
18843    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
18844        // Per-variant coherence pin: for every arm of [`WitTarget`],
18845        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
18846        // drift surface where a future extension of the
18847        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
18848        // without a paired extension of the [`gen_platform::IsVariant`]-
18849        // derived `is_pubsub()` predicate's accept-set, or vice versa
18850        // — a regression that split the "which arms count as pub-sub-
18851        // shaped for subject emission?" answer between two dispatch
18852        // surfaces the substrate ships. Sibling to the peer
18853        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
18854        // pin on the per-arm HTTP-shape axis — extended onto the
18855        // per-arm pub-sub predicate-vs-accessor coherence axis so the
18856        // gen-platform IsVariant predicate and the substrate-lifted
18857        // per-arm accessor carry one shared answer to "is this the
18858        // PubSub arm?".
18859        for variant in [
18860            WitTarget::Http {
18861                endpoint: "/charge",
18862            },
18863            WitTarget::PubSub {
18864                subject: "events.checkout.paid",
18865            },
18866            WitTarget::Store {
18867                slot: "checkout/$order",
18868            },
18869            WitTarget::Capability,
18870        ] {
18871            assert_eq!(
18872                variant.pubsub_subject().is_some(),
18873                variant.is_pubsub(),
18874                "WitTarget::{variant:?} pubsub_subject().is_some() must \
18875                 equal is_pubsub() — a drift would split the pub-sub \
18876                 emit branch's arm-set gate from the substrate-derived \
18877                 shape-discrimination predicate on the same axis",
18878            );
18879        }
18880    }
18881
18882    #[test]
18883    fn wit_target_store_slot_pins_per_variant() {
18884        // Fail-before-pass-after pin: the substrate-canonical per-arm
18885        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
18886        // is the single dispatch every future store-facing consumer
18887        // routes through, sibling to the peer [`WitContract::slot`]
18888        // pre-projection scalar accessor on the raw-field axis and to
18889        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
18890        // [`WitTarget::pubsub_subject`] post-projection per-arm
18891        // accessors on the sibling per-payload-arm axes. The
18892        // [`WitTarget::Store`] arm round-trips its author-declared
18893        // slot verbatim as `Some("checkout/$order")`; the three
18894        // sibling arms each return `None` because they carry no
18895        // WASI-key/value slot by definition. Same fail-before-pass-
18896        // after per-variant discipline as the sibling
18897        // `wit_target_http_endpoint_pins_per_variant` +
18898        // `wit_target_pubsub_subject_pins_per_variant` pins on the
18899        // peer per-arm axes — extended onto the per-arm store-shape
18900        // post-projection axis so a future [`WitTarget`] variant
18901        // addition trips a compile-time exhaustiveness error on the
18902        // sibling [`WitTarget::store_slot`] match arms whose payload
18903        // the store-shape accept-set is meant to bound.
18904        assert_eq!(
18905            WitTarget::Store {
18906                slot: "checkout/$order",
18907            }
18908            .store_slot(),
18909            Some("checkout/$order"),
18910        );
18911        assert_eq!(
18912            WitTarget::Http {
18913                endpoint: "/charge",
18914            }
18915            .store_slot(),
18916            None,
18917        );
18918        assert_eq!(
18919            WitTarget::PubSub {
18920                subject: "events.checkout.paid",
18921            }
18922            .store_slot(),
18923            None,
18924        );
18925        assert_eq!(WitTarget::Capability.store_slot(), None);
18926    }
18927
18928    #[test]
18929    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
18930        // Per-variant coherence pin: for every arm of [`WitTarget`],
18931        // `.store_slot()` equals `.payload()` on the
18932        // [`WitTarget::Store`] arm (both project the same
18933        // author-declared slot scalar), and returns `None` on every
18934        // sibling arm regardless of whether [`WitTarget::payload`]
18935        // itself returns `Some`. Sibling to the peer
18936        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
18937        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
18938        // pins on the per-arm HTTP and PubSub axes — closes the
18939        // per-arm-vs-pan-arm byte-shape coherence trio across all
18940        // three payload arms.
18941        for variant in [
18942            WitTarget::Http {
18943                endpoint: "/charge",
18944            },
18945            WitTarget::PubSub {
18946                subject: "events.checkout.paid",
18947            },
18948            WitTarget::Store {
18949                slot: "checkout/$order",
18950            },
18951            WitTarget::Capability,
18952        ] {
18953            let per_arm = variant.store_slot();
18954            let pan_arm = variant.payload();
18955            if variant.is_store() {
18956                assert_eq!(
18957                    per_arm, pan_arm,
18958                    "WitTarget::{variant:?} store_slot() must equal \
18959                     payload() on the Store arm — a per-arm-vs-pan-arm \
18960                     split would silently drift the store-shape emit \
18961                     branch's slot-scalar source from the graph verb's \
18962                     payload scalar source",
18963                );
18964            } else {
18965                assert_eq!(
18966                    per_arm, None,
18967                    "WitTarget::{variant:?} store_slot() must return \
18968                     None on non-Store arms — a leak that surfaced an \
18969                     HTTP :endpoint or a NATS :subject through the \
18970                     key/value-slot accessor would silently widen the \
18971                     downstream WASI-key/value slot accept-set onto \
18972                     protocol shapes the kv backends can't route",
18973                );
18974            }
18975        }
18976    }
18977
18978    #[test]
18979    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
18980        // Per-variant coherence pin: for every arm of [`WitTarget`],
18981        // `.store_slot().is_some()` iff `.is_store()`. Guards the
18982        // drift surface where a future extension of the
18983        // [`WitTarget::store_slot`] accessor's accept-set landed
18984        // without a paired extension of the [`gen_platform::IsVariant`]-
18985        // derived `is_store()` predicate's accept-set. Sibling to the
18986        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
18987        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
18988        // pins — closes the per-arm predicate-vs-accessor coherence
18989        // trio across all three payload arms so the gen-platform
18990        // IsVariant predicate and the substrate-lifted per-arm
18991        // accessor carry one shared answer to "is this the Store arm?".
18992        for variant in [
18993            WitTarget::Http {
18994                endpoint: "/charge",
18995            },
18996            WitTarget::PubSub {
18997                subject: "events.checkout.paid",
18998            },
18999            WitTarget::Store {
19000                slot: "checkout/$order",
19001            },
19002            WitTarget::Capability,
19003        ] {
19004            assert_eq!(
19005                variant.store_slot().is_some(),
19006                variant.is_store(),
19007                "WitTarget::{variant:?} store_slot().is_some() must \
19008                 equal is_store() — a drift would split the store-shape \
19009                 emit branch's arm-set gate from the substrate-derived \
19010                 shape-discrimination predicate on the same axis",
19011            );
19012        }
19013    }
19014
19015    #[test]
19016    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
19017        // Fail-before-pass-after cross-axis pin on the trio
19018        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
19019        // payload-carrying arm of [`WitTarget`], exactly one per-arm
19020        // accessor returns `Some(payload)` and the two peers return
19021        // `None`; and on the payload-less [`WitTarget::Capability`]
19022        // arm, all three return `None`. Guards the drift surface where
19023        // a future extension of one per-arm accessor's accept-set (e.g.
19024        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
19025        // that widened `http_endpoint` to cover both peers without
19026        // narrowing the peer `pubsub_subject` / `store_slot` accept-
19027        // sets to keep the partition mutually exclusive) landed without
19028        // threading through the peer per-arm accessors — the resulting
19029        // silent overlap would land the same edge's payload on two
19030        // downstream per-shape emit branches at once, or leak a
19031        // pub-sub subject through the store-slot channel, at renderer
19032        // emit time far from the substrate primitive's arm-widening
19033        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
19034        // 3-way pin on the payload-field-name axis — extended onto the
19035        // per-arm-accessor payload-projection axis so the substrate-
19036        // owned partition invariant is load-bearing at every per-arm
19037        // consumer's read site.
19038        let payload_variants = [
19039            (
19040                WitTarget::Http {
19041                    endpoint: "/charge",
19042                },
19043                "http",
19044            ),
19045            (
19046                WitTarget::PubSub {
19047                    subject: "events.checkout.paid",
19048                },
19049                "pubsub",
19050            ),
19051            (
19052                WitTarget::Store {
19053                    slot: "checkout/$order",
19054                },
19055                "store",
19056            ),
19057        ];
19058        for (variant, own_arm_label) in payload_variants {
19059            let own_arm_hit = match own_arm_label {
19060                "http" => variant.is_http(),
19061                "pubsub" => variant.is_pubsub(),
19062                "store" => variant.is_store(),
19063                other => panic!("unknown own-arm label {other:?}"),
19064            };
19065            let per_arm_results = [
19066                ("http_endpoint", variant.http_endpoint()),
19067                ("pubsub_subject", variant.pubsub_subject()),
19068                ("store_slot", variant.store_slot()),
19069            ];
19070            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
19071            assert_eq!(
19072                some_count, 1,
19073                "WitTarget::{variant:?} must land exactly one per-arm \
19074                 post-projection accessor's Some result — the trio \
19075                 (http_endpoint, pubsub_subject, store_slot) must \
19076                 partition the payload arm-set; got {per_arm_results:?}",
19077            );
19078            assert!(
19079                own_arm_hit,
19080                "WitTarget::{variant:?} own-arm gen-platform predicate \
19081                 must return true on its own arm — a partition failure \
19082                 upstream of this pin",
19083            );
19084            assert!(
19085                variant.payload().is_some(),
19086                "WitTarget::{variant:?} pan-arm payload() must return \
19087                 Some on every payload-carrying arm the trio partitions",
19088            );
19089        }
19090        // The payload-less Capability arm must return None on every
19091        // per-arm accessor — the partition's terminal-fallback shape.
19092        let cap = WitTarget::Capability;
19093        assert_eq!(cap.http_endpoint(), None);
19094        assert_eq!(cap.pubsub_subject(), None);
19095        assert_eq!(cap.store_slot(), None);
19096        assert_eq!(
19097            cap.payload(),
19098            None,
19099            "WitTarget::Capability pan-arm payload() must return None — \
19100             the trio's payload-less-arm coherence witness",
19101        );
19102    }
19103
19104    #[test]
19105    fn wit_target_field_names_are_pairwise_distinct() {
19106        // Distinctness pin: if any two of the three payload-field-name
19107        // scalars ever collapse (e.g. an accidental `endpoint` copy-
19108        // paste over the `subject` const), the [`WitContract::target`]
19109        // gate's diagnostic would point authors at the wrong field —
19110        // an "expected `:endpoint`" error on a pub-sub edge would
19111        // silently misroute the fix. Same cross-axis-distinctness
19112        // discipline as the peer M3 `:placement :estrategia` variant-
19113        // discriminator scalar-value pins (cc8f749) applied to the
19114        // payload-field-name axis.
19115        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
19116        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
19117        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
19118    }
19119
19120    #[test]
19121    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
19122        // Fail-before-pass-after pin: the graph-verb payload column's
19123        // per-arm `{field}={payload}` byte-string is derived through the
19124        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
19125        // payload-carrying arms, not through a hand-rolled per-arm match
19126        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
19127        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
19128        // inline. A future variant addition — the M4-and-later per-edge
19129        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
19130        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
19131        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
19132        // and both [`WitTarget::label`] (duplicate-`:contratos`
19133        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
19134        // payload column) pick up the new arm from the same dispatch.
19135        // Prior to this lift the graph verb open-coded the 4-arm match
19136        // in caixa-feira, so a variant addition would have to be threaded
19137        // through both projections in lockstep or the graph verb would
19138        // silently drop the new arm to `(capability-only)`.
19139        for variant in [
19140            WitTarget::Http {
19141                endpoint: "/charge",
19142            },
19143            WitTarget::PubSub {
19144                subject: "events.checkout.paid",
19145            },
19146            WitTarget::Store {
19147                slot: "checkout/$order",
19148            },
19149        ] {
19150            let (field, payload) = variant
19151                .payload_pair()
19152                .expect("payload arm must expose (field, payload)");
19153            assert_eq!(
19154                variant.graph_label(),
19155                format!("{field}={payload}"),
19156                "WitTarget::{variant:?} graph_label must route the \
19157                 `{{field}}={{payload}}` template through payload_pair — \
19158                 a regression to a hand-rolled per-arm match at the graph \
19159                 verb would silently disagree with a future variant \
19160                 addition landed only at payload_pair"
19161            );
19162        }
19163    }
19164
19165    #[test]
19166    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
19167        // Fail-before-pass-after pin on the payload-less arm: the graph
19168        // verb's `(capability-only)` byte-string routes through the
19169        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
19170        // [`WitTarget::Capability`] arm, not through an inline
19171        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
19172        // per-`:contratos` payload column. Peer of the sibling
19173        // [`wit_target_label_pins_per_variant_format`] Capability-arm
19174        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
19175        // extended here onto the third payload-less-arm consumer axis
19176        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
19177        // axis and the wrong-target diagnostic axis).
19178        assert_eq!(
19179            WitTarget::Capability.graph_label(),
19180            WitTarget::CAPABILITY_GRAPH_LABEL,
19181        );
19182        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
19183    }
19184
19185    #[test]
19186    fn wit_target_capability_graph_label_distinct_from_capability_label() {
19187        // Cross-consumer-axis distinctness pin: the graph-verb
19188        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
19189        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
19190        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
19191        // payload)`) surface the payload-less arm on two distinct
19192        // consumer axes; a collapse (an accidental rebrand that lands
19193        // one spelling on both consts, a copy-paste that unifies them
19194        // "for consistency") would silently merge the two byte-strings
19195        // and lose the vocabulary distinction the graph verb's
19196        // compact-column form and the diagnostic's descriptive-clause
19197        // form each carry on purpose. Peer of the sibling 4-way
19198        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
19199        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
19200        // extended here onto the cross-consumer-axis distinctness of the
19201        // two payload-less-arm consts.
19202        assert_ne!(
19203            WitTarget::CAPABILITY_GRAPH_LABEL,
19204            WitTarget::CAPABILITY_LABEL,
19205            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
19206             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
19207             diagnostic) must remain distinct — a collapse would silently \
19208             merge two consumer axes onto one spelling"
19209        );
19210    }
19211
19212    #[test]
19213    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
19214        // 4-way distinctness pin extending the sibling
19215        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
19216        // (which covers only the HTTP / PubSub / Store payload arms)
19217        // onto the fourth scalar the shared
19218        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
19219        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
19220        // (`"none"`), the payload-less Capability-arm rejection scalar.
19221        //
19222        // All four [`WitTarget::HTTP_FIELD_NAME`] /
19223        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
19224        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
19225        // dispatch surface [`WitContract::target`] writes onto the
19226        // `ContratoWrongTarget::expected` field — the same `&'static
19227        // str` axis authors read as "this WIT world's shape admits
19228        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
19229        // downstream consumers rely on: an `expected: "endpoint"`
19230        // diagnostic on a Capability-shaped edge tells the author to
19231        // add a `:endpoint "…"` slot to a WIT world that admits none,
19232        // silently misrouting the fix. Until this pin landed the three
19233        // payload-arm consts were distinctness-guarded by the sibling
19234        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
19235        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
19236        // author-facing vocabulary shift from `"none"` to `"endpoint"`
19237        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
19238        // into per-shape peers) would have silently landed one
19239        // Capability-arm rejection on a payload-arm's `expected:` byte-
19240        // string and desynchronized the diagnostic from the author's
19241        // typed shape.
19242        //
19243        // Same 4-way pairwise-distinctness pin discipline as the peer
19244        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
19245        // (cc8f749) applies on the sibling M3 closed-set typed-enum
19246        // scalar-value dispatch axis; extends the pin trajectory the
19247        // sibling `wit_target_field_names_are_pairwise_distinct`
19248        // 3-way pin opened to cover the last unguarded corner on the
19249        // `ContratoWrongTarget::expected` scalar-value axis.
19250        //
19251        // Fail-before-pass-after locally verified by mutating
19252        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
19253        // — this pin fires as expected; restoring passes.
19254        let all = [
19255            WitTarget::HTTP_FIELD_NAME,
19256            WitTarget::PUBSUB_FIELD_NAME,
19257            WitTarget::STORE_FIELD_NAME,
19258            WitTarget::CAPABILITY_EXPECTED,
19259        ];
19260        for (i, a) in all.iter().enumerate() {
19261            for (j, b) in all.iter().enumerate() {
19262                if i != j {
19263                    assert_ne!(
19264                        a, b,
19265                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
19266                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
19267                         pairwise distinct — got duplicate {a:?} at indices \
19268                         {i} and {j}; all four scalars thread through the \
19269                         shared `AplicacaoError::ContratoWrongTarget::expected` \
19270                         &'static str axis, so a collapse silently misdirects \
19271                         the diagnostic on which typed shape the WIT world admits",
19272                    );
19273                }
19274            }
19275        }
19276    }
19277
19278    #[test]
19279    fn wit_target_is_variant_predicates_partition_the_arm_set() {
19280        // Fail-before-pass-after pin on the
19281        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
19282        // each of the four variants exactly one of the generated
19283        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
19284        // predicates returns `true` and the other three return
19285        // `false`. Prior to this derive the only production
19286        // arm-discriminator on [`WitTarget`] — the sync-cycle
19287        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
19288        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
19289        // the variant that expressed no compile-time link back to
19290        // the closed-set typed dispatch a future fifth
19291        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
19292        // split of [`WitTarget::PubSub`] into shape-specific peers,
19293        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
19294        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
19295        // to thread through in lockstep or the DFS exclusion would
19296        // silently disagree with the peer diagnostic templates on
19297        // which arms carry sync-versus-async semantics. Peer of the
19298        // sibling [`crate::CaixaKind`] (f5bba80),
19299        // [`PlacementStrategy`] (766ec63),
19300        // [`crate::supervisor::RestartStrategy`],
19301        // [`crate::supervisor::RestartPolicy`], and
19302        // [`crate::upgrade::UpgradeInstruction`] (915a934)
19303        // `IsVariant` derives on the sibling closed-set typed-enum
19304        // discriminator axes — extends the same one-typed-dispatch-
19305        // per-variant discipline onto the last unlifted closed-set
19306        // typed-enum discriminator on the caixa surface (the M3
19307        // mesh-slot per-`:contratos` target-arm axis), closing the
19308        // arm-discriminator convergence trajectory across every
19309        // closed-set typed enum in caixa-core.
19310        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
19311            (
19312                WitTarget::Http { endpoint: "/x" },
19313                [true, false, false, false],
19314            ),
19315            (
19316                WitTarget::PubSub {
19317                    subject: "events.x",
19318                },
19319                [false, true, false, false],
19320            ),
19321            (
19322                WitTarget::Store { slot: "kv/x" },
19323                [false, false, true, false],
19324            ),
19325            (WitTarget::Capability, [false, false, false, true]),
19326        ];
19327        for (variant, expected) in rows {
19328            let observed = [
19329                variant.is_http(),
19330                variant.is_pubsub(),
19331                variant.is_store(),
19332                variant.is_capability(),
19333            ];
19334            assert_eq!(
19335                observed, expected,
19336                "WitTarget::{variant:?} is_* predicates must partition \
19337                 the arm set (http, pubsub, store, capability); got {observed:?}"
19338            );
19339        }
19340    }
19341
19342    #[test]
19343    fn wit_target_is_variant_predicates_are_const_fn() {
19344        // The [`gen_platform::IsVariant`] derive emits `const fn`
19345        // predicates on the peer [`crate::CaixaKind`] +
19346        // [`crate::upgrade::UpgradeInstruction`] +
19347        // [`crate::supervisor::RestartStrategy`] +
19348        // [`crate::supervisor::RestartPolicy`] +
19349        // [`PlacementStrategy`] closed-set typed enums — pin the
19350        // same posture on [`WitTarget`] so a future accidental
19351        // downgrade to non-`const` (an added runtime helper reachable
19352        // only from a non-`const` context, a manual hand-rolled
19353        // `impl` that shadows the derive-generated method) trips at
19354        // caixa-core build time rather than surfacing as a downstream
19355        // `const`-context regression far from the derive declaration.
19356        //
19357        // Unlike the peer unit-variant enums (`CaixaKind` /
19358        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
19359        // whose `const` constructors need no arguments, the three
19360        // payload-carrying [`WitTarget`] arms are const-constructed
19361        // through `&'static str` payloads — the same `'static`
19362        // lifetime the closed-set typed enum's four-arm partition
19363        // pin above already threads through.
19364        //
19365        // The pin lives inside a `const { assert!(..) }` block so the
19366        // compiler enforces both halves (arm predicate is `const`-
19367        // callable AND returns `true` for the matching arm) at
19368        // caixa-core compile time — peer to the sibling
19369        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
19370        // typed enum arm-predicate const-callability axis.
19371        const {
19372            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
19373            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
19374            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
19375            assert!(WitTarget::Capability.is_capability());
19376        }
19377    }
19378
19379    #[test]
19380    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
19381        // Consumer-side pin on the sole production converge site:
19382        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
19383        // edges from the synchronous-subgraph DFS via the lifted
19384        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
19385        // predicate (rebound from the prior raw
19386        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
19387        // variant). Byte-equivalent today (`is_pubsub` is the
19388        // derive-generated `matches!(self, Self::PubSub { .. })` by
19389        // construction, the `#[is_variant(name = "pubsub")]` override
19390        // aliasing the auto-derived `is_pub_sub` back to the sibling
19391        // [`WitContract::is_pubsub`] name); pin the behavior so a
19392        // future accidental drift (a rebind onto a peer arm
19393        // predicate, a manual hand-rolled `impl` that shadows the
19394        // derive-generated method with different semantics, a peer
19395        // arm rename that shifts which variant carries sync-versus-
19396        // async semantics) trips at caixa-core test time rather than
19397        // at some downstream operator's runtime dispatch far from the
19398        // rebind commit.
19399        //
19400        // The fixture constructs a two-Servico Aplicacao with one
19401        // pub-sub edge that would close a sync-cycle if the DFS did
19402        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
19403        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
19404        // edge, which is not a cycle. A regression in the converge
19405        // (a rebind that reads the pub-sub arm as sync) would report
19406        // `AplicacaoError::ContratoCycle`.
19407        let s = AplicacaoSpec {
19408            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
19409            contratos: vec![
19410                // Pub-sub edge: DFS must skip via is_pubsub().
19411                WitContract {
19412                    de: "a".into(),
19413                    para: "b".into(),
19414                    wit: "nats:pub-sub".into(),
19415                    endpoint: None,
19416                    subject: Some("events.x".into()),
19417                    slot: None,
19418                },
19419                // HTTP edge: DFS must include.
19420                WitContract {
19421                    de: "b".into(),
19422                    para: "a".into(),
19423                    wit: "wasi:http/proxy".into(),
19424                    endpoint: Some("/x".into()),
19425                    subject: None,
19426                    slot: None,
19427                },
19428            ],
19429            politicas: MeshPolicy::default(),
19430            placement: Placement {
19431                estrategia: PlacementStrategy::Replicated,
19432                clusters: vec!["rio".into()],
19433                affinity: None,
19434                shard_key: None,
19435            },
19436            entrada: None,
19437        };
19438        s.validate()
19439            .expect("pub-sub edge must be excluded from sync-cycle DFS");
19440    }
19441
19442    #[test]
19443    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
19444        // Consumer-side pin: the same three peer consts thread through
19445        // both the [`WitTarget::label`] template (leading-`:` keyword
19446        // prefix in the duplicate-`:contratos` diagnostic) and the
19447        // [`WitContract::target`] gate's [`AplicacaoError::
19448        // ContratoMissingTarget`] `expected:` scalar (the field the
19449        // author needs to add). Pin both routes at once so a future
19450        // refactor can't accidentally split them onto separate string
19451        // literals — the "one place, everywhere reaches for it"
19452        // invariant the peer const set carries.
19453        let http_label = WitTarget::Http { endpoint: "/x" }.label();
19454        assert!(
19455            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
19456            "label must lead with :{} keyword (got {http_label:?})",
19457            WitTarget::HTTP_FIELD_NAME,
19458        );
19459
19460        let mut s = three_member_spec();
19461        s.contratos.push(WitContract {
19462            de: "cart".into(),
19463            para: "catalog".into(),
19464            wit: "kafka:topic".into(),
19465            endpoint: None,
19466            subject: None,
19467            slot: None,
19468        });
19469        match s.validate().unwrap_err() {
19470            AplicacaoError::ContratoMissingTarget { expected, .. } => {
19471                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
19472            }
19473            other => panic!("expected ContratoMissingTarget, got {other:?}"),
19474        }
19475    }
19476
19477    #[test]
19478    fn duplicate_pubsub_diagnostic_names_offending_subject() {
19479        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
19480        // on the pub-sub target axis: the duplicate-edge diagnostic
19481        // must name the `:subject` payload verbatim (not just the
19482        // `(de, para, wit)` triple). Prior to lifting the label onto
19483        // [`WitTarget::label`] the diagnostic derived the label from
19484        // raw [`WitContract`] `Option<String>` probes — a future
19485        // `WitTarget` variant addition (M4 per-edge WIT registry)
19486        // would silently fall through to the `Capability` "no
19487        // payload" default without a compiler warning. Pinning the
19488        // pub-sub arm's format closes the second of three
19489        // payload-carrying `WitTarget` arms this diagnostic threads
19490        // through.
19491        let mut s = three_member_spec();
19492        let pubsub = WitContract {
19493            de: "payment".into(),
19494            para: "cart".into(),
19495            wit: "nats:pub-sub".into(),
19496            endpoint: None,
19497            subject: Some("events.checkout.paid".into()),
19498            slot: None,
19499        };
19500        s.contratos.push(pubsub.clone());
19501        s.contratos.push(pubsub);
19502        let err = s.validate().unwrap_err();
19503        let msg = format!("{err}");
19504        assert!(
19505            msg.contains(":subject \"events.checkout.paid\""),
19506            "duplicate-pubsub diagnostic must name the offending \
19507             :subject payload (got: {msg:?})"
19508        );
19509    }
19510
19511    #[test]
19512    fn duplicate_store_diagnostic_names_offending_slot() {
19513        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
19514        // key-value target axis: the diagnostic must name the `:slot`
19515        // payload verbatim. Third of three payload-carrying
19516        // `WitTarget` arms this diagnostic threads through, closing
19517        // the per-arm label pin trilogy (`Http` — 6841,
19518        // `PubSub` + `Store` — this test + peer above).
19519        let mut s = three_member_spec();
19520        let store = WitContract {
19521            de: "cart".into(),
19522            para: "payment".into(),
19523            wit: "wasi:keyvalue/store".into(),
19524            endpoint: None,
19525            subject: None,
19526            slot: Some("checkout/$orderId".into()),
19527        };
19528        s.contratos
19529            .retain(|c| !(c.de == "cart" && c.para == "payment"));
19530        s.contratos.push(store.clone());
19531        s.contratos.push(store);
19532        let err = s.validate().unwrap_err();
19533        let msg = format!("{err}");
19534        assert!(
19535            msg.contains(":slot \"checkout/$orderId\""),
19536            "duplicate-store diagnostic must name the offending :slot \
19537             payload (got: {msg:?})"
19538        );
19539    }
19540
19541    #[test]
19542    fn rejects_entrada_path_without_leading_slash() {
19543        let mut s = three_member_spec();
19544        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
19545        let err = s.validate().unwrap_err();
19546        assert!(
19547            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
19548            "got {err:?}"
19549        );
19550    }
19551
19552    #[test]
19553    fn rejects_empty_entrada_path() {
19554        let mut s = three_member_spec();
19555        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
19556        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
19557    }
19558
19559    #[test]
19560    fn rejects_duplicate_entrada_paths() {
19561        let mut s = three_member_spec();
19562        s.entrada.as_mut().unwrap().paths = vec![
19563            "/api/cart".into(),
19564            "/api/products".into(),
19565            "/api/cart".into(),
19566        ];
19567        let err = s.validate().unwrap_err();
19568        assert!(
19569            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
19570            "got {err:?}"
19571        );
19572    }
19573
19574    #[test]
19575    fn rejects_zero_entrada_port() {
19576        let mut s = three_member_spec();
19577        s.entrada.as_mut().unwrap().port = 0;
19578        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19579    }
19580
19581    // ── :entrada :paths value-shape gate ─────────────────────────────
19582    //
19583    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
19584    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
19585    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
19586    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
19587    // time now becomes a caixa-build-time `EntradaPathInvalid` with
19588    // the offending `:paths` entry named verbatim.
19589
19590    #[test]
19591    fn rejects_entrada_path_with_query() {
19592        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
19593        // silently passed validate and the Gateway API webhook
19594        // rejected it at apply time with no source citation.
19595        let mut s = three_member_spec();
19596        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
19597        let err = s.validate().unwrap_err();
19598        assert!(
19599            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19600                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
19601            "got {err:?}"
19602        );
19603    }
19604
19605    #[test]
19606    fn rejects_entrada_path_with_fragment() {
19607        let mut s = three_member_spec();
19608        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
19609        let err = s.validate().unwrap_err();
19610        assert!(
19611            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19612                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
19613            "got {err:?}"
19614        );
19615    }
19616
19617    #[test]
19618    fn rejects_entrada_path_with_space() {
19619        let mut s = three_member_spec();
19620        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
19621        let err = s.validate().unwrap_err();
19622        assert!(
19623            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19624                if path == "/api/my cart" && reason.contains("whitespace")),
19625            "got {err:?}"
19626        );
19627    }
19628
19629    #[test]
19630    fn rejects_entrada_path_with_tab() {
19631        let mut s = three_member_spec();
19632        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
19633        let err = s.validate().unwrap_err();
19634        assert!(
19635            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19636                if path == "/api/\tcart" && reason.contains("whitespace")),
19637            "got {err:?}"
19638        );
19639    }
19640
19641    #[test]
19642    fn rejects_entrada_path_with_control_char() {
19643        // 0x01 (SOH) — a non-whitespace control char surfaces the
19644        // distinct "control character" reason arm, separate from
19645        // the whitespace arm. Pinned so a future refactor that
19646        // collapses the two arms can't accidentally drop the more
19647        // self-locating diagnostic.
19648        let mut s = three_member_spec();
19649        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
19650        let err = s.validate().unwrap_err();
19651        assert!(
19652            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19653                if path == "/api/\x01cart" && reason.contains("control character")),
19654            "got {err:?}"
19655        );
19656    }
19657
19658    #[test]
19659    fn rejects_entrada_path_with_non_ascii() {
19660        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
19661        // unreserved-set rule rejects. The Gateway API webhook
19662        // rejects literal non-ASCII bytes; percent-encoding is the
19663        // only way to author non-ASCII in a path.
19664        let mut s = three_member_spec();
19665        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
19666        let err = s.validate().unwrap_err();
19667        assert!(
19668            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19669                if path == "/api/café" && reason.contains("non-ASCII")),
19670            "got {err:?}"
19671        );
19672    }
19673
19674    #[test]
19675    fn rejects_entrada_path_with_consecutive_slashes() {
19676        let mut s = three_member_spec();
19677        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
19678        let err = s.validate().unwrap_err();
19679        assert!(
19680            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19681                if path == "/api//cart" && reason.contains("consecutive `/`")),
19682            "got {err:?}"
19683        );
19684    }
19685
19686    #[test]
19687    fn rejects_entrada_path_with_dot_segment() {
19688        let mut s = three_member_spec();
19689        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
19690        let err = s.validate().unwrap_err();
19691        assert!(
19692            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19693                if path == "/api/./cart" && reason.contains("`.` segment")),
19694            "got {err:?}"
19695        );
19696    }
19697
19698    #[test]
19699    fn rejects_entrada_path_with_trailing_dot_segment() {
19700        // The bare `/.` and the trailing `/foo/.` are both rejected
19701        // by the Gateway API webhook; pinned separately so a future
19702        // narrowing that catches only the inner form surfaces here.
19703        let mut s = three_member_spec();
19704        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
19705        let err = s.validate().unwrap_err();
19706        assert!(
19707            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19708                if path == "/api/." && reason.contains("`.` segment")),
19709            "got {err:?}"
19710        );
19711    }
19712
19713    #[test]
19714    fn rejects_entrada_path_with_parent_segment() {
19715        let mut s = three_member_spec();
19716        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
19717        let err = s.validate().unwrap_err();
19718        assert!(
19719            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19720                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
19721            "got {err:?}"
19722        );
19723    }
19724
19725    #[test]
19726    fn rejects_entrada_path_with_trailing_parent_segment() {
19727        // Trailing `/..` — symmetric arm of the parent-segment rule,
19728        // pinned separately so a future relaxation that only checks
19729        // the inner form (`/../`) surfaces here.
19730        let mut s = three_member_spec();
19731        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
19732        let err = s.validate().unwrap_err();
19733        assert!(
19734            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19735                if path == "/api/.." && reason.contains("`..` parent-segment")),
19736            "got {err:?}"
19737        );
19738    }
19739
19740    #[test]
19741    fn rejects_entrada_path_too_long() {
19742        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
19743        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
19744        // ASCII-alphanumeric body so only the length rule fires.
19745        let mut s = three_member_spec();
19746        let big = format!("/api/{}", "a".repeat(1020));
19747        assert_eq!(big.len(), 1025);
19748        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
19749        let err = s.validate().unwrap_err();
19750        assert!(
19751            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19752                if path == &big && reason.contains("max length of 1024")),
19753            "got {err:?}"
19754        );
19755    }
19756
19757    #[test]
19758    fn entrada_path_max_length_validates() {
19759        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
19760        // maxLength cap. Boundary pin: drift in the cap surfaces here
19761        // and at `rejects_entrada_path_too_long` simultaneously.
19762        let mut s = three_member_spec();
19763        let big = format!("/api/{}", "a".repeat(1019));
19764        assert_eq!(big.len(), 1024);
19765        s.entrada.as_mut().unwrap().paths = vec![big];
19766        s.validate().unwrap();
19767    }
19768
19769    #[test]
19770    fn entrada_accepts_canonical_paths() {
19771        // Positive-control sweep — every form the Gateway API
19772        // apiserver accepts must round-trip through validate. Covers
19773        // the root catch-all, plain paths, dot-prefixed segments
19774        // (hidden-file-style, distinct from `.` and `..` segments
19775        // which are rejected), digit-bearing segments, the canonical
19776        // route-template `:param` form (`:` is RFC 3986 reserved-set
19777        // valid in paths), trailing-slash form, percent-encoded
19778        // segments, and an interior `..` *substring* (`/foo..bar` is
19779        // not the `..` segment and is allowed).
19780        for path in [
19781            "/",
19782            "/api/cart",
19783            "/healthz",
19784            "/api/.config",
19785            "/v1/products",
19786            "/products/:id",
19787            "/api/cart/",
19788            "/api/caf%C3%A9",
19789            "/foo..bar",
19790            "/...",
19791        ] {
19792            let mut s = three_member_spec();
19793            s.entrada.as_mut().unwrap().paths = vec![path.into()];
19794            s.validate()
19795                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
19796        }
19797    }
19798
19799    #[test]
19800    fn entrada_path_empty_takes_precedence_over_invalid() {
19801        // Ordering pin: `EntradaPathEmpty` is the more self-locating
19802        // diagnostic on `""` and must lead — `validate_entrada_path`
19803        // is only reached after the empty-check fires at the call
19804        // site. (The predicate itself defends against direct
19805        // invocation by returning the same error on `""`.)
19806        let mut s = three_member_spec();
19807        s.entrada.as_mut().unwrap().paths = vec![String::new()];
19808        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
19809    }
19810
19811    #[test]
19812    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
19813        // Ordering pin: a path without a leading `/` surfaces the
19814        // narrower `EntradaPathNotAbsolute` diagnostic first; the
19815        // value-shape gate is only consulted on paths that already
19816        // satisfy the absolute-prefix invariant.
19817        let mut s = three_member_spec();
19818        // `bad path` would fire the whitespace rule under the
19819        // value-shape gate, but missing-leading-`/` is the more
19820        // self-locating diagnostic.
19821        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
19822        let err = s.validate().unwrap_err();
19823        assert!(
19824            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
19825            "got {err:?}"
19826        );
19827    }
19828
19829    #[test]
19830    fn entrada_path_invalid_fires_before_duplicate_check() {
19831        // Ordering pin: a malformed path on the *first* entry of a
19832        // would-be duplicate pair fires the value-shape gate before
19833        // the duplicate gate, mirroring the
19834        // `placement_cluster_invalid_fires_before_duplicate_check`
19835        // (6cbb900) pattern on the peer axis.
19836        let mut s = three_member_spec();
19837        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
19838        let err = s.validate().unwrap_err();
19839        assert!(
19840            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
19841            "got {err:?}"
19842        );
19843    }
19844
19845    #[test]
19846    fn entrada_path_diagnostic_carries_offending_path() {
19847        // Diagnostic-shape pin — the offending path + a non-empty
19848        // reason flow through verbatim so the author can grep their
19849        // caixa.lisp for `:paths` and fix it in one edit. Same shape
19850        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
19851        let mut s = three_member_spec();
19852        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
19853        let err = s.validate().unwrap_err();
19854        match err {
19855            AplicacaoError::EntradaPathInvalid { path, reason } => {
19856                assert_eq!(path, "/api?q=1");
19857                assert!(!reason.is_empty(), "reason field must be non-empty");
19858            }
19859            other => panic!("expected EntradaPathInvalid, got {other:?}"),
19860        }
19861    }
19862
19863    #[test]
19864    fn rejects_entrada_path_with_curly_brace_template_form() {
19865        // Per-axis pin on the shared `is_gateway_api_http_path`
19866        // reserved-byte arm: the canonical "I wrote an OpenAPI
19867        // path-template `{id}` instead of the Gateway API `:id` form"
19868        // footgun the K8s apiserver would otherwise catch at admission
19869        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
19870        // landing site, far from the caixa.lisp. Surfaces as
19871        // `EntradaPathInvalid` carrying the offending path verbatim
19872        // plus the canonical `%7B`/`%7D` percent-encoding remediation
19873        // — the substrate-side `gateway_api_http_path_rejects_every_
19874        // reserved_printable_ascii_byte` predicate-level sweep pins the
19875        // full eleven-byte set; this per-axis pin confirms the
19876        // diagnostic flows through to the `EntradaPathInvalid` variant.
19877        let mut s = three_member_spec();
19878        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
19879        let err = s.validate().unwrap_err();
19880        assert!(
19881            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19882                if path == "/api/cart/{id}"
19883                    && reason.contains("reserved character")
19884                    && reason.contains("'{'")
19885                    && reason.contains("%7B")),
19886            "got {err:?}"
19887        );
19888    }
19889
19890    #[test]
19891    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
19892        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
19893        // template_form` on the sibling `:contratos :endpoint` axis.
19894        // Same shared `is_gateway_api_http_path` reserved-byte arm
19895        // fires through `ContratoEndpointInvalid`, with the offending
19896        // endpoint + `:de` + `:para` + reason flowing through verbatim.
19897        // Pins that the lifted predicate's tightening lands on both
19898        // caller axes simultaneously — one source of truth for the
19899        // Gateway API HTTPPathMatch.value accepted set.
19900        let err = contrato_endpoint_err("/api/cart/{id}");
19901        assert!(
19902            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
19903                if endpoint == "/api/cart/{id}"
19904                    && reason.contains("reserved character")
19905                    && reason.contains("'{'")
19906                    && reason.contains("%7B")),
19907            "got {err:?}"
19908        );
19909    }
19910
19911    // ── :entrada :host value-shape gate ──────────────────────────────
19912    //
19913    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
19914    // the sibling `:host` axis. Every authoring footgun the K8s
19915    // Gateway API v1 apiserver would catch at admission time becomes
19916    // a caixa-build-time `EntradaHostInvalid` with the offending
19917    // `:host` named verbatim. Same diagnostic shape as
19918    // `MembroVersaoInvalid` (9888b13).
19919
19920    #[test]
19921    fn rejects_entrada_host_with_scheme() {
19922        // Fail-before-pass-after pin — pre-gate codebases silently
19923        // accepted `https://…` and the apiserver rejected it at apply
19924        // time with no source citation.
19925        let mut s = three_member_spec();
19926        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
19927        let err = s.validate().unwrap_err();
19928        assert!(
19929            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
19930                if host == "https://checkout.quero.cloud"),
19931            "got {err:?}"
19932        );
19933    }
19934
19935    #[test]
19936    fn rejects_entrada_host_with_port() {
19937        // The `:8080` port suffix is the canonical "I forgot the port
19938        // belongs in `:entrada :port`" footgun. The top-level `:` arm
19939        // (introduced after the per-label loop-only impl silently
19940        // surfaced a deep "label \"cloud:8080\" contains invalid
19941        // character ':'" leak) names the canonical fix verbatim — the
19942        // `:entrada :port` slot.
19943        let mut s = three_member_spec();
19944        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
19945        let err = s.validate().unwrap_err();
19946        assert!(
19947            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19948                if host == "checkout.quero.cloud:8080"
19949                && reason.contains(":entrada :port")),
19950            "got {err:?}"
19951        );
19952    }
19953
19954    #[test]
19955    fn rejects_entrada_host_with_trailing_colon() {
19956        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
19957        // edit) — the per-label loop would land it as a deep
19958        // "label \"com:\" must start and end with an alphanumeric"
19959        // / "contains invalid character ':'" leak. The top-level
19960        // `:` arm pre-empts with the canonical `:port` slot
19961        // diagnostic.
19962        let mut s = three_member_spec();
19963        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
19964        let err = s.validate().unwrap_err();
19965        assert!(
19966            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19967                if host == "checkout.quero.cloud:"
19968                && reason.contains(":entrada :port")),
19969            "got {err:?}"
19970        );
19971    }
19972
19973    #[test]
19974    fn rejects_entrada_host_unbracketed_ipv6_literal() {
19975        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
19976        // literals across the board (peer with `rejects_entrada_host_
19977        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
19978        // Before this top-level `:` arm landed the per-label loop
19979        // surfaced a single-label byte-class diagnostic that named the
19980        // `:` byte but not the IP-literal prohibition. The top-level
19981        // `:` arm names both the `:port` slot and the IP-literal
19982        // prohibition verbatim, so an author whose `:host "2001:..."`
19983        // value lands here gets a self-locating fix either way.
19984        let mut s = three_member_spec();
19985        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
19986        let err = s.validate().unwrap_err();
19987        assert!(
19988            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19989                if host == "2001:db8::1"
19990                && reason.contains("IPv6")),
19991            "got {err:?}"
19992        );
19993    }
19994
19995    #[test]
19996    fn rejects_entrada_host_wildcard_with_port() {
19997        // Wildcard host with port suffix — the `*.` strip and the
19998        // per-label loop on `["foo", "quero", "cloud:8080"]` would
19999        // surface the deep byte-class leak. The top-level `:` arm sits
20000        // upstream of the `*.` strip, so it names the canonical `:port`
20001        // fix verbatim regardless of whether the host is wildcard-led.
20002        let mut s = three_member_spec();
20003        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
20004        let err = s.validate().unwrap_err();
20005        assert!(
20006            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
20007                if host == "*.quero.cloud:8080"
20008                && reason.contains(":entrada :port")),
20009            "got {err:?}"
20010        );
20011    }
20012
20013    #[test]
20014    fn rejects_entrada_host_with_path() {
20015        let mut s = three_member_spec();
20016        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
20017        let err = s.validate().unwrap_err();
20018        assert!(
20019            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
20020                if host == "checkout.quero.cloud/api"),
20021            "got {err:?}"
20022        );
20023    }
20024
20025    #[test]
20026    fn rejects_entrada_host_with_uppercase() {
20027        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
20028        // rejected, not silently lower-cased.
20029        let mut s = three_member_spec();
20030        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
20031        let err = s.validate().unwrap_err();
20032        assert!(
20033            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20034                if reason.contains("uppercase")),
20035            "got {err:?}"
20036        );
20037    }
20038
20039    #[test]
20040    fn rejects_entrada_host_with_underscore() {
20041        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
20042        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
20043        let mut s = three_member_spec();
20044        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
20045        let err = s.validate().unwrap_err();
20046        assert!(
20047            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20048                if reason.contains('_')),
20049            "got {err:?}"
20050        );
20051    }
20052
20053    #[test]
20054    fn rejects_entrada_host_ipv4_literal() {
20055        // Gateway API v1 explicitly forbids IP literals as Hostnames.
20056        let mut s = three_member_spec();
20057        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
20058        let err = s.validate().unwrap_err();
20059        assert!(
20060            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20061                if reason.contains("IPv4")),
20062            "got {err:?}"
20063        );
20064    }
20065
20066    #[test]
20067    fn rejects_entrada_host_with_trailing_dot() {
20068        // The Gateway API regex anchors at end-of-string with no
20069        // trailing `.` allowance — the FQDN root-dot form is rejected.
20070        let mut s = three_member_spec();
20071        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
20072        let err = s.validate().unwrap_err();
20073        assert!(
20074            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
20075                if host == "checkout.quero.cloud."),
20076            "got {err:?}"
20077        );
20078    }
20079
20080    #[test]
20081    fn rejects_entrada_host_with_leading_dot() {
20082        let mut s = three_member_spec();
20083        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
20084        let err = s.validate().unwrap_err();
20085        assert!(
20086            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20087                if reason.contains("empty label")),
20088            "got {err:?}"
20089        );
20090    }
20091
20092    #[test]
20093    fn rejects_entrada_host_with_consecutive_dots() {
20094        let mut s = three_member_spec();
20095        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
20096        let err = s.validate().unwrap_err();
20097        assert!(
20098            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20099                if reason.contains("empty label")),
20100            "got {err:?}"
20101        );
20102    }
20103
20104    #[test]
20105    fn rejects_entrada_host_with_leading_hyphen_label() {
20106        let mut s = three_member_spec();
20107        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
20108        let err = s.validate().unwrap_err();
20109        assert!(
20110            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20111                if reason.contains("alphanumeric")),
20112            "got {err:?}"
20113        );
20114    }
20115
20116    #[test]
20117    fn rejects_entrada_host_with_trailing_hyphen_label() {
20118        let mut s = three_member_spec();
20119        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
20120        let err = s.validate().unwrap_err();
20121        assert!(
20122            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20123                if reason.contains("alphanumeric")),
20124            "got {err:?}"
20125        );
20126    }
20127
20128    #[test]
20129    fn rejects_entrada_host_with_inner_wildcard() {
20130        // Gateway API allows `*` only as the first label (`*.foo`);
20131        // any inner or trailing `*` is rejected.
20132        let mut s = three_member_spec();
20133        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
20134        let err = s.validate().unwrap_err();
20135        assert!(
20136            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20137                if reason.contains("wildcard")),
20138            "got {err:?}"
20139        );
20140    }
20141
20142    #[test]
20143    fn rejects_entrada_host_bare_wildcard() {
20144        // `*.` with no domain is meaningless; Gateway API rejects it.
20145        let mut s = three_member_spec();
20146        s.entrada.as_mut().unwrap().host = "*.".into();
20147        let err = s.validate().unwrap_err();
20148        assert!(
20149            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20150                if reason.contains("wildcard")),
20151            "got {err:?}"
20152        );
20153    }
20154
20155    #[test]
20156    fn rejects_entrada_host_with_whitespace() {
20157        let mut s = three_member_spec();
20158        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
20159        let err = s.validate().unwrap_err();
20160        assert!(
20161            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20162                if reason.contains("whitespace")),
20163            "got {err:?}"
20164        );
20165    }
20166
20167    #[test]
20168    fn rejects_entrada_host_space_names_offending_byte() {
20169        // Embedded space in the `:entrada :host` axis surfaces the
20170        // byte-naming diagnostic through the lifted
20171        // `find_ascii_whitespace_byte` predicate. Peer with the
20172        // sibling `parse_rejects_leading_whitespace` pins on
20173        // `supervisor::duration_codec` (a7ae622) — same "the
20174        // diagnostic carries the offending byte's `0x{b:02x}` shape"
20175        // discipline extended from the shared duration codec to the
20176        // Gateway API v1 Hostname axis.
20177        let mut s = three_member_spec();
20178        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
20179        let err = s.validate().unwrap_err();
20180        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
20181            panic!("expected EntradaHostInvalid, got {err:?}");
20182        };
20183        assert!(
20184            reason.contains("ASCII whitespace byte"),
20185            "expected byte-naming diagnostic, got {reason:?}"
20186        );
20187        assert!(
20188            reason.contains("0x20"),
20189            "expected offending space byte 0x20, got {reason:?}"
20190        );
20191    }
20192
20193    #[test]
20194    fn rejects_entrada_host_tab_names_offending_byte() {
20195        // Embedded tab byte in the `:entrada :host` axis — the
20196        // canonical paste-from-YAML-block-scalar / paste-from-
20197        // indented-doc footgun. Pins that the lifted predicate covers
20198        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
20199        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
20200        // not just the leading-space case the pre-lift `.bytes().any`
20201        // arm's opaque "must not contain whitespace" reason already
20202        // covered. Peer with `parse_rejects_tab_byte` on
20203        // `supervisor::duration_codec` (a7ae622).
20204        let mut s = three_member_spec();
20205        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
20206        let err = s.validate().unwrap_err();
20207        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
20208            panic!("expected EntradaHostInvalid, got {err:?}");
20209        };
20210        assert!(
20211            reason.contains("ASCII whitespace byte"),
20212            "expected byte-naming diagnostic, got {reason:?}"
20213        );
20214        assert!(
20215            reason.contains("0x09"),
20216            "expected offending tab byte 0x09, got {reason:?}"
20217        );
20218    }
20219
20220    #[test]
20221    fn rejects_entrada_host_lf_names_offending_byte() {
20222        // Embedded LF byte in the `:entrada :host` axis — the
20223        // canonical paste-from-shell-heredoc / paste-from-multiline-
20224        // doc footgun the caixa-mesh YAML emitter would silently
20225        // reinterpret at the Gateway API v1 HTTPRoute admission
20226        // layer (an embedded LF byte in a YAML plain scalar either
20227        // truncates the value at the emitter or crashes the parser
20228        // on the k8s-apiserver side). Pins the third representative
20229        // of the full ASCII-whitespace set through the shared
20230        // predicate.
20231        let mut s = three_member_spec();
20232        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
20233        let err = s.validate().unwrap_err();
20234        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
20235            panic!("expected EntradaHostInvalid, got {err:?}");
20236        };
20237        assert!(
20238            reason.contains("ASCII whitespace byte"),
20239            "expected byte-naming diagnostic, got {reason:?}"
20240        );
20241        assert!(
20242            reason.contains("0x0a"),
20243            "expected offending LF byte 0x0a, got {reason:?}"
20244        );
20245    }
20246
20247    #[test]
20248    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
20249        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
20250        // axis — the canonical paste-from-typography /
20251        // paste-from-word-processor footgun. Before the non-ASCII
20252        // Unicode `White_Space` scan lifted through the shared
20253        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
20254        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
20255        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
20256        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
20257        // with the far-from-source `label "…" must start and end
20258        // with an alphanumeric` diagnostic — burying the
20259        // paste-from-typography origin under a label-shape leak.
20260        // Peer with the sibling non-ASCII-whitespace pins at
20261        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
20262        // — 1b75b38), `limits::parse_duration`,
20263        // `limits::parse_millicores`, and the shared duration codec
20264        // — same "the diagnostic carries the offending Unicode
20265        // codepoint's `U+XXXX` shape" discipline extended from every
20266        // typed-magnitude codec to the Gateway API v1 Hostname axis.
20267        let mut s = three_member_spec();
20268        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
20269        let err = s.validate().unwrap_err();
20270        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
20271            panic!("expected EntradaHostInvalid, got {err:?}");
20272        };
20273        assert!(
20274            reason.contains("non-ASCII Unicode whitespace character"),
20275            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
20276        );
20277        assert!(
20278            reason.contains("U+00A0"),
20279            "expected offending NBSP codepoint U+00A0, got {reason:?}"
20280        );
20281    }
20282
20283    #[test]
20284    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
20285        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
20286        // `:entrada :host` axis — the canonical paste-from-web-doc /
20287        // paste-from-published-HTML footgun. `char::is_whitespace`
20288        // returns true for `U+2028` per the Unicode `White_Space`
20289        // property, so `str::trim` at any downstream site would
20290        // silently strip it — same drift class as NBSP but on a
20291        // different codepoint region. Pins the second representative
20292        // (non-Latin-1 `char::is_whitespace` member) through the
20293        // shared predicate. Peer with
20294        // `parse_byte_size_rejects_internal_line_separator` on
20295        // `limits::parse_byte_size` (1b75b38).
20296        let mut s = three_member_spec();
20297        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
20298        let err = s.validate().unwrap_err();
20299        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
20300            panic!("expected EntradaHostInvalid, got {err:?}");
20301        };
20302        assert!(
20303            reason.contains("non-ASCII Unicode whitespace character"),
20304            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
20305        );
20306        assert!(
20307            reason.contains("U+2028"),
20308            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
20309        );
20310    }
20311
20312    #[test]
20313    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
20314        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
20315        // labels in the `:entrada :host` axis — the canonical
20316        // paste-from-CJK-typography footgun (CJK IMEs default to
20317        // full-width whitespace when the space bar is pressed in
20318        // Japanese / Chinese input modes). Pins the third
20319        // representative of the non-ASCII Unicode `White_Space` set
20320        // through the shared predicate: the CJK block, distinct from
20321        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
20322        // SEPARATOR `U+2028` — covering the same axis breadth the
20323        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
20324        // (1b75b38) pins on `limits::parse_byte_size`.
20325        let mut s = three_member_spec();
20326        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
20327        let err = s.validate().unwrap_err();
20328        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
20329            panic!("expected EntradaHostInvalid, got {err:?}");
20330        };
20331        assert!(
20332            reason.contains("non-ASCII Unicode whitespace character"),
20333            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
20334        );
20335        assert!(
20336            reason.contains("U+3000"),
20337            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
20338        );
20339    }
20340
20341    #[test]
20342    fn rejects_entrada_host_too_long() {
20343        // Total length cap = 253; build a 254-byte host out of two
20344        // 63-byte labels + one 62-byte label + dots.
20345        let mut s = three_member_spec();
20346        let big = format!(
20347            "{}.{}.{}.{}",
20348            "a".repeat(63),
20349            "b".repeat(63),
20350            "c".repeat(63),
20351            "d".repeat(254 - 63 * 3 - 3)
20352        );
20353        assert_eq!(big.len(), 254);
20354        s.entrada.as_mut().unwrap().host = big;
20355        let err = s.validate().unwrap_err();
20356        assert!(
20357            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20358                if reason.contains("max length of 253")),
20359            "got {err:?}"
20360        );
20361    }
20362
20363    #[test]
20364    fn rejects_entrada_host_label_too_long() {
20365        let mut s = three_member_spec();
20366        // 64-byte label — one over the per-label cap.
20367        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
20368        let err = s.validate().unwrap_err();
20369        assert!(
20370            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
20371                if reason.contains("label max length of 63")),
20372            "got {err:?}"
20373        );
20374    }
20375
20376    #[test]
20377    fn entrada_host_diagnostic_carries_offending_host() {
20378        // Diagnostic-shape pin — the offending host + a non-empty
20379        // reason flow through verbatim so the author can grep their
20380        // caixa.lisp for `:host "<host>"` and fix it in one edit.
20381        let mut s = three_member_spec();
20382        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
20383        let err = s.validate().unwrap_err();
20384        match err {
20385            AplicacaoError::EntradaHostInvalid { host, reason } => {
20386                assert_eq!(host, "checkout.quero.cloud:8080");
20387                assert!(!reason.is_empty(), "reason field must be non-empty");
20388            }
20389            other => panic!("expected EntradaHostInvalid, got {other:?}"),
20390        }
20391    }
20392
20393    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
20394    // substrate primitive that folds the fourteen
20395    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
20396    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
20397    // one dispatch — peer with the sixteen equivalence pins the
20398    // [`crate::LayoutError`] `_violation` constructor family carries in
20399    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
20400    // fixture host + reason are fixed `&'static str`s so both fields of
20401    // both constructed variants pin verbatim: the `host` axis is pinned
20402    // through the shared `host.to_string()` wrap (the ctor's uniform
20403    // one-slot construction) and the `reason` axis is pinned through
20404    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
20405    // routing). Any future regression on the lift (an extra field
20406    // introduced without updating the ctor, a diverging string
20407    // conversion at either arm) surfaces at this pin's diagnostic
20408    // rather than at a per-wire-up struct-literal reintroduction.
20409    #[test]
20410    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
20411        let host = "checkout.quero.cloud:8080";
20412        let reason = "sample reason text";
20413        assert_eq!(
20414            AplicacaoError::entrada_host_invalid(host, reason),
20415            AplicacaoError::EntradaHostInvalid {
20416                host: host.to_string(),
20417                reason: reason.to_string(),
20418            },
20419            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
20420        );
20421    }
20422
20423    // Routing pin — the ctor's `host: &str` argument threads through
20424    // `.to_string()` verbatim on the `host` field, so the constructed
20425    // variant carries the offending host bytes without any wrapper-
20426    // side transformation (no `.to_ascii_lowercase()` normalization,
20427    // no `.trim()` strip, no truncation) — the same "diagnostic carries
20428    // the offending value verbatim so the author can grep their
20429    // caixa.lisp" discipline every peer typed-slot ctor at this
20430    // altitude carries.
20431    #[test]
20432    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
20433        // Uppercase + trailing whitespace + port suffix — three
20434        // wrapper-side transformations the ctor must *not* apply.
20435        let host = " Checkout.quero.CLOUD:8080 ";
20436        let err = AplicacaoError::entrada_host_invalid(host, "sample");
20437        match err {
20438            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
20439                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
20440            }
20441            other => panic!("expected EntradaHostInvalid, got {other:?}"),
20442        }
20443    }
20444
20445    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
20446    // `&str` literals and `format!(…)` outputs identically and both
20447    // route through `Into::into` verbatim onto the `reason` field.
20448    // Pins both codepaths against the same host to prove the two
20449    // shapes the fourteen wire-up sites use at their per-arm diagnostic
20450    // (ten `&str` literals — some with `.to_string()` at the caller,
20451    // some without — plus four `format!(…)` outputs) each produce
20452    // byte-equal `reason` fields against the same offending host.
20453    #[test]
20454    fn entrada_host_invalid_ctor_routes_reason_through_into() {
20455        let host = "checkout.quero.cloud";
20456        // `&str` literal — the ctor's `impl Into<String>` accepts it
20457        // without a caller-side `.to_string()`.
20458        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
20459        // Owned `String` from `format!` — the peer `format!(…)`-shaped
20460        // wire-up arm.
20461        let from_format =
20462            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
20463        // `String` from `.to_string()` on a literal — the peer
20464        // `"literal".to_string()`-shaped wire-up arm the pre-lift
20465        // sites carried.
20466        let from_to_string =
20467            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
20468        match (&from_literal, &from_format, &from_to_string) {
20469            (
20470                AplicacaoError::EntradaHostInvalid {
20471                    reason: r_lit,
20472                    host: h_lit,
20473                },
20474                AplicacaoError::EntradaHostInvalid {
20475                    reason: r_fmt,
20476                    host: h_fmt,
20477                },
20478                AplicacaoError::EntradaHostInvalid {
20479                    reason: r_ts,
20480                    host: h_ts,
20481                },
20482            ) => {
20483                assert_eq!(r_lit, "literal reason text");
20484                assert_eq!(r_fmt, "literal reason text");
20485                assert_eq!(r_ts, "literal reason text");
20486                assert_eq!(h_lit, host);
20487                assert_eq!(h_fmt, host);
20488                assert_eq!(h_ts, host);
20489            }
20490            _ => panic!("expected three EntradaHostInvalid variants"),
20491        }
20492        // Cross-arm equivalence — the three shapes must produce
20493        // byte-equal `AplicacaoError` values, so the fourteen wire-up
20494        // sites' mixed per-arm shapes fold onto one canonical form.
20495        assert_eq!(from_literal, from_format);
20496        assert_eq!(from_literal, from_to_string);
20497    }
20498
20499    // Equivalence pins for the six sibling
20500    // [`aplicacao_field_reason_ctors!`]-generated constructors that
20501    // fold the peer `{ <field>: String, reason: String }` variants
20502    // onto the same substrate-primitive family
20503    // `entrada_host_invalid` (17dd504) already carries pins for.
20504    // Each ctor's fixture pair (a fixed `&'static str` value and a
20505    // fixed `&'static str` reason) pins both fields verbatim so any
20506    // future regression on the macro (an extra field introduced
20507    // without updating the macro, a diverging string conversion at
20508    // either arm, a field-name typo on one variant that dropped it
20509    // off the shared shape) surfaces at the affected variant's pin
20510    // rather than at a per-wire-up struct-literal reintroduction. Peer
20511    // discipline of the sixteen `LayoutError` _violation ctor pins in
20512    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
20513    // and the paired
20514    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
20515    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
20516    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
20517    // (8580068) equivalence pins on the sibling `AplicacaoError`
20518    // ctor macros.
20519    #[test]
20520    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
20521        let caixa = "cart-svc";
20522        let reason = "sample reason text";
20523        assert_eq!(
20524            AplicacaoError::membro_caixa_invalid(caixa, reason),
20525            AplicacaoError::MembroCaixaInvalid {
20526                caixa: caixa.to_string(),
20527                reason: reason.to_string(),
20528            },
20529        );
20530    }
20531
20532    #[test]
20533    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
20534        let para = "checkout";
20535        let reason = "sample reason text";
20536        assert_eq!(
20537            AplicacaoError::entrada_para_invalid(para, reason),
20538            AplicacaoError::EntradaParaInvalid {
20539                para: para.to_string(),
20540                reason: reason.to_string(),
20541            },
20542        );
20543    }
20544
20545    #[test]
20546    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
20547        let path = "/api/cart";
20548        let reason = "sample reason text";
20549        assert_eq!(
20550            AplicacaoError::entrada_path_invalid(path, reason),
20551            AplicacaoError::EntradaPathInvalid {
20552                path: path.to_string(),
20553                reason: reason.to_string(),
20554            },
20555        );
20556    }
20557
20558    #[test]
20559    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
20560        let cluster = "rio";
20561        let reason = "sample reason text";
20562        assert_eq!(
20563            AplicacaoError::placement_cluster_invalid(cluster, reason),
20564            AplicacaoError::PlacementClusterInvalid {
20565                cluster: cluster.to_string(),
20566                reason: reason.to_string(),
20567            },
20568        );
20569    }
20570
20571    #[test]
20572    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
20573        let affinity = "data-locality";
20574        let reason = "sample reason text";
20575        assert_eq!(
20576            AplicacaoError::placement_affinity_invalid(affinity, reason),
20577            AplicacaoError::PlacementAffinityInvalid {
20578                affinity: affinity.to_string(),
20579                reason: reason.to_string(),
20580            },
20581        );
20582    }
20583
20584    #[test]
20585    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
20586        let shard_key = "tenantId";
20587        let reason = "sample reason text";
20588        assert_eq!(
20589            AplicacaoError::shard_key_invalid(shard_key, reason),
20590            AplicacaoError::ShardKeyInvalid {
20591                shard_key: shard_key.to_string(),
20592                reason: reason.to_string(),
20593            },
20594        );
20595    }
20596
20597    // Pin the three-slot per-`:contratos <slot>` sibling of the
20598    // two-slot `aplicacao_field_reason_ctors!` family — the sole
20599    // per-axis ctor carrying the extra `slot: &'static str` axis-tag
20600    // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
20601    // canonical author-side slot tags through the ctor and asserts
20602    // byte-equality against the pre-lift struct-literal shape so no
20603    // per-arm wrapper transformation drifts in against the sole
20604    // in-crate wire-up.
20605    #[test]
20606    fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
20607        let caixa = "cart-svc";
20608        let reason = "sample reason text";
20609        for slot in [
20610            crate::render::CONTRATO_AUTHOR_KEY_DE,
20611            crate::render::CONTRATO_AUTHOR_KEY_PARA,
20612        ] {
20613            assert_eq!(
20614                AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
20615                AplicacaoError::ContratoCaixaInvalid {
20616                    slot,
20617                    caixa: caixa.to_string(),
20618                    reason: reason.to_string(),
20619                },
20620            );
20621        }
20622    }
20623
20624    // The `reason: impl Into<String>` bound accepts both a `&str`
20625    // literal and a `format!(…)` owned-`String` output verbatim,
20626    // matching the peer `aplicacao_field_reason_ctors!` family's
20627    // reason-axis invariance so the sole in-crate wire-up's
20628    // `require_valid_dns_1123_label`-delivered owned-`String` return
20629    // and any future `&str` literal caller land on the same variant.
20630    #[test]
20631    fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
20632        let via_literal = "literal reason text";
20633        let via_format = format!("{} reason text", "literal");
20634        for slot in [
20635            crate::render::CONTRATO_AUTHOR_KEY_DE,
20636            crate::render::CONTRATO_AUTHOR_KEY_PARA,
20637        ] {
20638            assert_eq!(
20639                AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
20640                AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
20641            );
20642        }
20643    }
20644
20645    // Pin the paired one-slot empty-arm sibling of the three-slot
20646    // `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
20647    // closure-form empty-arm on the shared
20648    // [`crate::render::require_valid_dns_1123_label`] two-closure
20649    // cascade at [`validate_contrato_caixa`], carrying the same
20650    // `slot: &'static str` axis-tag that distinguishes the two-arm
20651    // `:de` / `:para` cascade. Sweeps both canonical author-side slot
20652    // tags through the ctor and asserts byte-equality against the
20653    // pre-lift struct-literal shape so no per-arm wrapper transformation
20654    // drifts in against the sole in-crate wire-up. Peer of the sibling
20655    // [`crate::behavior::BehaviorError::empty_path`] one-slot
20656    // `{ slot: &'static str }` equivalence pin on the paired
20657    // `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
20658    // ([`crate::render::require_sandboxed_lisp_path`]) — extended here
20659    // onto the sibling `AplicacaoError` envelope's two-arm
20660    // DNS-1123-label cascade so both empty-arm axes carry a
20661    // substrate-primitive equivalence pin rather than the pre-lift
20662    // hand-open struct-literal.
20663    #[test]
20664    fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
20665        for slot in [
20666            crate::render::CONTRATO_AUTHOR_KEY_DE,
20667            crate::render::CONTRATO_AUTHOR_KEY_PARA,
20668        ] {
20669            assert_eq!(
20670                AplicacaoError::contrato_caixa_empty(slot),
20671                AplicacaoError::ContratoCaixaEmpty { slot },
20672                "generated contrato_caixa_empty ctor must produce \
20673                 byte-equal AplicacaoError to the open-coded \
20674                 struct-literal wrap on the same &'static str fixture \
20675                 (slot = {slot:?})",
20676            );
20677        }
20678    }
20679
20680    // Cross-axis pin: sweep the constructor's single input axis (`slot:
20681    // &'static str`) through every canonical
20682    // [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
20683    // `&'static str` value (`":phantom"`), so any wrapper-side lowercase
20684    // / trim / truncate / re-order / fixed-slot substitution on the
20685    // one-field construction surfaces here rather than at a downstream
20686    // diagnostic-shape mismatch. The non-canonical arm proves the
20687    // constructor does not silently clamp `slot` to the `:de` /
20688    // `:para` roster (a future third `:contratos <slot>` axis lands on
20689    // this ctor without a per-arm rewrite), matching the discipline the
20690    // sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
20691    // establishes at
20692    // `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
20693    // (18114) on the paired three-slot invalid-arm envelope.
20694    #[test]
20695    fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
20696        for slot in [
20697            crate::render::CONTRATO_AUTHOR_KEY_DE,
20698            crate::render::CONTRATO_AUTHOR_KEY_PARA,
20699            ":phantom",
20700        ] {
20701            assert_eq!(
20702                AplicacaoError::contrato_caixa_empty(slot),
20703                AplicacaoError::ContratoCaixaEmpty { slot },
20704            );
20705        }
20706    }
20707
20708    // End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
20709    // `:contratos :de` value must surface a diagnostic byte-equal to
20710    // the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
20711    // output on the same slot fixture. Proves the sole in-crate
20712    // closure-form wire-up inside [`validate_contrato_caixa`]'s
20713    // [`crate::render::require_valid_dns_1123_label`] empty-arm routes
20714    // through the ctor rather than the pre-lift open-coded
20715    // struct-literal block, matching the sibling per-arm
20716    // `end_to_end_wire_up_routes_through_ctor` discipline the peer
20717    // per-envelope ctor pins the recent
20718    // [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
20719    // [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
20720    // [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
20721    // and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
20722    // cross-axis Policy* variants carry. Complements the two axis-tag
20723    // arms already pinned above the `:contratos` value-shape gate
20724    // block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
20725    // which anchor via the shape; this pin additionally verifies the
20726    // ctor is the exclusive construction path.
20727    #[test]
20728    fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
20729        // Empty `:de` — the sole in-crate wire-up hits the empty-arm
20730        // closure at the first `:contratos` value-shape gate, threading
20731        // the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
20732        let mut s_de = three_member_spec();
20733        s_de.contratos.push(contract_http("", "catalog", "/x"));
20734        assert_eq!(
20735            s_de.validate().unwrap_err(),
20736            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
20737        );
20738        // Symmetric arm: an empty `:para` on a valid `:de` fires the
20739        // same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
20740        let mut s_para = three_member_spec();
20741        s_para.contratos.push(contract_http("cart", "", "/x"));
20742        assert_eq!(
20743            s_para.validate().unwrap_err(),
20744            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
20745        );
20746    }
20747
20748    // Cross-family invariance pin — the six sibling ctors and
20749    // `entrada_host_invalid` all route `reason: impl Into<String>` +
20750    // `<field>: &str` verbatim onto their respective typed variants
20751    // through the shared [`aplicacao_field_reason_ctors!`] macro.
20752    // Sweeps a fixture pair (`&str` literal, `format!` output) against
20753    // every ctor to pin that no per-arm wrapper transformation drifted
20754    // in against the uniform macro-generated body.
20755    #[test]
20756    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
20757        let via_literal = "literal reason text";
20758        let via_format = format!("{} reason text", "literal");
20759        assert_eq!(
20760            AplicacaoError::membro_caixa_invalid("m", via_literal),
20761            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
20762        );
20763        assert_eq!(
20764            AplicacaoError::entrada_para_invalid("p", via_literal),
20765            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
20766        );
20767        assert_eq!(
20768            AplicacaoError::entrada_path_invalid("/a", via_literal),
20769            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
20770        );
20771        assert_eq!(
20772            AplicacaoError::placement_cluster_invalid("c", via_literal),
20773            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
20774        );
20775        assert_eq!(
20776            AplicacaoError::placement_affinity_invalid("a", via_literal),
20777            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
20778        );
20779        assert_eq!(
20780            AplicacaoError::shard_key_invalid("k", via_literal),
20781            AplicacaoError::shard_key_invalid("k", via_format.clone()),
20782        );
20783        assert_eq!(
20784            AplicacaoError::entrada_host_invalid("h", via_literal),
20785            AplicacaoError::entrada_host_invalid("h", via_format),
20786        );
20787    }
20788
20789    #[test]
20790    fn entrada_host_empty_takes_precedence_over_invalid() {
20791        // Ordering pin: `EmptyEntradaHost` is the more self-locating
20792        // diagnostic on `""` and must lead — `validate_entrada_host`
20793        // is only reached after the empty-check fires at the call
20794        // site. (The predicate itself defends against direct
20795        // invocation by returning the same error on `""`.)
20796        let mut s = three_member_spec();
20797        s.entrada.as_mut().unwrap().host = String::new();
20798        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
20799    }
20800
20801    #[test]
20802    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
20803        // Ordering pin: a missing :para member is the more
20804        // self-locating diagnostic and fires before the host gate.
20805        let mut s = three_member_spec();
20806        let e = s.entrada.as_mut().unwrap();
20807        e.para = "ghost".into();
20808        e.host = "BAD HOST".into();
20809        let err = s.validate().unwrap_err();
20810        assert!(
20811            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
20812            "got {err:?}"
20813        );
20814    }
20815
20816    #[test]
20817    fn entrada_host_invalid_fires_before_port_zero() {
20818        // Ordering pin: the host gate fires before the port gate so
20819        // a malformed host is named even when the port is also wrong.
20820        let mut s = three_member_spec();
20821        let e = s.entrada.as_mut().unwrap();
20822        e.host = "Checkout.quero.cloud".into();
20823        e.port = 0;
20824        let err = s.validate().unwrap_err();
20825        assert!(
20826            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
20827                if host == "Checkout.quero.cloud"),
20828            "got {err:?}"
20829        );
20830    }
20831
20832    #[test]
20833    fn entrada_accepts_canonical_hosts() {
20834        // Positive-control sweep — every form the Gateway API
20835        // apiserver accepts must round-trip through validate. Covers
20836        // a plain DNS subdomain, a leading wildcard, a single-label
20837        // host (cluster-internal), a max-length-edge label, a
20838        // hyphen-bearing label, and a Punycode IDN label.
20839        for host in [
20840            "checkout.quero.cloud",
20841            "*.quero.cloud",
20842            "checkout",
20843            // 63-byte label — exactly the per-label cap.
20844            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
20845            "foo-bar.quero.cloud",
20846            // Punycode IDN — valid because the author pre-encoded.
20847            "xn--bcher-kva.example.com",
20848        ] {
20849            let mut s = three_member_spec();
20850            s.entrada.as_mut().unwrap().host = host.into();
20851            s.validate()
20852                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
20853        }
20854    }
20855
20856    #[test]
20857    fn entrada_host_max_length_validates() {
20858        // 253-byte host is the cap exactly — must validate. Build a
20859        // 253-byte host out of three 63-byte labels + one 61-byte
20860        // label + 3 dots = 252 bytes, then pad one byte to 253.
20861        let mut s = three_member_spec();
20862        let host = format!(
20863            "{}.{}.{}.{}",
20864            "a".repeat(63),
20865            "b".repeat(63),
20866            "c".repeat(63),
20867            "d".repeat(253 - 63 * 3 - 3)
20868        );
20869        assert_eq!(host.len(), 253);
20870        s.entrada.as_mut().unwrap().host = host;
20871        s.validate().unwrap();
20872    }
20873
20874    #[test]
20875    fn entrada_host_total_length_cap_threads_lifted_render_const() {
20876        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
20877        // total-length gate now reads the K8s Gateway API v1 Hostname
20878        // `maxLength: 253` cap from the lifted
20879        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
20880        // of truth — the same constant every future Gateway-API-Hostname
20881        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
20882        // materializer's per-host validator, the future per-`Certificate`
20883        // SAN emitter for cert-manager, the multi-`:entrada`
20884        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
20885        // from. Before the lift, the aplicacao-side reader consumed a
20886        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
20887        // 253-byte value as the peer render-side canonical bounds
20888        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
20889        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
20890        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
20891        // module boundary — a future 253-byte drift on either side would
20892        // silently split into two axes' worth of admission-schema mismatch
20893        // without a build-time signal. Pin the cap through a fresh 254-
20894        // byte host that hits the total-length arm, then read the reason
20895        // for the exact byte count the shared constant carries: any future
20896        // regression on the lift (a private alias reintroduced, a hard-
20897        // coded literal at the arm, a mismatch between the aplicacao-side
20898        // and render-side canonicals) surfaces as this pin's diagnostic
20899        // failing to match, not as a per-cluster admission rejection far
20900        // from the caixa.lisp source line.
20901        let mut s = three_member_spec();
20902        let over_cap = format!(
20903            "{}.{}.{}.{}",
20904            "a".repeat(63),
20905            "b".repeat(63),
20906            "c".repeat(63),
20907            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
20908        );
20909        assert_eq!(
20910            over_cap.len(),
20911            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
20912        );
20913        s.entrada.as_mut().unwrap().host = over_cap;
20914        let err = s.validate().unwrap_err();
20915        match err {
20916            AplicacaoError::EntradaHostInvalid { reason, .. } => {
20917                let needle = format!(
20918                    "max length of {} bytes",
20919                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
20920                );
20921                assert!(
20922                    reason.contains(&needle),
20923                    "diagnostic must name the lifted \
20924                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
20925                );
20926            }
20927            other => panic!("expected EntradaHostInvalid, got {other:?}"),
20928        }
20929    }
20930
20931    #[test]
20932    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
20933        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
20934        // on the per-label-cap axis. Before the lift, the aplicacao-side
20935        // per-label arm consumed a private const alias
20936        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
20937        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
20938        // split from it at the module boundary — every `.`-separated
20939        // label in a Gateway API v1 Hostname is a DNS-1123 label under
20940        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
20941        // so the private alias's 63 and the canonical const's 63 were
20942        // pinning the same underlying rule twice. Pin the cap through a
20943        // 64-byte label that hits the per-label arm, then read the reason
20944        // for the exact byte count the shared constant carries: any
20945        // future drift on either side (a private alias reintroduced, a
20946        // hard-coded literal at the arm, a mismatch between the two
20947        // 63-byte pins) surfaces at this pin's diagnostic rather than at
20948        // a per-cluster admission rejection whose "field is invalid"
20949        // opacity misframes the root cause.
20950        let mut s = three_member_spec();
20951        let over_cap_label = format!(
20952            "{}.quero.cloud",
20953            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
20954        );
20955        s.entrada.as_mut().unwrap().host = over_cap_label;
20956        let err = s.validate().unwrap_err();
20957        match err {
20958            AplicacaoError::EntradaHostInvalid { reason, .. } => {
20959                let needle = format!(
20960                    "label max length of {} bytes",
20961                    crate::render::DNS_1123_LABEL_MAX_LEN,
20962                );
20963                assert!(
20964                    reason.contains(&needle),
20965                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
20966                     cap verbatim on the per-label arm, got: {reason:?}",
20967                );
20968            }
20969            other => panic!("expected EntradaHostInvalid, got {other:?}"),
20970        }
20971    }
20972
20973    #[test]
20974    fn entrada_with_empty_paths_validates() {
20975        // Empty `:paths` is the documented "match every path" form;
20976        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
20977        let mut s = three_member_spec();
20978        s.entrada.as_mut().unwrap().paths = vec![];
20979        s.validate().unwrap();
20980    }
20981
20982    #[test]
20983    fn entrada_root_path_validates() {
20984        // The author-supplied bare-root `:entrada :paths` entry is the
20985        // same byte-shape the peer emit-side catch-all constant
20986        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
20987        // the author's `:paths` list is empty — sweeping the test-side
20988        // probe literal onto the lifted const closes the two-axis pin
20989        // (author-side admit + emit-side canonical fallback) around
20990        // one `&'static str`, so a future rebrand of the catch-all
20991        // reaches both consumers by construction. Peer to
20992        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
20993        // on the canonical-literal pin surface.
20994        let mut s = three_member_spec();
20995        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
20996        s.validate().unwrap();
20997    }
20998
20999    #[test]
21000    fn placement_strategy_variants_round_trip() {
21001        for s in [
21002            PlacementStrategy::SingleNode,
21003            PlacementStrategy::Replicated,
21004            PlacementStrategy::Sharded,
21005        ] {
21006            let p = Placement {
21007                estrategia: s,
21008                clusters: vec!["rio".into()],
21009                affinity: None,
21010                // Route the paired `:shard-key` fixture-builder through the
21011                // typed cross-slot invariant predicate
21012                // [`PlacementStrategy::requires_shard_key`] rather than the
21013                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
21014                // arm-identity predicate — the two answer the same
21015                // question under today's closed accept-set but a future
21016                // arm addition that consumed `:shard-key` under a
21017                // non-`Sharded` name would silently mis-attach the
21018                // fixture's `:shard-key` if the builder read through the
21019                // arm-identity predicate. The cross-slot-invariant
21020                // predicate migrates through one caixa-core edit on any
21021                // future arm addition; the fixture keeps producing a
21022                // `validate()`-passing round-trip by construction.
21023                shard_key: if s.requires_shard_key() {
21024                    Some("$key".into())
21025                } else {
21026                    None
21027                },
21028            };
21029            let json = serde_json::to_string(&p).unwrap();
21030            let back: Placement = serde_json::from_str(&json).unwrap();
21031            assert_eq!(back, p);
21032        }
21033    }
21034
21035    #[test]
21036    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
21037        // The fail-before-pass-after pin: pre-lift there was no
21038        // single-source binding between the [`PlacementStrategy`]
21039        // variant name the `Serialize` derive emits and the byte-
21040        // string every downstream cluster-side dispatcher (the
21041        // `lareira-fleet-programs` aggregator's per-entry strategy
21042        // branch, the future `app-operator` reconciler, the M3
21043        // Adaptive compression pass's per-strategy weighting) probes
21044        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
21045        // future `#[serde(rename_all = "kebab-case")]` attribute on
21046        // the enum — or a variant rename in the source — would
21047        // silently rebrand the emitted scalar under one spelling
21048        // while every downstream dispatcher still probed the other,
21049        // with the failure surfacing at the aggregator's dispatch
21050        // step or the operator's reconcile posture (workloads coming
21051        // up under the `default()` `Replicated` arm rather than the
21052        // typed slot's declared strategy) far from the source
21053        // rebrand commit and with no field naming the drift. Pinning
21054        // the two paths (the `Serialize` derive's serialized string
21055        // AND the [`PlacementStrategy::as_str`] helper) to the same
21056        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
21057        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
21058        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
21059        // makes any future drift on either endpoint fail here at
21060        // caixa-core build time.
21061        for (variant, expected) in [
21062            (
21063                PlacementStrategy::SingleNode,
21064                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21065            ),
21066            (
21067                PlacementStrategy::Replicated,
21068                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21069            ),
21070            (
21071                PlacementStrategy::Sharded,
21072                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21073            ),
21074        ] {
21075            let json = serde_json::to_string(&variant).unwrap();
21076            assert_eq!(
21077                json,
21078                format!("\"{expected}\""),
21079                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
21080            );
21081            assert_eq!(
21082                variant.as_str(),
21083                expected,
21084                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
21085                 M3_PLACEMENT_ESTRATEGIA_* constant"
21086            );
21087        }
21088    }
21089
21090    #[test]
21091    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
21092        // Cross-arm drift-detection pin on the M3
21093        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
21094        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
21095        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
21096        // scalar-value pentad: a future collapse of two canonical
21097        // variant byte-strings onto the same value (an accidental
21098        // copy-paste flip of
21099        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
21100        // read `"SingleNode"`, a per-arm rebrand that lands one const
21101        // without touching its paired peer) would silently reroute
21102        // every downstream operator's per-strategy dispatch onto the
21103        // sibling arm's reconcile branch and pass every
21104        // propagation-probe test that expected only the stale arm's
21105        // value — a `Replicated`-declared Aplicacao would come up
21106        // under the `SingleNode` primary-and-standby reconcile
21107        // posture, so every-cluster active-active workload would
21108        // silently collapse onto one-cluster-runs-at-a-time takeover
21109        // semantics against its declared strategy, with no field
21110        // naming the strategy-value drift root cause. Peer of the
21111        // sibling
21112        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
21113        // (09ffb2d) /
21114        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
21115        // (ccdf955) /
21116        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
21117        // (d739850) distinctness pins on the sibling OTP-shape /
21118        // caixa-kind closed-set typed-enum discriminator axes — the
21119        // fourth (and structurally the M3 mesh-primitive-defining)
21120        // closed-set typed-enum axis to converge on the same
21121        // "pairwise-distinct-by-construction" discipline.
21122        //
21123        // Fail-before-pass-after locally verified by mutating
21124        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
21125        // also read `"SingleNode"` — this pin fires as expected;
21126        // restoring passes.
21127        let all = [
21128            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21129            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21130            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21131        ];
21132        for (i, a) in all.iter().enumerate() {
21133            for (j, b) in all.iter().enumerate() {
21134                if i != j {
21135                    assert_ne!(
21136                        a, b,
21137                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
21138                         distinct — got duplicate {a:?} at indices {i} and {j}",
21139                    );
21140                }
21141            }
21142        }
21143    }
21144
21145    #[test]
21146    fn placement_strategy_display_routes_through_as_str_helper() {
21147        // The fail-before-pass-after pin: pre-lift the sibling
21148        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
21149        // / [`crate::supervisor::RestartPolicy`] both carried a stable
21150        // [`std::fmt::Display`] surface via their
21151        // `#[discriminant(also_display)]` gen-platform derive, but
21152        // [`PlacementStrategy`] did not — every consumer reaching for
21153        // a strategy byte-string past the wire format had to pick
21154        // between three paths ([`PlacementStrategy::as_str`], the
21155        // `Serialize` derive's serialized string, or `format!("{v:?}")`
21156        // on the `Debug` derive), any two of which a future variant
21157        // rename or `#[serde(rename_all = "kebab-case")]` attribute
21158        // would silently desynchronize. Wiring [`std::fmt::Display`]
21159        // through [`PlacementStrategy::as_str`] closes the third path:
21160        // every `format!("{v}")` call reaches the same lifted
21161        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
21162        // and the [`PlacementStrategy::as_str`] helper already route
21163        // through, so a future variant rename lands at exactly one
21164        // place. Pin the routing here so a future
21165        // `impl std::fmt::Display for PlacementStrategy` reimplementation
21166        // that hand-rolls the arms instead of delegating to
21167        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
21168        for variant in [
21169            PlacementStrategy::SingleNode,
21170            PlacementStrategy::Replicated,
21171            PlacementStrategy::Sharded,
21172        ] {
21173            assert_eq!(
21174                variant.to_string(),
21175                variant.as_str(),
21176                "PlacementStrategy::{variant:?} Display must route through \
21177                 PlacementStrategy::as_str (single source of truth: the lifted \
21178                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
21179            );
21180        }
21181    }
21182
21183    #[test]
21184    fn placement_strategy_display_matches_serialized_wire_byte_string() {
21185        // The fail-before-pass-after pin on the second half of the
21186        // three-path convergence: `Display` (user-facing text) agrees
21187        // byte-for-byte with the `Serialize` derive's wire format
21188        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
21189        // scalar) on every variant. Pre-lift the two paths were
21190        // structurally independent — a future
21191        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
21192        // would silently rebrand the emitted wire scalar
21193        // (`single-node`, `replicated`, `sharded`) while every consumer
21194        // that pretty-prints the strategy (the M3 diagnostic templates,
21195        // the future `feira app graph` per-Aplicacao strategy line,
21196        // the future M4 CR materializer's admission-webhook rejection
21197        // body) would still emit the TitleCase form the `as_str` /
21198        // `Display` route returns, with the mismatch surfacing at
21199        // consumer parse time / operator dispatch time far from the
21200        // source rebrand commit. Pin the two paths byte-for-byte here
21201        // so any future serde-attribute or variant-rename drift is a
21202        // caixa-core-build-time test failure at this call, not a
21203        // silent per-consumer dispatch miss.
21204        for variant in [
21205            PlacementStrategy::SingleNode,
21206            PlacementStrategy::Replicated,
21207            PlacementStrategy::Sharded,
21208        ] {
21209            let wire = serde_json::to_string(&variant).unwrap();
21210            // Strip the outer `"…"` the JSON string form carries — the
21211            // wire scalar the K8s / YAML apiserver consumes is the
21212            // enclosed byte-string, not the quote wrapper.
21213            let unquoted = wire
21214                .strip_prefix('"')
21215                .and_then(|s| s.strip_suffix('"'))
21216                .expect("serialized PlacementStrategy is a JSON string");
21217            assert_eq!(
21218                variant.to_string(),
21219                unquoted,
21220                "PlacementStrategy::{variant:?} Display byte-string must match the \
21221                 Serialize derive's wire byte-string (three-path convergence: \
21222                 Display + as_str + Serialize all resolve to the same \
21223                 M3_PLACEMENT_ESTRATEGIA_* const)"
21224            );
21225        }
21226    }
21227
21228    #[test]
21229    fn placement_strategy_as_ref_str_routes_through_as_str_accessor() {
21230        // Fail-before-pass-after byte-parity pin on the lifted
21231        // `impl AsRef<str> for PlacementStrategy` — asserts the
21232        // standard-library trait impl and the substrate-primitive
21233        // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
21234        // to the same `&str` per instance across the three-arm closed
21235        // set, so any future silent detour that routes the impl through
21236        // a divergent projection (a per-arm inline
21237        // `match self { PlacementStrategy::Sharded => "Sharded", … }`
21238        // re-inlining that opens a compile-time link to the un-lifted
21239        // arm-literal, a swap onto the kebab-case
21240        // [`gen_platform::Discriminant`] catalog identity that would
21241        // collide the wire axis with the dispatcher-catalog axis) trips
21242        // at caixa-core test time under `PartialEq` rather than at a
21243        // downstream `impl AsRef<str>`-bound consumer's silent split.
21244        // Sweeps every one of the three arms [`PlacementStrategy::ALL`]
21245        // carries so no arm's projection is covered only by the sibling
21246        // wire-format `Serialize` derive path. Peer of the sibling
21247        // [`crate::supervisor::tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
21248        // (419ea81) / `restart_strategy_as_ref_str_routes_through_as_str_accessor`
21249        // (63eb1a4) on the paired M2 per-supervisor closed-set typed
21250        // enums, and the [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
21251        // (16d5c7e) pin on the paired top-level `:versao` typed newtype
21252        // — the four pins together close the substrate primitive's
21253        // `AsRef<str>` projection axis on every closed-set typed enum
21254        // /newtype on the M2/M3 mesh + supervision + version surface.
21255        for &variant in PlacementStrategy::ALL {
21256            assert_eq!(
21257                <PlacementStrategy as AsRef<str>>::as_ref(&variant),
21258                variant.as_str(),
21259                "AsRef<str> impl on PlacementStrategy::{variant:?} must \
21260                 byte-equal PlacementStrategy::as_str on the same instance \
21261                 — divergence signals a silent detour off the substrate-\
21262                 primitive accessor"
21263            );
21264        }
21265    }
21266
21267    #[test]
21268    fn placement_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
21269        // Fail-before-pass-after byte-parity pin on the three-path
21270        // convergence discipline the M3 per-Aplicacao distribution-
21271        // strategy primitive now carries on the `&str`-projection axis:
21272        // `<PlacementStrategy as AsRef<str>>::as_ref(&v)` (the newly
21273        // lifted impl), `format!("{v}")` (the pre-existing
21274        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
21275        // primitive `pub const fn` accessor both trait impls delegate
21276        // through) must resolve to the same byte-string on every
21277        // instance across the three-arm closed set. Refuses any future
21278        // divergence between the two trait impls (a stray
21279        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms rather
21280        // than delegating through the shared accessor; a hypothetical
21281        // `AsRef<str>` rewrite that inlines a per-arm literal cascade)
21282        // that would silently split the two projection paths of the
21283        // same closed-set typed enum. Mirrors the sibling three-path-
21284        // convergence discipline the peer
21285        // [`crate::supervisor::RestartPolicy`] typed enum carries on its
21286        // `AsRef<str>` / `Display` / `as_str` triple (supervisor.rs pin
21287        // `restart_policy_as_ref_str_routes_through_display_via_shared_accessor`,
21288        // 419ea81), the peer [`crate::supervisor::RestartStrategy`]
21289        // triple (supervisor.rs pin
21290        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
21291        // 63eb1a4), and the [`crate::CaixaVersion`] typed newtype
21292        // triple (version.rs pin
21293        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
21294        // 16d5c7e).
21295        for &variant in PlacementStrategy::ALL {
21296            let via_as_ref: &str = <PlacementStrategy as AsRef<str>>::as_ref(&variant);
21297            let via_display: String = format!("{variant}");
21298            let via_accessor: &str = variant.as_str();
21299            assert_eq!(via_as_ref, via_accessor);
21300            assert_eq!(via_display, via_accessor);
21301            assert_eq!(via_as_ref, via_display.as_str());
21302        }
21303    }
21304
21305    #[test]
21306    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
21307        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
21308        // derive on [`PlacementStrategy`]: for each of the three variants
21309        // exactly one of the generated `is_single_node` / `is_replicated`
21310        // / `is_sharded` predicates returns `true` and the other two
21311        // return `false`. Prior to this derive the three per-arm
21312        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
21313        // (the `placement_strategy_variants_round_trip` fixture, the
21314        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
21315        // fixture, and the
21316        // `validate_placement_reads_through_lifted_estrategia_accessor`
21317        // fixture) each open-coded a per-arm PartialEq compare against
21318        // the enum variant — three sites that expressed no compile-time
21319        // link back to the closed-set typed dispatch a future fourth
21320        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
21321        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
21322        // would have to thread through in lockstep or one fixture would
21323        // silently disagree with the others on which arms consume the
21324        // `:shard-key` axis. Peer of the sibling
21325        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
21326        // / [`crate::supervisor::RestartPolicy`] /
21327        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
21328        // the sibling closed-set typed-enum discriminator axes — extends
21329        // the same one-typed-dispatch-per-variant discipline onto the
21330        // fifth (and only remaining) closed-set typed-enum discriminator
21331        // on the caixa surface, closing the axis on the M3 mesh-slot
21332        // family.
21333        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
21334            (PlacementStrategy::SingleNode, [true, false, false]),
21335            (PlacementStrategy::Replicated, [false, true, false]),
21336            (PlacementStrategy::Sharded, [false, false, true]),
21337        ];
21338        for (variant, expected) in rows {
21339            let observed = [
21340                variant.is_single_node(),
21341                variant.is_replicated(),
21342                variant.is_sharded(),
21343            ];
21344            assert_eq!(
21345                observed, expected,
21346                "PlacementStrategy::{variant:?} is_* predicates must partition \
21347                 the arm set (single_node, replicated, sharded); got {observed:?}"
21348            );
21349        }
21350    }
21351
21352    #[test]
21353    fn placement_strategy_is_variant_predicates_are_const_fn() {
21354        // The [`gen_platform::IsVariant`] derive emits `const fn`
21355        // predicates on the peer [`crate::CaixaKind`] +
21356        // [`crate::upgrade::UpgradeInstruction`] +
21357        // [`crate::supervisor::RestartStrategy`] +
21358        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
21359        // pin the same posture on [`PlacementStrategy`] so a future
21360        // accidental downgrade to non-`const` (an added runtime helper
21361        // reachable only from a non-`const` context, a manual hand-rolled
21362        // `impl` that shadows the derive-generated method) trips at
21363        // caixa-core build time rather than surfacing as a downstream
21364        // `const`-context regression far from the derive declaration.
21365        //
21366        // The pin lives inside a `const { assert!(..) }` block so the
21367        // compiler enforces both halves (arm predicate is `const`-
21368        // callable AND returns `true` for the matching arm) at
21369        // caixa-core compile time — peer to the sibling
21370        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
21371        // pins on the closed-set typed enum arm-predicate const-
21372        // callability axis.
21373        const {
21374            assert!(PlacementStrategy::SingleNode.is_single_node());
21375            assert!(PlacementStrategy::Replicated.is_replicated());
21376            assert!(PlacementStrategy::Sharded.is_sharded());
21377        }
21378    }
21379
21380    #[test]
21381    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
21382        // Fail-before-pass-after pin on the substrate-lifted
21383        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
21384        // per-arm predicate: for each variant in the closed accept-set the
21385        // predicate returns `true` iff the variant consumes the paired
21386        // [`Placement::shard_key`] axis under
21387        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
21388        // partition. Today the accept-set is the singleton `{Sharded}` —
21389        // `Sharded` is the Akka-style hash-keyed distribution arm
21390        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
21391        // §II.1) and `Replicated` (active-active) refuse the axis through
21392        // [`AplicacaoError::ShardKeyOnNonSharded`].
21393        //
21394        // Pins the per-arm truth-table so a future arm addition (an
21395        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
21396        // roadmap names, a `WeightedShard` promotion the future M5
21397        // adaptive-placement engine acknowledges) that landed a variant
21398        // without extending this predicate's arm-set would surface as a
21399        // caixa-core build-time exhaustiveness error at the
21400        // `match self { … }` arm-fan below rather than a silent per-consumer
21401        // mis-classification at renderer emit time. The paired
21402        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
21403        // predicate stays a distinct question — arm-identity (which the
21404        // sibling
21405        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
21406        // pin already locks) is not cross-slot-invariant consumption; today
21407        // they trip on the same singleton but the pair migrates through
21408        // one caixa-core edit on any future arm addition.
21409        //
21410        // Peer of the sibling per-arm classifier pins
21411        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
21412        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
21413        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
21414        // derived paired predicate on the post-projection typed-view axis
21415        // — same "per-arm semantic-classification predicate paired with
21416        // the arm-identity predicate the derive already emits" discipline
21417        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
21418        // `:placement :shard-key` cross-slot-invariant axis.
21419        let rows: [(PlacementStrategy, bool); 3] = [
21420            (PlacementStrategy::SingleNode, false),
21421            (PlacementStrategy::Replicated, false),
21422            (PlacementStrategy::Sharded, true),
21423        ];
21424        for (variant, expected) in rows {
21425            assert_eq!(
21426                variant.requires_shard_key(),
21427                expected,
21428                "PlacementStrategy::{variant:?}.requires_shard_key() must \
21429                 be {expected} (the substrate-canonical cross-slot invariant \
21430                 on the :placement :shard-key axis; today `Sharded` is the \
21431                 singleton consuming arm — MESH-COMPOSITION §II.4)",
21432            );
21433        }
21434    }
21435
21436    #[test]
21437    fn placement_strategy_requires_shard_key_is_const_fn() {
21438        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
21439        // invariant per-arm predicate is declared `#[must_use] pub const
21440        // fn` — pin the `const`-eval posture here so a future accidental
21441        // downgrade to non-`const` (an added runtime helper reachable
21442        // only from a non-`const` context, a manual hand-rolled `impl`
21443        // that shadows the current three-arm `match self { … }` dispatch)
21444        // trips at caixa-core build time rather than surfacing as a
21445        // downstream `const`-context regression far from the declaration.
21446        // Same shape as the sibling
21447        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
21448        // the peer [`gen_platform::IsVariant`]-derived arm-identity
21449        // predicate axis, but here the load-bearing assertions live in
21450        // module-scope `const _: () = assert!(…)` items so a violation
21451        // fails at compile time (const-eval trip) rather than test time —
21452        // strictly stronger than the runtime `assert!(CONST)` pattern the
21453        // sibling pin uses, and side-steps the
21454        // `clippy::assertions_on_constants` lint the runtime pattern
21455        // otherwise accumulates on the module baseline.
21456        //
21457        // The test body simply witnesses that the module-scope items
21458        // compiled and the runtime dispatch agrees with the const-eval
21459        // dispatch on every arm — the runtime read gives the test a
21460        // failure surface (rather than an empty test body clippy would
21461        // flag as a no-op).
21462        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
21463        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
21464        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
21465        assert_eq!(
21466            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
21467            [
21468                PlacementStrategy::SingleNode.requires_shard_key(),
21469                PlacementStrategy::Replicated.requires_shard_key(),
21470                PlacementStrategy::Sharded.requires_shard_key(),
21471            ],
21472            "runtime and const-eval dispatch on \
21473             PlacementStrategy::requires_shard_key must agree on every arm",
21474        );
21475    }
21476
21477    #[test]
21478    fn placement_estrategia_accessor_is_const_fn() {
21479        // The [`Placement::estrategia`] per-`:placement` distribution-
21480        // strategy `Copy`-return scalar accessor is declared
21481        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
21482        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
21483        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
21484        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
21485        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
21486        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
21487        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
21488        // [`RateLimit`], every one a `pub const fn`). Pin the
21489        // `const`-eval posture here so a future accidental downgrade to
21490        // non-`const` (an added runtime helper reachable only from a
21491        // non-`const` context, a slot promotion to a non-`Copy` return
21492        // that would silently drop the `const` qualifier, a manual
21493        // hand-rolled shadow) trips at caixa-core build time rather
21494        // than surfacing as a downstream `const`-context regression far
21495        // from the declaration.
21496        //
21497        // Same shape as the sibling
21498        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
21499        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
21500        // predicate axis — the load-bearing witness lives in the
21501        // module-scope `const fn` wrapper `estrategia_via_const_fn`
21502        // below: a body that calls [`Placement::estrategia`] under a
21503        // `const fn` signature is well-formed only when the callee is
21504        // itself `const fn`, so any future accidental downgrade of
21505        // [`Placement::estrategia`] to non-`const` fails at caixa-core
21506        // build time (const-eval E0015 / E0658 depending on the arm),
21507        // strictly stronger than a runtime `assert!(CONST)` and
21508        // side-stepping the destructor-in-const restriction that
21509        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
21510        // items on `Placement`'s `Vec<String>` / `Option<String>`
21511        // carriers.
21512        //
21513        // The runtime body witnesses that the const-eval-shaped
21514        // wrapper agrees with a direct call on every closed-set arm.
21515        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
21516            p.estrategia()
21517        }
21518        for estrategia in [
21519            PlacementStrategy::SingleNode,
21520            PlacementStrategy::Replicated,
21521            PlacementStrategy::Sharded,
21522        ] {
21523            let placement = Placement {
21524                estrategia,
21525                clusters: Vec::new(),
21526                affinity: None,
21527                shard_key: None,
21528            };
21529            assert_eq!(
21530                estrategia_via_const_fn(&placement),
21531                placement.estrategia(),
21532                "const-fn-wrapped and direct dispatch on \
21533                 Placement::estrategia must agree for {estrategia:?}",
21534            );
21535        }
21536    }
21537
21538    #[test]
21539    fn entrada_port_accessor_is_const_fn() {
21540        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
21541        // scalar accessor is declared `#[must_use] pub const fn` —
21542        // matching the peer M3 mesh-slot `Copy`-return accessor family
21543        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
21544        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
21545        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
21546        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
21547        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
21548        // [`RateLimit::window`] on the sibling [`RateLimit`], the
21549        // sibling per-`:placement` [`Placement::estrategia`] pinned by
21550        // [`placement_estrategia_accessor_is_const_fn`] above — every
21551        // one a `pub const fn`). Pin the `const`-eval posture here so
21552        // a future accidental downgrade to non-`const` (an added
21553        // runtime helper reachable only from a non-`const` context, an
21554        // `Option<u16>`-shape migration once the substrate grows
21555        // per-`:membros` heterogeneous listener ports that would
21556        // silently drop the `const` qualifier, a manual hand-rolled
21557        // shadow) trips at caixa-core build time rather than surfacing
21558        // as a downstream `const`-context regression far from the
21559        // declaration.
21560        //
21561        // Same shape as the sibling
21562        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
21563        // load-bearing witness lives in the module-scope `const fn`
21564        // wrapper `port_via_const_fn`: a body that calls
21565        // [`Entrada::port`] under a `const fn` signature is well-formed
21566        // only when the callee is itself `const fn`, side-stepping the
21567        // destructor-in-const restriction that would otherwise block a
21568        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
21569        // `String` / `Vec<String>` carriers.
21570        //
21571        // The runtime body sweeps a representative port set spanning
21572        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
21573        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
21574        // ceiling — the const-fn-wrapped call must agree with a direct
21575        // call on every fixture (a violation trips the test) and every
21576        // returned scalar must byte-equal the input `port` (a violation
21577        // means the accessor stopped being a raw field-return copy).
21578        const fn port_via_const_fn(e: &Entrada) -> u16 {
21579            e.port()
21580        }
21581        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
21582            let entrada = Entrada {
21583                host: String::new(),
21584                para: String::new(),
21585                port,
21586                paths: Vec::new(),
21587            };
21588            assert_eq!(
21589                port_via_const_fn(&entrada),
21590                entrada.port(),
21591                "const-fn-wrapped and direct dispatch on Entrada::port \
21592                 must agree for port={port}",
21593            );
21594            assert_eq!(
21595                entrada.port(),
21596                port,
21597                "Entrada::port must return the storage-side u16 verbatim \
21598                 for port={port}",
21599            );
21600        }
21601    }
21602
21603    #[test]
21604    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
21605        // Load-bearing cross-slot-partition pin closing the loop between
21606        // the substrate-lifted
21607        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
21608        // the closed-set typed enum and the actual
21609        // [`AplicacaoSpec::validate_placement`] runtime behavior across
21610        // the paired `:placement :shard-key` axis: every validated
21611        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
21612        // satisfies `placement.shard_key().is_some() ==
21613        // placement.estrategia().requires_shard_key()`. The four-cell
21614        // shape witness sweeps every combination of (variant in the
21615        // closed accept-set, `:shard-key` Some/None) and pins:
21616        //
21617        //   * variant.requires_shard_key() && shard_key.is_some() →
21618        //     validate() passes; the paired shape is the sole
21619        //     `requires_shard_key` arm-family accepted shape.
21620        //   * variant.requires_shard_key() && shard_key.is_none() →
21621        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
21622        //     the paired shape is the refused missing-key shape on
21623        //     Sharded-family arms.
21624        //   * !variant.requires_shard_key() && shard_key.is_some() →
21625        //     validate() fails with
21626        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
21627        //     is the refused declared-but-inert shape on non-Sharded-
21628        //     family arms.
21629        //   * !variant.requires_shard_key() && shard_key.is_none() →
21630        //     validate() passes; the paired shape is the sole
21631        //     non-`requires_shard_key` arm-family accepted shape.
21632        //
21633        // The compile-time-exhaustive `match p.estrategia()` dispatch at
21634        // [`AplicacaoSpec::validate_placement`] preserves its structural
21635        // arm-fan (a future arm addition still surfaces a build-time
21636        // exhaustiveness error there); this pin closes the semantic loop
21637        // between the arm-fan's shape-gate cascades and the substrate-
21638        // canonical predicate every downstream consumer of the paired
21639        // shape reads through. Fail-before-pass-after locally verified by
21640        // mutating the predicate's `Sharded => true` arm to `false` — the
21641        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
21642        // `validate() must pass` assertion; restoring passes. Same "close
21643        // the loop between the typed predicate and the runtime behavior"
21644        // discipline as the sibling
21645        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
21646        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
21647        // per-arm classifier axis.
21648        for variant in [
21649            PlacementStrategy::SingleNode,
21650            PlacementStrategy::Replicated,
21651            PlacementStrategy::Sharded,
21652        ] {
21653            for present in [false, true] {
21654                let mut spec = three_member_spec();
21655                spec.placement.estrategia = variant;
21656                spec.placement.shard_key = present.then(|| "tenantId".into());
21657                let expects_ok = variant.requires_shard_key() == present;
21658                let result = spec.validate();
21659                match (expects_ok, &result) {
21660                    (true, Ok(())) => {}
21661                    (false, Err(err)) => {
21662                        // Cross-check the refusal diagnostic names the
21663                        // right cell of the four-cell shape witness — the
21664                        // `requires_shard_key && !present` cell must trip
21665                        // [`AplicacaoError::ShardedWithoutKey`]; the
21666                        // `!requires_shard_key && present` cell must trip
21667                        // [`AplicacaoError::ShardKeyOnNonSharded`].
21668                        match (variant.requires_shard_key(), present, err) {
21669                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
21670                            (
21671                                false,
21672                                true,
21673                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
21674                            ) => {
21675                                assert_eq!(
21676                                    *e, variant,
21677                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
21678                                     the paired PlacementStrategy",
21679                                );
21680                            }
21681                            _ => panic!(
21682                                "unexpected refusal for estrategia={variant:?} \
21683                                 present={present}: {err:?}"
21684                            ),
21685                        }
21686                    }
21687                    (true, Err(err)) => panic!(
21688                        "validate() must pass for estrategia={variant:?} \
21689                         present={present} (requires_shard_key={} == present={present}), \
21690                         got {err:?}",
21691                        variant.requires_shard_key(),
21692                    ),
21693                    (false, Ok(())) => panic!(
21694                        "validate() must fail for estrategia={variant:?} \
21695                         present={present} (requires_shard_key={} != present={present})",
21696                        variant.requires_shard_key(),
21697                    ),
21698                }
21699            }
21700        }
21701    }
21702
21703    #[test]
21704    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
21705        // Pin the M3 diagnostic template routes through the typed
21706        // [`PlacementStrategy`] Display byte-string (rebound from the
21707        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
21708        // routes emitted identical bytes (the `Debug` derive on a
21709        // unit variant emits the variant name verbatim, exactly what
21710        // `as_str` returns), but the two paths were structurally
21711        // independent — a future `#[serde(rename_all = "…")]`
21712        // attribute or variant rename would coordinate the wire /
21713        // `Display` / `as_str` triple through the lifted const but
21714        // leave the `Debug` route on the compiler-derived variant name,
21715        // silently desynchronizing the diagnostic byte-string from the
21716        // wire byte-string. Rebinding the template onto `Display`
21717        // ties the diagnostic to the same lifted
21718        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
21719        // emits — drift becomes structurally impossible. Pin the
21720        // byte-string here so a future edit that reverts the template
21721        // to `{estrategia:?}` is caught at caixa-core test time, not
21722        // at consumer dispatch time.
21723        for (variant, expected_scalar) in [
21724            (
21725                PlacementStrategy::SingleNode,
21726                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21727            ),
21728            (
21729                PlacementStrategy::Replicated,
21730                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21731            ),
21732            (
21733                PlacementStrategy::Sharded,
21734                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21735            ),
21736        ] {
21737            let err = AplicacaoError::PlacementWithoutClusters {
21738                estrategia: variant,
21739            };
21740            let msg = err.to_string();
21741            assert!(
21742                msg.starts_with(&format!(":placement {expected_scalar} requires")),
21743                "PlacementWithoutClusters diagnostic for {variant:?} must open \
21744                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
21745            );
21746        }
21747    }
21748
21749    #[test]
21750    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
21751        // Peer of
21752        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
21753        // on the second M3 diagnostic that carries the typed
21754        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
21755        // diagnostics now route the strategy scalar through the same
21756        // [`std::fmt::Display`] surface, tying the diagnostic
21757        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
21758        // const set the wire format also emits. The two non-Sharded
21759        // arms are exercised here (the diagnostic exists to flag a
21760        // `:shard-key` slot the current strategy will never consume);
21761        // the peer `Sharded` arm never reaches this diagnostic (the
21762        // `Sharded` strategy consumes `:shard-key` — the
21763        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
21764        // slot instead).
21765        for (variant, expected_scalar) in [
21766            (
21767                PlacementStrategy::SingleNode,
21768                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21769            ),
21770            (
21771                PlacementStrategy::Replicated,
21772                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21773            ),
21774        ] {
21775            let err = AplicacaoError::ShardKeyOnNonSharded {
21776                estrategia: variant,
21777                shard_key: "$tenantId".into(),
21778            };
21779            let msg = err.to_string();
21780            assert!(
21781                msg.starts_with(&format!(":placement {expected_scalar} carries")),
21782                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
21783                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
21784            );
21785        }
21786    }
21787
21788    #[test]
21789    fn placement_strategy_all_enumerates_every_variant_once() {
21790        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
21791        // exhaustive-iteration surface: every variant appears exactly
21792        // once, and the slice length matches the arm count of the
21793        // closed set. Every consumer that walks the accepted-strategy
21794        // set (a future `feira app placement --list` CLI-side surfacing,
21795        // a future M4 admission-webhook's rejection body naming the
21796        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
21797        // reverse-projection consumers that iterate the accept-set for
21798        // a "did you mean" hint) reads through this slice, so a future
21799        // variant addition (an `Anycast` mesh-anycast arm the
21800        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
21801        // grows the enum but forgets to grow [`Self::ALL`] silently
21802        // truncates every downstream consumer's accept-set at the same
21803        // pre-addition boundary — this pin fails at caixa-core build
21804        // time on the pairwise-distinct + arm-count invariants.
21805        //
21806        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
21807        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
21808        // pins on the peer closed-set typed-enum axes.
21809        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
21810        assert_eq!(
21811            all.len(),
21812            3,
21813            "PlacementStrategy::ALL must enumerate every variant of the \
21814             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
21815        );
21816        for (i, a) in all.iter().enumerate() {
21817            for (j, b) in all.iter().enumerate() {
21818                if i != j {
21819                    assert_ne!(
21820                        a, b,
21821                        "PlacementStrategy::ALL must carry every variant exactly \
21822                         once — got duplicate {a:?} at indices {i} and {j}"
21823                    );
21824                }
21825            }
21826        }
21827        for variant in [
21828            PlacementStrategy::SingleNode,
21829            PlacementStrategy::Replicated,
21830            PlacementStrategy::Sharded,
21831        ] {
21832            assert!(
21833                all.contains(&variant),
21834                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
21835                 addition that grows the enum but forgets to grow the ALL slice \
21836                 silently truncates every downstream consumer's accept-set at the \
21837                 pre-addition boundary"
21838            );
21839        }
21840    }
21841
21842    #[test]
21843    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
21844        // Fail-before-pass-after pin on the forward accept-set of the
21845        // [`PlacementStrategy::from_wire`] reverse projection: every
21846        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
21847        // constant the [`PlacementStrategy::as_str`] emitter walks
21848        // parses back to its paired variant. Any future arm addition
21849        // that grows the emitter's `as_str` match but forgets to grow
21850        // the parser's `from_str` match silently splits the two halves
21851        // of the round-trip — the wire byte-string one non-serde
21852        // consumer parses from the one the emitter wrote — with the
21853        // failure surfacing at parse time far from the rebrand commit.
21854        // Pinning the three-arm accept-set here catches the drift at
21855        // caixa-core build time.
21856        //
21857        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
21858        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
21859        // closed-set typed-enum `str → Self` axes.
21860        for (wire, expected) in [
21861            (
21862                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21863                PlacementStrategy::SingleNode,
21864            ),
21865            (
21866                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21867                PlacementStrategy::Replicated,
21868            ),
21869            (
21870                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21871                PlacementStrategy::Sharded,
21872            ),
21873        ] {
21874            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
21875                panic!(
21876                    "PlacementStrategy::from_wire({wire:?}) must accept every \
21877                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
21878                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
21879                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
21880                )
21881            });
21882            assert_eq!(
21883                parsed, expected,
21884                "PlacementStrategy::from_wire({wire:?}) must return \
21885                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
21886            );
21887        }
21888    }
21889
21890    #[test]
21891    fn placement_strategy_from_wire_round_trips_through_as_str() {
21892        // Fail-before-pass-after pin on the closed round-trip between
21893        // the forward [`PlacementStrategy::as_str`] emitter and the
21894        // reverse [`PlacementStrategy::from_wire`] parser: for every
21895        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
21896        // output must return exactly the same variant. Any per-arm
21897        // divergence — a future arm added to `as_str` but not
21898        // `from_str`, an accidental copy-paste flip in one but not the
21899        // other — silently splits the emit and parse halves and the
21900        // failure surfaces at consumer parse time far from the drift
21901        // site. The `ALL`-iterating shape means a future variant
21902        // addition picks up the coverage by construction.
21903        //
21904        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
21905        // [`crate::CaixaKind::from_wire`] and the
21906        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
21907        // sibling round-trip pin on [`RateLimitUnit`].
21908        for &variant in PlacementStrategy::ALL {
21909            let wire = variant.as_str();
21910            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
21911                panic!(
21912                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
21913                     must be Some({variant:?}) — the two halves of the round-trip \
21914                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
21915                     got None on wire byte-string {wire:?}"
21916                )
21917            });
21918            assert_eq!(
21919                parsed, variant,
21920                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
21921                 must round-trip to the same variant; got {parsed:?}"
21922            );
21923        }
21924    }
21925
21926    #[test]
21927    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
21928        // Fail-before-pass-after pin on the closed-set refusal
21929        // discipline of [`PlacementStrategy::from_wire`]: every
21930        // byte-string outside the three-arm accept-set returns `None`
21931        // rather than silently collapsing onto the [`Default`]
21932        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
21933        // exercised here sweeps the load-bearing drift shapes: the
21934        // empty string (a stripped serde-attribute drift), an all-
21935        // whitespace string (the canonical text-editor accidental
21936        // padding shape), the lowercased kebab-case forms a future
21937        // `#[serde(rename_all = "kebab-case")]` attribute would emit
21938        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
21939        // coincidentally match the accepted canonical scalars, so only
21940        // `"single-node"` fires as a refusal, but pinning the case-
21941        // sensitivity of the accepted arms via the peer [`SingleNode`]
21942        // assertion in the round-trip pin makes the discipline
21943        // structurally clear), the lowercased single-word forms
21944        // (`"singlenode"`), the padded canonical scalar
21945        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
21946        // (`"Sharded\n"`), and a pointer-different `&'static str` that
21947        // happens to alias a canonical byte-string by content but not
21948        // by identity (validated implicitly by the emitter's routing
21949        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
21950        // identity a paired [`crate::assert_str_reexport_identity`] pin
21951        // in caixa-core's per-const declaration surface would catch).
21952        //
21953        // Peer of the sibling
21954        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
21955        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
21956        for bad in [
21957            "",
21958            " ",
21959            "\n",
21960            "\t",
21961            "single-node",
21962            "singlenode",
21963            "SingleNodes",
21964            "single_node",
21965            "single node",
21966            "SINGLENODE",
21967            "SingleNode ",
21968            " SingleNode",
21969            " Sharded ",
21970            "Sharded\n",
21971            "replicated ",
21972            "sharded",
21973            "REPLICATED",
21974            "Anycast",
21975            "Global",
21976            "?",
21977        ] {
21978            assert!(
21979                PlacementStrategy::from_wire(bad).is_none(),
21980                "PlacementStrategy::from_wire({bad:?}) must return None — the \
21981                 parser's accept-set is exactly the three PlacementStrategy::as_str \
21982                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
21983                 is outside that closed set"
21984            );
21985        }
21986    }
21987
21988    #[test]
21989    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
21990        // Fail-before-pass-after pin on the third path of the four-path
21991        // convergence: `from_str` (the reverse projection) inverts the
21992        // `Serialize` derive's wire byte-string on every variant.
21993        // Together with the pre-existing three-path convergence
21994        // (`Display` + `as_str` + `Serialize` all resolve to the same
21995        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
21996        // the peer
21997        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
21998        // this closes the round-trip: the wire byte-string the
21999        // `Serialize` derive emits parses back to the same variant
22000        // through `from_str`, so any future serde-attribute or variant-
22001        // rename drift on the emit half now surfaces as a matched drift
22002        // on the parse half at caixa-core build time — the two halves
22003        // migrate as a unit through the lifted consts on any future
22004        // rename, and the round-trip cannot silently split.
22005        //
22006        // Peer of the sibling
22007        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
22008        // wire-format pin — extends the three-path convergence
22009        // (`Display` + `as_str` + `Serialize`) onto the fourth path
22010        // (`from_str`), closing the `str ↔ Self` round-trip on the
22011        // M3 `:placement :estrategia` closed-set axis.
22012        for &variant in PlacementStrategy::ALL {
22013            let wire = serde_json::to_string(&variant).unwrap();
22014            let unquoted = wire
22015                .strip_prefix('"')
22016                .and_then(|s| s.strip_suffix('"'))
22017                .expect("serialized PlacementStrategy is a JSON string");
22018            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
22019                panic!(
22020                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
22021                     Serialize derive's wire byte-string for \
22022                     PlacementStrategy::{variant:?} — the four-path convergence \
22023                     (Display + as_str + Serialize + from_str) resolves through \
22024                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
22025                )
22026            });
22027            assert_eq!(
22028                parsed, variant,
22029                "PlacementStrategy::from_wire of the Serialize derive's wire \
22030                 byte-string for PlacementStrategy::{variant:?} must round-trip \
22031                 to the same variant; got {parsed:?}"
22032            );
22033        }
22034    }
22035
22036    #[test]
22037    fn placement_strategy_try_from_str_routes_through_from_wire_accessor() {
22038        // Fail-before-pass-after byte-parity pin on the newly lifted
22039        // `impl TryFrom<&str> for PlacementStrategy` — asserts the
22040        // standard-library trait impl and the substrate-primitive
22041        // [`PlacementStrategy::from_wire`] `Option<Self>` accessor
22042        // resolve to the same three-arm accept-set across every arm the
22043        // exhaustive [`PlacementStrategy::ALL`] slice enumerates. Any
22044        // future silent detour that routes the trait impl through a
22045        // divergent projection (a per-arm inline `match s { "SingleNode"
22046        // => Ok(Self::SingleNode), … }` re-inlining that opens a
22047        // compile-time link to the un-lifted arm-literal, a stray
22048        // `#[serde(rename_all = "…")]` attribute drift that silently
22049        // splits the wire byte-string from every consumer that reaches
22050        // for this typed dispatch) trips at caixa-core test time under
22051        // `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
22052        // bound consumer's silent split. Sweeps every one of the three
22053        // arms [`PlacementStrategy::ALL`] carries so no arm's projection
22054        // is covered only by the sibling method-named `from_wire` path.
22055        // Peer of the sibling
22056        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
22057        // (3c83606) and
22058        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
22059        // (bf33136) — extends the trait-idiomatic reverse-projection
22060        // axis onto the first M3-mesh-primitive-defining slot enum on
22061        // the caixa surface.
22062        for &variant in PlacementStrategy::ALL {
22063            let wire = variant.as_str();
22064            assert_eq!(
22065                <PlacementStrategy as TryFrom<&str>>::try_from(wire),
22066                Ok(variant),
22067                "TryFrom<&str> impl on PlacementStrategy must round-trip \
22068                 PlacementStrategy::{variant:?}.as_str() = {wire:?} back to \
22069                 Ok(PlacementStrategy::{variant:?}) — divergence from \
22070                 PlacementStrategy::from_wire signals a silent detour off \
22071                 the substrate-primitive accessor"
22072            );
22073            assert_eq!(
22074                <PlacementStrategy as TryFrom<&str>>::try_from(wire).ok(),
22075                PlacementStrategy::from_wire(wire),
22076                "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
22077                 PlacementStrategy::from_wire on the same input"
22078            );
22079        }
22080    }
22081
22082    #[test]
22083    fn placement_strategy_try_from_str_rejects_unknown_byte_strings() {
22084        // Rejection witness on the `impl TryFrom<&str> for
22085        // PlacementStrategy` — sweeps a candidate set of byte-strings
22086        // outside the three-arm camelCase-schema wire accept-set the
22087        // sibling [`PlacementStrategy::as_str`] emits and asserts every
22088        // one lands on `Err(())`, so a future accidental widening of the
22089        // trait impl's accept-set (a stray additional
22090        // `_ if s.eq_ignore_ascii_case("SingleNode") => Ok(…)` case-
22091        // fold path, a silent inclusion of a kebab-case rebrand of the
22092        // wire byte-string that would collide the two-axis split the
22093        // sibling `placement_strategy_from_wire_rejects_unknown_byte_strings`
22094        // pin makes load-bearing) trips at caixa-core test time. The
22095        // candidate set includes the empty string, whitespace-only
22096        // padding, kebab-case rebrand candidates (`"single-node"`),
22097        // snake_case rebrand candidates (`"single_node"`), uppercase
22098        // rebrand candidates, trailing/leading-whitespace-padded
22099        // canonical scalars, the trailing-newline shape, English-rebrand
22100        // candidates (`"Anycast"`, `"Global"`), and the residual `"?"`
22101        // to trip on any future accidental widening onto the sentinel
22102        // shape sibling enums use for unknown-arm diagnostics.
22103        // Peer of the sibling
22104        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
22105        // (3c83606) rejection witness.
22106        let rejected: &[&str] = &[
22107            "",
22108            " ",
22109            "\n",
22110            "\t",
22111            "single-node",
22112            "singlenode",
22113            "SingleNodes",
22114            "single_node",
22115            "single node",
22116            "SINGLENODE",
22117            "SingleNode ",
22118            " SingleNode",
22119            " Sharded ",
22120            "Sharded\n",
22121            "replicated ",
22122            "sharded",
22123            "REPLICATED",
22124            "Anycast",
22125            "Global",
22126            "?",
22127            "\"Sharded\"",
22128        ];
22129        for &input in rejected {
22130            assert_eq!(
22131                <PlacementStrategy as TryFrom<&str>>::try_from(input),
22132                Err(()),
22133                "TryFrom<&str> impl on PlacementStrategy must reject the \
22134                 non-wire byte-string {input:?} — silent acceptance signals \
22135                 an accept-set widening off the paired \
22136                 PlacementStrategy::from_wire resolver"
22137            );
22138        }
22139    }
22140
22141    #[test]
22142    fn placement_strategy_from_into_static_str_routes_through_as_str_accessor() {
22143        // Fail-before-pass-after byte-parity pin on the newly lifted
22144        // `impl From<PlacementStrategy> for &'static str` — asserts the
22145        // standard-library trait impl and the substrate-primitive
22146        // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
22147        // to the same three-arm emit-set across every arm the exhaustive
22148        // [`PlacementStrategy::ALL`] slice enumerates. Any future silent
22149        // detour that routes the trait impl through a divergent
22150        // projection (a per-arm inline `match strategy { SingleNode =>
22151        // "SingleNode", … }` re-inlining that opens a compile-time link
22152        // to the un-lifted arm-literal outside the paired
22153        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants,
22154        // an accidental swap onto the sibling kebab-case
22155        // [`gen_platform::Discriminant`] catalog identity that would
22156        // collide the wire axis with the dispatcher-catalog axis the
22157        // sibling [`PlacementStrategy::as_str`] doc block makes load-
22158        // bearing) trips at caixa-core test time under `assert_eq!`
22159        // rather than at a downstream `impl Into<&'static str>`-bound
22160        // consumer's silent split. Sweeps every one of the three arms
22161        // [`PlacementStrategy::ALL`] carries so no arm's projection is
22162        // covered only by the sibling method-named `as_str` /
22163        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
22164        // `<&'static str as From<PlacementStrategy>>::from` output in
22165        // three `const`-shape bindings to make the `'static` lifetime
22166        // promise a build-time invariant — a future accidental downgrade
22167        // of any of the three arms'
22168        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants to a
22169        // non-`&'static str` (a `String::leak()`-produced return, a
22170        // `Box::leak`-cast, an intermediate lifetime-erasing helper)
22171        // trips at caixa-core build time rather than at a downstream
22172        // `'static`-bound consumer. Peer of the sibling
22173        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
22174        // (523157d) /
22175        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
22176        // (9fb37d0) /
22177        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
22178        // (edb827b) /
22179        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
22180        // (c189a6f) pins on the sibling closed-set typed-enum forward-
22181        // projection axes — extends the trait-idiomatic forward-
22182        // projection axis onto the fifth closed-set fieldless typed
22183        // enum on the caixa surface (the M3-mesh-primitive-defining
22184        // `:placement :estrategia` axis, first-of-many on the M3 mesh
22185        // slot family the caixa-mesh renderer keys off end-to-end).
22186        const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
22187        const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
22188        const SHARDED: &str = PlacementStrategy::Sharded.as_str();
22189        for &variant in PlacementStrategy::ALL {
22190            let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
22191            let via_method: &'static str = variant.as_str();
22192            assert_eq!(
22193                via_trait, via_method,
22194                "From<PlacementStrategy> for &'static str impl must \
22195                 round-trip PlacementStrategy::{variant:?} to the same \
22196                 lifted M3_PLACEMENT_ESTRATEGIA_* const \
22197                 PlacementStrategy::as_str returns — divergence signals \
22198                 a silent detour off the substrate-primitive accessor"
22199            );
22200            let via_into: &'static str = variant.into();
22201            assert_eq!(
22202                via_into, via_method,
22203                "Into<&'static str>::into on PlacementStrategy::{variant:?} \
22204                 must byte-equal PlacementStrategy::as_str on the same \
22205                 input — the blanket-derived Into shape must resolve to \
22206                 the same as_str dispatch as the explicit From impl"
22207            );
22208        }
22209        assert_eq!(
22210            [SINGLE_NODE, REPLICATED, SHARDED],
22211            [
22212                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
22213                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
22214                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
22215            ],
22216            "const-context PlacementStrategy::as_str must resolve to the \
22217             three lifted M3_PLACEMENT_ESTRATEGIA_* consts — a future \
22218             accidental downgrade of any arm to a non-const or non-static \
22219             byte-string breaks the `&'static str`-lifetime promise the \
22220             paired From<PlacementStrategy> for &'static str impl carries \
22221             by construction"
22222        );
22223    }
22224
22225    #[test]
22226    fn placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
22227        // Cross-axis partition pin: the paired trait-idiomatic
22228        // `From<PlacementStrategy> for &'static str` forward projection
22229        // and the method-named [`PlacementStrategy::as_str`] forward
22230        // projection must resolve identically on *every* arm, not just
22231        // the ones named in the primary byte-parity pin above. Sweeps
22232        // every [`PlacementStrategy::ALL`] arm and asserts the trait's
22233        // `From::from` output byte-equals the method-named accessor's
22234        // return-value on each, locking the two forward-projection paths
22235        // together by construction so any future detour (a stray `From`
22236        // special-case that lands on a divergent per-arm literal outside
22237        // the paired `as_str` dispatch, a hypothetical rebrand touching
22238        // one axis without the other) trips at caixa-core test time.
22239        // Peer of the sibling forward-projection partition pins
22240        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
22241        // (523157d) /
22242        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
22243        // (9fb37d0) /
22244        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
22245        // (edb827b) /
22246        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
22247        // (c189a6f) — extends the round-trip discipline onto the fifth
22248        // closed-set typed enum on the caixa surface, closing the two-way
22249        // `Self ↔ &'static str` round-trip on the trait-idiomatic pair
22250        // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
22251        // well as the pre-existing method-named pair (`as_str` +
22252        // `from_wire`).
22253        for &variant in PlacementStrategy::ALL {
22254            let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
22255            let via_method: &'static str = variant.as_str();
22256            assert_eq!(
22257                via_trait, via_method,
22258                "From<PlacementStrategy> for &'static str and \
22259                 PlacementStrategy::as_str must resolve identically on \
22260                 PlacementStrategy::{variant:?} — divergence signals the \
22261                 two forward-projection paths have drifted onto different \
22262                 emit-sets"
22263            );
22264        }
22265        // Round-trip witness: every arm's forward `From` output re-parses
22266        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
22267        // to the original variant. Closes the two-way `PlacementStrategy
22268        // ↔ &'static str` round-trip on the trait-idiomatic axis pair
22269        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
22270        // axis pair requires — the emit-side
22271        // [`PlacementStrategy::as_str`] and the parse-side
22272        // [`PlacementStrategy::from_wire`] dispatch on the same three
22273        // lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
22274        // by construction), mirroring the pre-existing method-named
22275        // `as_str` + `from_wire` round-trip on the substrate-primitive
22276        // axis pair.
22277        for &variant in PlacementStrategy::ALL {
22278            let emitted: &'static str = variant.into();
22279            let re_parsed: Result<PlacementStrategy, ()> =
22280                <PlacementStrategy as TryFrom<&str>>::try_from(emitted);
22281            assert_eq!(
22282                re_parsed,
22283                Ok(variant),
22284                "trait-idiomatic axis pair must round-trip \
22285                 PlacementStrategy::{variant:?} through `.into::<&'static \
22286                 str>()` and back through `TryFrom<&str>` — a break \
22287                 signals the forward-emit and reverse-parse axes have \
22288                 drifted onto different vocabularies"
22289            );
22290        }
22291    }
22292
22293    #[test]
22294    fn placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
22295        // Fail-before-pass-after byte-parity pin on the newly lifted
22296        // `impl From<&PlacementStrategy> for &'static str` — asserts
22297        // the borrowed-input standard-library trait impl and the
22298        // substrate-primitive [`PlacementStrategy::as_str`] `pub const
22299        // fn` accessor resolve to the same three-arm emit-set across
22300        // every arm the exhaustive [`PlacementStrategy::ALL`] slice
22301        // enumerates. Rust's `From` trait does not auto-derive the
22302        // borrowed-input sibling from a paired owned-input impl (no
22303        // `impl<T, U> From<&T> for U where T: Copy, U: From<T>`
22304        // blanket in `core`), so the borrowed-input axis is a distinct
22305        // trait-idiomatic surface that a `.iter().map(Into::into)`
22306        // shape over [`PlacementStrategy::ALL`] (whose iterator yields
22307        // `&PlacementStrategy`, not `PlacementStrategy`) reaches
22308        // through this impl and no other — the paired owned-input
22309        // [`From<PlacementStrategy>`] impl requires an explicit
22310        // `.copied()` / dereference before the trait fires.
22311        // Materializes the `<&'static str as
22312        // From<&PlacementStrategy>>::from` output in a `const`-shape
22313        // binding to make the `'static` lifetime promise a build-time
22314        // invariant. Peer of the sibling
22315        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
22316        // (64aa742) /
22317        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
22318        // (5ab993a) /
22319        // [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
22320        // (807b0b5) /
22321        // [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
22322        // (e941836) /
22323        // [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
22324        // (842c7f3) pins on the sibling closed-set typed-enum
22325        // borrowed-input forward-projection axes — extends the
22326        // borrowed-input axis onto the first M3-mesh-primitive-defining
22327        // closed-set typed enum on the caixa surface.
22328        const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
22329        const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
22330        const SHARDED: &str = PlacementStrategy::Sharded.as_str();
22331        for variant in PlacementStrategy::ALL {
22332            let via_trait: &'static str = <&'static str as From<&PlacementStrategy>>::from(variant);
22333            let via_method: &'static str = variant.as_str();
22334            assert_eq!(
22335                via_trait, via_method,
22336                "From<&PlacementStrategy> for &'static str impl must \
22337                 round-trip &PlacementStrategy::{variant:?} to the same \
22338                 lifted M3_PLACEMENT_ESTRATEGIA_* const \
22339                 PlacementStrategy::as_str returns — divergence signals \
22340                 a silent detour off the substrate-primitive accessor"
22341            );
22342            let via_into: &'static str = variant.into();
22343            assert_eq!(
22344                via_into, via_method,
22345                "Into<&'static str>::into on &PlacementStrategy::{variant:?} \
22346                 must byte-equal PlacementStrategy::as_str on the same \
22347                 input — the blanket-derived Into shape must resolve to \
22348                 the same as_str dispatch as the explicit From impl"
22349            );
22350        }
22351        assert_eq!(
22352            [SINGLE_NODE, REPLICATED, SHARDED],
22353            [
22354                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
22355                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
22356                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
22357            ],
22358            "const-context PlacementStrategy::as_str must resolve to the \
22359             three lifted M3_PLACEMENT_ESTRATEGIA_* consts — the \
22360             borrowed-input From<&PlacementStrategy> for &'static str \
22361             impl inherits its `'static` lifetime promise from the same \
22362             accessor the owned-input sibling routes through"
22363        );
22364    }
22365
22366    #[test]
22367    fn placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
22368        // Cross-axis partition pin: the paired trait-idiomatic
22369        // owned-input `From<PlacementStrategy> for &'static str`
22370        // (afa3562 campaign-shape) and borrowed-input
22371        // `From<&PlacementStrategy> for &'static str` (this lift)
22372        // forward projections must resolve identically on every arm,
22373        // locking the two input-shape paths together so any future
22374        // detour trips at caixa-core test time. Then a witness that a
22375        // `.iter().map(Into::into)` pipe over
22376        // [`PlacementStrategy::ALL`] (whose iterator yields
22377        // `&PlacementStrategy`) materializes the three-arm accept-set
22378        // through the borrowed-input axis alone — the exact shape a
22379        // future M4 admission-webhook rejection body's accepted-set
22380        // enumeration, a future substrate-wide per-arm diagnostic
22381        // column, or a
22382        // `HashMap::<&'static str, PlacementStrategy>::from_iter(
22383        //     PlacementStrategy::ALL.iter().map(|s| (s.into(), *s)))`-
22384        // style per-strategy lookup reaches through — closing the
22385        // two-way owned/borrowed input-shape symmetry on the M3 slot
22386        // enum's forward-projection trait-idiomatic axis. Peer of the
22387        // sibling
22388        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
22389        // (64aa742) /
22390        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
22391        // (5ab993a) /
22392        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
22393        // (807b0b5) /
22394        // [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
22395        // (e941836) /
22396        // [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
22397        // (842c7f3) partition pins on the sibling closed-set typed-enum
22398        // discriminator axes — extends the borrowed-input axis
22399        // discipline onto the first M3-mesh-primitive-defining closed-
22400        // set typed enum on the caixa surface (the `:placement
22401        // :estrategia` axis). Also closes the direct two-way `&Self →
22402        // &'static str → Self` round-trip via the paired
22403        // [`TryFrom<&str>`] axis — unlike the peer [`crate::CaixaKind`]
22404        // axis pair (whose forward `From` emits lowercase Portuguese
22405        // diagnostic bytes while the reverse `TryFrom` parses
22406        // `PascalCase` wire bytes, forcing the round-trip through an
22407        // intermediate wire-vocab hop), the
22408        // [`PlacementStrategy::as_str`] emit and
22409        // [`PlacementStrategy::from_wire`] parse share the same
22410        // `PascalCase` vocabulary by construction, so the borrowed-
22411        // input forward axis and the reverse axis compose directly.
22412        for &variant in PlacementStrategy::ALL {
22413            let owned: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
22414            let borrowed: &'static str = <&'static str as From<&PlacementStrategy>>::from(&variant);
22415            assert_eq!(
22416                owned, borrowed,
22417                "From<PlacementStrategy> and From<&PlacementStrategy> \
22418                 for &'static str must resolve identically on \
22419                 PlacementStrategy::{variant:?} — divergence signals \
22420                 the owned-input and borrowed-input forward-projection \
22421                 paths have drifted onto different emit-sets"
22422            );
22423        }
22424        let via_iter: Vec<&'static str> = PlacementStrategy::ALL.iter().map(Into::into).collect();
22425        let via_method: Vec<&'static str> =
22426            PlacementStrategy::ALL.iter().map(|s| s.as_str()).collect();
22427        assert_eq!(
22428            via_iter, via_method,
22429            "`.iter().map(Into::into)` over PlacementStrategy::ALL must \
22430             byte-equal `.iter().map(|s| s.as_str())` on every arm — \
22431             the borrowed-input `From<&PlacementStrategy> for &'static \
22432             str` axis is what makes the `.iter().map(Into::into)` \
22433             shape route through the substrate-primitive \
22434             `PlacementStrategy::as_str` accessor rather than through a \
22435             per-call-site `.copied()` / dereference detour"
22436        );
22437        for variant in PlacementStrategy::ALL {
22438            let emitted: &'static str = variant.into();
22439            let re_parsed: Result<PlacementStrategy, ()> =
22440                <PlacementStrategy as TryFrom<&str>>::try_from(emitted);
22441            assert_eq!(
22442                re_parsed,
22443                Ok(*variant),
22444                "trait-idiomatic borrowed-input forward-projection + \
22445                 reverse-projection axis pair must round-trip \
22446                 &PlacementStrategy::{variant:?} through `.into::<&'static \
22447                 str>()` (via the borrowed-input axis) and back through \
22448                 `TryFrom<&str>` — a break signals the borrowed-input \
22449                 forward-emit and reverse-parse axes have drifted onto \
22450                 different vocabularies"
22451            );
22452        }
22453    }
22454
22455    #[test]
22456    fn rejects_zero_policy_timeout() {
22457        let mut s = three_member_spec();
22458        s.politicas.timeout = Some(Duration::ZERO);
22459        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
22460    }
22461
22462    #[test]
22463    fn rejects_zero_policy_retries() {
22464        let mut s = three_member_spec();
22465        s.politicas.retries = Some(0);
22466        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
22467    }
22468
22469    #[test]
22470    fn rejects_policy_retries_above_cap() {
22471        // The fail-before-pass-after pin: `Some(11)` is structurally
22472        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
22473        // passed validate on every pre-gate codebase because the
22474        // typed slot's only check was the zero-floor arm. The
22475        // thundering-herd amplification vector only surfaced at the
22476        // runtime substrate (Envoy / Cilium L7 retry overlay)
22477        // far from the source caixa.lisp with no field naming the
22478        // offending policy.
22479        let mut s = three_member_spec();
22480        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
22481        assert_eq!(
22482            s.validate().unwrap_err(),
22483            AplicacaoError::PolicyRetriesExceedsCap {
22484                retries: POLICY_RETRIES_MAX + 1
22485            }
22486        );
22487    }
22488
22489    #[test]
22490    fn rejects_policy_retries_far_above_cap() {
22491        // The `u32::MAX` worst case — the four-billion-retry policy
22492        // a typo (`(:retries 4294967295)`) or struct-literal
22493        // copy-paste lands in the slot. Pin the cap arm's coverage
22494        // explicitly across the full `u32` overflow so a future
22495        // relaxation that drops the upper bound surfaces here.
22496        let mut s = three_member_spec();
22497        s.politicas.retries = Some(u32::MAX);
22498        assert_eq!(
22499            s.validate().unwrap_err(),
22500            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
22501        );
22502    }
22503
22504    #[test]
22505    fn accepts_policy_retries_at_cap() {
22506        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
22507        // must validate. The cap is inclusive on the top edge,
22508        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
22509        // discipline on the sibling [`crate::LimitsSpec::memory`]
22510        // axis. Pin the boundary explicitly so a future off-by-one
22511        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
22512        // surfaces here as a test failure rather than a silent
22513        // contract narrowing.
22514        let mut s = three_member_spec();
22515        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22516        s.validate()
22517            .expect("retries == POLICY_RETRIES_MAX must validate");
22518    }
22519
22520    #[test]
22521    fn accepts_policy_retries_typical_values() {
22522        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
22523        // every value in the validated set must pass. The
22524        // Envoy / Istio production-playbook recommendation band
22525        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
22526        // (`maxRetries ≤ 10`) both lie within this set.
22527        for r in 1..=POLICY_RETRIES_MAX {
22528            let mut s = three_member_spec();
22529            s.politicas.retries = Some(r);
22530            s.validate()
22531                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
22532        }
22533    }
22534
22535    #[test]
22536    fn policy_retries_zero_takes_precedence_over_cap() {
22537        // The cross-arm ordering pin: `Some(0)` is structurally
22538        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
22539        // (cap), but the zero-floor diagnostic is the more
22540        // self-locating one (it directly names the omit-axis
22541        // remediation), so the validate gate must fire on zero
22542        // first. Pin the order so a future refactor that reorders
22543        // the arms surfaces here as a test failure rather than a
22544        // silent diagnostic regression. Same shape every other
22545        // zero-then-shape ordering on this surface uses
22546        // ([`AplicacaoError::PolicyTimeoutZero`] then
22547        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
22548        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
22549        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
22550        let mut s = three_member_spec();
22551        s.politicas.retries = Some(0);
22552        assert_eq!(
22553            s.validate().unwrap_err(),
22554            AplicacaoError::PolicyRetriesZero,
22555            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
22556        );
22557    }
22558
22559    #[test]
22560    fn policy_retries_cap_diagnostic_carries_offending_value() {
22561        // The diagnostic-shape pin: the offending `u32` is carried
22562        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
22563        // variant so the surfaced error message names the value the
22564        // author wrote (`":politicas :retries (47) exceeds the
22565        // mesh-policy ceiling …"`), not just the cap. Same
22566        // self-locating diagnostic shape every other typed-cap arm
22567        // on this surface carries
22568        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
22569        // offending byte count verbatim).
22570        let mut s = three_member_spec();
22571        s.politicas.retries = Some(47);
22572        let err = s.validate().unwrap_err();
22573        assert!(
22574            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
22575            "got {err:?}"
22576        );
22577        let msg = err.to_string();
22578        assert!(
22579            msg.contains("47"),
22580            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
22581        );
22582    }
22583
22584    #[test]
22585    fn policy_retries_cap_is_aws_app_mesh_aligned() {
22586        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
22587        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
22588        // schema cap — the only upstream mesh-policy schema that
22589        // documents an explicit hard cap. Pinning the literal value
22590        // here surfaces a future drift (a relaxation to 20, a
22591        // tightening to 5) as a deliberate test edit, not a silent
22592        // contract narrowing.
22593        assert_eq!(POLICY_RETRIES_MAX, 10);
22594    }
22595
22596    #[test]
22597    fn rejects_circuit_breaker_zero_max_failures() {
22598        let mut s = three_member_spec();
22599        s.politicas.circuit_breaker = Some(CircuitBreaker {
22600            max_failures: 0,
22601            window: Duration::from_secs(60),
22602        });
22603        assert_eq!(
22604            s.validate().unwrap_err(),
22605            AplicacaoError::PolicyBreakerZeroFailures
22606        );
22607    }
22608
22609    #[test]
22610    fn rejects_circuit_breaker_max_failures_above_cap() {
22611        // The fail-before-pass-after pin: `1001` is structurally one
22612        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
22613        // silently passed validate on every pre-gate codebase
22614        // because the typed slot's only check was the zero-floor
22615        // arm. The breaker-no-op vector only surfaced at the runtime
22616        // substrate (Envoy / Cilium L7 outlier-detection overlay)
22617        // far from the source caixa.lisp with no field naming the
22618        // offending policy.
22619        let mut s = three_member_spec();
22620        s.politicas.circuit_breaker = Some(CircuitBreaker {
22621            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22622            window: Duration::from_secs(60),
22623        });
22624        assert_eq!(
22625            s.validate().unwrap_err(),
22626            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22627                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22628            }
22629        );
22630    }
22631
22632    #[test]
22633    fn rejects_circuit_breaker_max_failures_far_above_cap() {
22634        // The `u32::MAX` worst case — the four-billion-failure
22635        // threshold a typo (`(:max-failures 4294967295)`) or a
22636        // struct-literal copy-paste lands in the slot. Pin the cap
22637        // arm's coverage explicitly across the full `u32` overflow
22638        // so a future relaxation that drops the upper bound surfaces
22639        // here.
22640        let mut s = three_member_spec();
22641        s.politicas.circuit_breaker = Some(CircuitBreaker {
22642            max_failures: u32::MAX,
22643            window: Duration::from_secs(60),
22644        });
22645        assert_eq!(
22646            s.validate().unwrap_err(),
22647            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22648                max_failures: u32::MAX,
22649            }
22650        );
22651    }
22652
22653    #[test]
22654    fn accepts_circuit_breaker_max_failures_at_cap() {
22655        // The boundary value — exactly
22656        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
22657        // cap is inclusive on the top edge, matching the
22658        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
22659        // discipline on the sibling capped axes. Pin the boundary
22660        // explicitly so a future off-by-one tightening
22661        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
22662        // surfaces here as a test failure rather than a silent
22663        // contract narrowing.
22664        let mut s = three_member_spec();
22665        s.politicas.circuit_breaker = Some(CircuitBreaker {
22666            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22667            window: Duration::from_secs(60),
22668        });
22669        s.validate()
22670            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
22671    }
22672
22673    #[test]
22674    fn accepts_circuit_breaker_max_failures_typical_values() {
22675        // The documented production-playbook band positive-control
22676        // sweep — every value Hystrix / Istio / Envoy / Polly /
22677        // Resilience4j recommend (5..=50) must pass, plus a sweep
22678        // through the hyperscale band (100, 500, 1000) the cap
22679        // accepts. Pin the inclusive validated set explicitly so a
22680        // future tightening of the ceiling surfaces here.
22681        //
22682        // Clears the fixture's `:retries` (which is `Some(3)`) so this
22683        // per-axis sweep is pure: the sibling cross-axis
22684        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
22685        // gate rejects any `max_failures <= retries` pair, so the
22686        // `max_failures = 1` boundary at the head of the sweep would
22687        // otherwise trip on the fixture-inherited retry policy rather
22688        // than the per-axis boundary this test names. Same discipline
22689        // the sibling per-axis `accepts_circuit_breaker_window_*`
22690        // sweeps take against the fixture's `:timeout` for the
22691        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
22692        // cross-axis arm.
22693        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
22694            let mut s = three_member_spec();
22695            s.politicas.retries = None;
22696            s.politicas.circuit_breaker = Some(CircuitBreaker {
22697                max_failures: n,
22698                window: Duration::from_secs(60),
22699            });
22700            s.validate()
22701                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
22702        }
22703    }
22704
22705    #[test]
22706    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
22707        // The cross-arm ordering pin: `0` is structurally outside
22708        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
22709        // (cap), but the zero-floor diagnostic is the more
22710        // self-locating one (it directly names the omit-axis
22711        // remediation), so the validate gate must fire on zero
22712        // first. Same shape every other zero-then-shape ordering on
22713        // this surface uses
22714        // ([`AplicacaoError::PolicyRetriesZero`] then
22715        // [`AplicacaoError::PolicyRetriesExceedsCap`];
22716        // [`AplicacaoError::PolicyTimeoutZero`] then
22717        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
22718        let mut s = three_member_spec();
22719        s.politicas.circuit_breaker = Some(CircuitBreaker {
22720            max_failures: 0,
22721            window: Duration::from_secs(60),
22722        });
22723        assert_eq!(
22724            s.validate().unwrap_err(),
22725            AplicacaoError::PolicyBreakerZeroFailures,
22726            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
22727        );
22728    }
22729
22730    #[test]
22731    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
22732        // The cross-arm ordering pin between the cap and the
22733        // sibling `:window` gates (zero-window, canonical-window).
22734        // A breaker carrying both an over-cap `max_failures` AND a
22735        // structurally invalid window (zero, sub-ms) must surface
22736        // the cap diagnostic first — the cap arm is wired
22737        // immediately after the zero-failure arm and strictly
22738        // before the window arms, so the offending value the
22739        // diagnostic names matches the order the author would
22740        // discover the gates by reading top-to-bottom through
22741        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
22742        // future refactor that reorders the arms surfaces here as a
22743        // test failure rather than a silent diagnostic regression.
22744        let mut s = three_member_spec();
22745        s.politicas.circuit_breaker = Some(CircuitBreaker {
22746            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22747            window: Duration::ZERO,
22748        });
22749        assert_eq!(
22750            s.validate().unwrap_err(),
22751            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22752                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22753            },
22754            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
22755        );
22756    }
22757
22758    #[test]
22759    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
22760        // The diagnostic-shape pin: the offending `u32` is carried
22761        // verbatim into the
22762        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
22763        // variant so the surfaced error message names the value the
22764        // author wrote (`":politicas :circuit-breaker :max-failures
22765        // (50000) exceeds the mesh-policy ceiling …"`), not just
22766        // the cap. Same self-locating diagnostic shape every other
22767        // typed-cap arm on this surface carries
22768        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
22769        // offending retry count verbatim,
22770        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
22771        // offending byte count verbatim).
22772        let mut s = three_member_spec();
22773        s.politicas.circuit_breaker = Some(CircuitBreaker {
22774            max_failures: 50_000,
22775            window: Duration::from_secs(60),
22776        });
22777        let err = s.validate().unwrap_err();
22778        assert!(
22779            matches!(
22780                err,
22781                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22782                    max_failures: 50_000
22783                }
22784            ),
22785            "got {err:?}"
22786        );
22787        let msg = err.to_string();
22788        assert!(
22789            msg.contains("50000"),
22790            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
22791        );
22792    }
22793
22794    #[test]
22795    fn policy_breaker_max_failures_cap_pins_canonical_value() {
22796        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
22797        // value at 1000 — an order of magnitude above every
22798        // documented production-playbook recommendation band
22799        // (Hystrix `requestVolumeThreshold` default 20, Istio
22800        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
22801        // `outlier_detection.consecutive_5xx` default 5, Polly /
22802        // Resilience4j typical 5..=50) and below the
22803        // clearly-pathological "effectively no protection" floor
22804        // (10_000, 100_000, u32::MAX). Pinning the literal value
22805        // here surfaces a future drift (a relaxation to 10_000, a
22806        // tightening to 100) as a deliberate test edit, not a
22807        // silent contract narrowing.
22808        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
22809    }
22810
22811    #[test]
22812    fn rejects_circuit_breaker_zero_window() {
22813        let mut s = three_member_spec();
22814        s.politicas.circuit_breaker = Some(CircuitBreaker {
22815            max_failures: 5,
22816            window: Duration::ZERO,
22817        });
22818        assert_eq!(
22819            s.validate().unwrap_err(),
22820            AplicacaoError::PolicyBreakerZeroWindow
22821        );
22822    }
22823
22824    #[test]
22825    fn rejects_zero_rate_limit() {
22826        let mut s = three_member_spec();
22827        s.politicas.rate_limit = Some(RateLimit {
22828            rate: 0,
22829            window: Duration::from_secs(1),
22830        });
22831        assert_eq!(
22832            s.validate().unwrap_err(),
22833            AplicacaoError::PolicyRateLimitZero
22834        );
22835    }
22836
22837    #[test]
22838    fn rejects_rate_limit_zero_window() {
22839        // `RateLimit { rate: 100, window: Duration::ZERO }` is
22840        // constructible programmatically (the typed `Duration` field
22841        // imposes no nonzero invariant) but renders through
22842        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
22843        // codec's `parse` rejects as `unknown rate-limit window unit
22844        // "0s"`. Until this validate-time gate landed the typed slot
22845        // accepted the value silently and the round-trip break only
22846        // surfaced at deserialize time (potentially in a downstream
22847        // consumer that never re-validates). Pin the rejection at
22848        // `AplicacaoSpec::validate` so the typed slot's valid set
22849        // matches the codec's round-trippable set structurally.
22850        let mut s = three_member_spec();
22851        s.politicas.rate_limit = Some(RateLimit {
22852            rate: 100,
22853            window: Duration::ZERO,
22854        });
22855        assert_eq!(
22856            s.validate().unwrap_err(),
22857            AplicacaoError::PolicyRateLimitWindowNotCanonical {
22858                window: Duration::ZERO
22859            }
22860        );
22861    }
22862
22863    #[test]
22864    fn rejects_rate_limit_arbitrary_seconds_window() {
22865        // 45 seconds is a valid `Duration` but not one of the three
22866        // canonical rate-limit windows the codec round-trips
22867        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
22868        // refuses on round-trip — same round-trip-break shape the
22869        // zero-window arm above pins, with a non-zero magnitude to
22870        // guard against a future "reject only zero" half-measure.
22871        let mut s = three_member_spec();
22872        let window = Duration::from_secs(45);
22873        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
22874        assert_eq!(
22875            s.validate().unwrap_err(),
22876            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
22877        );
22878    }
22879
22880    #[test]
22881    fn rejects_rate_limit_two_minute_window() {
22882        // 120 seconds = 2 minutes is a "looks-canonical" but
22883        // not-canonical window: it's a clean integer multiple of the
22884        // minute unit, but the codec only round-trips the
22885        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
22886        // A `Duration::from_secs(120)` window renders as `"100/120s"`
22887        // which the parser rejects. Pinning this case rules out a
22888        // future "accept any clean multiple of s/m/h" relaxation
22889        // that would silently break the codec contract.
22890        let mut s = three_member_spec();
22891        let window = Duration::from_secs(120);
22892        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
22893        assert_eq!(
22894            s.validate().unwrap_err(),
22895            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
22896        );
22897    }
22898
22899    #[test]
22900    fn rejects_rate_limit_subsecond_window() {
22901        // A sub-second window (e.g. 500ms) is a valid `Duration` but
22902        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
22903        // Pin the rejection so a future relaxation can't silently
22904        // admit fractional-second windows that the codec can't
22905        // round-trip.
22906        let mut s = three_member_spec();
22907        let window = Duration::from_millis(500);
22908        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
22909        assert_eq!(
22910            s.validate().unwrap_err(),
22911            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
22912        );
22913    }
22914
22915    #[test]
22916    fn rejects_policy_rate_limit_above_cap() {
22917        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
22918        // is structurally one past the cap and silently passed
22919        // validate on every pre-gate codebase because the typed slot's
22920        // only `rate` check was the zero-floor arm. The no-op-limiter
22921        // shape only surfaced at the runtime substrate (Envoy's
22922        // `local_rate_limit.token_bucket.max_tokens`, the future
22923        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
22924        // with no field naming the offending policy.
22925        let mut s = three_member_spec();
22926        s.politicas.rate_limit = Some(RateLimit {
22927            rate: POLICY_RATE_LIMIT_MAX + 1,
22928            window: Duration::from_secs(1),
22929        });
22930        assert_eq!(
22931            s.validate().unwrap_err(),
22932            AplicacaoError::PolicyRateLimitExceedsCap {
22933                rate: POLICY_RATE_LIMIT_MAX + 1
22934            }
22935        );
22936    }
22937
22938    #[test]
22939    fn rejects_policy_rate_limit_far_above_cap() {
22940        // The `u32::MAX` worst case — the four-billion-token rate-limit
22941        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
22942        // copy-paste lands in the slot. Pin the cap arm's coverage
22943        // explicitly across the full `u32` overflow so a future
22944        // relaxation that drops the upper bound surfaces here. Peer to
22945        // `rejects_policy_retries_far_above_cap` on the sibling
22946        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
22947        // on the sibling `:max-failures` axis.
22948        let mut s = three_member_spec();
22949        s.politicas.rate_limit = Some(RateLimit {
22950            rate: u32::MAX,
22951            window: Duration::from_secs(1),
22952        });
22953        assert_eq!(
22954            s.validate().unwrap_err(),
22955            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
22956        );
22957    }
22958
22959    #[test]
22960    fn accepts_policy_rate_limit_at_cap() {
22961        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
22962        // must validate. The cap is inclusive on the top edge, matching
22963        // every other typed upper bound in this crate
22964        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
22965        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
22966        // across all three canonical windows so a future off-by-one
22967        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
22968        // window-conditional cap surfaces here as a test failure rather
22969        // than a silent contract narrowing.
22970        for secs in [1u64, 60, 3600] {
22971            let mut s = three_member_spec();
22972            s.politicas.rate_limit = Some(RateLimit {
22973                rate: POLICY_RATE_LIMIT_MAX,
22974                window: Duration::from_secs(secs),
22975            });
22976            s.validate().unwrap_or_else(|e| {
22977                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
22978            });
22979        }
22980    }
22981
22982    #[test]
22983    fn accepts_policy_rate_limit_typical_values() {
22984        // The documented production-playbook recommendation band —
22985        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
22986        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
22987        // Enterprise ~1M per-hour. Every value in the validated set
22988        // must pass; pin the band explicitly so a future tightening
22989        // surfaces here.
22990        //
22991        // Clears the fixture's `:retries` (which is `Some(3)`) so this
22992        // per-axis sweep is pure: the sibling cross-axis
22993        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
22994        // rejects any `rate <= retries` pair, so the `rate = 1`
22995        // boundary at the head of the sweep would otherwise trip on the
22996        // fixture-inherited retry policy rather than the per-axis
22997        // boundary this test names. Same discipline the sibling per-axis
22998        // `accepts_circuit_breaker_max_failures_typical_values` sweep
22999        // takes against the fixture's `:retries` for the peer cross-axis
23000        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
23001        // arm.
23002        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
23003            for secs in [1u64, 60, 3600] {
23004                let mut s = three_member_spec();
23005                s.politicas.retries = None;
23006                s.politicas.rate_limit = Some(RateLimit {
23007                    rate,
23008                    window: Duration::from_secs(secs),
23009                });
23010                s.validate().unwrap_or_else(|e| {
23011                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
23012                });
23013            }
23014        }
23015    }
23016
23017    #[test]
23018    fn policy_rate_limit_zero_takes_precedence_over_cap() {
23019        // The cross-arm ordering pin: `rate == 0` is structurally
23020        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
23021        // (cap), but the zero-floor diagnostic is the more
23022        // self-locating one (it directly names the omit-axis
23023        // remediation). Pin the order so a future refactor that
23024        // reorders the arms surfaces here as a test failure rather
23025        // than a silent diagnostic regression. Same shape every other
23026        // zero-then-cap ordering on this surface uses
23027        // ([`AplicacaoError::PolicyRetriesZero`] then
23028        // [`AplicacaoError::PolicyRetriesExceedsCap`];
23029        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
23030        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
23031        let mut s = three_member_spec();
23032        s.politicas.rate_limit = Some(RateLimit {
23033            rate: 0,
23034            window: Duration::from_secs(1),
23035        });
23036        assert_eq!(
23037            s.validate().unwrap_err(),
23038            AplicacaoError::PolicyRateLimitZero,
23039            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
23040        );
23041    }
23042
23043    #[test]
23044    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
23045        // Two-axis-bad pin: rate above cap *and* window non-canonical.
23046        // The validate gate must fire on the rate cap first — the
23047        // amplification-shape (no-op limiter) diagnostic is the more
23048        // fundamental one; the window-canonical diagnostic is the
23049        // narrower codec-round-trip shape. Pin the ordering so a future
23050        // refactor that reorders the rate-then-window check arms
23051        // surfaces here as a test failure rather than a silent
23052        // diagnostic regression.
23053        let mut s = three_member_spec();
23054        s.politicas.rate_limit = Some(RateLimit {
23055            rate: POLICY_RATE_LIMIT_MAX + 1,
23056            window: Duration::from_secs(45),
23057        });
23058        assert_eq!(
23059            s.validate().unwrap_err(),
23060            AplicacaoError::PolicyRateLimitExceedsCap {
23061                rate: POLICY_RATE_LIMIT_MAX + 1
23062            },
23063            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
23064        );
23065    }
23066
23067    #[test]
23068    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
23069        // The diagnostic-shape pin: the offending `u32` is carried
23070        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
23071        // variant so the surfaced error message names the value the
23072        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
23073        // the mesh-policy ceiling …"`), not just the cap. Same
23074        // self-locating diagnostic shape every other typed-cap arm on
23075        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
23076        // carries the offending retries count verbatim,
23077        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
23078        // the offending failure count verbatim).
23079        let mut s = three_member_spec();
23080        s.politicas.rate_limit = Some(RateLimit {
23081            rate: 5_000_000,
23082            window: Duration::from_secs(1),
23083        });
23084        let err = s.validate().unwrap_err();
23085        assert!(
23086            matches!(
23087                err,
23088                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
23089            ),
23090            "got {err:?}"
23091        );
23092        let msg = err.to_string();
23093        assert!(
23094            msg.contains("5000000"),
23095            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
23096        );
23097    }
23098
23099    #[test]
23100    fn policy_rate_limit_cap_pins_canonical_value() {
23101        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
23102        // 1_000_000 — two-to-three orders of magnitude above every
23103        // documented production-playbook recommendation band (Envoy /
23104        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
23105        // Gateway 10_000..=100_000 per-minute) and below the
23106        // clearly-pathological "paste-from-binary blob" floor
23107        // (100_000_000, u32::MAX). Pinning the literal value here
23108        // surfaces a future drift (a relaxation to 10_000_000, a
23109        // tightening to 100_000) as a deliberate test edit, not a
23110        // silent contract narrowing.
23111        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
23112    }
23113
23114    #[test]
23115    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
23116        // Both axes are invalid here: rate == 0 *and* window is
23117        // non-canonical. The validate gate must fire on rate first
23118        // (matching the existing `rejects_zero_rate_limit` ordering),
23119        // so the existing diagnostic continues to lead with the
23120        // simpler "zero rate" framing. Pinning the order of checks
23121        // so a future refactor that reorders the arms surfaces here
23122        // as a test failure rather than a silent diagnostic
23123        // regression.
23124        let mut s = three_member_spec();
23125        s.politicas.rate_limit = Some(RateLimit {
23126            rate: 0,
23127            window: Duration::from_secs(45),
23128        });
23129        assert_eq!(
23130            s.validate().unwrap_err(),
23131            AplicacaoError::PolicyRateLimitZero
23132        );
23133    }
23134
23135    #[test]
23136    fn rate_limit_canonical_windows_validate() {
23137        // The three canonical windows the codec round-trips
23138        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
23139        // unchanged. Pin the full canonical set as a positive case
23140        // (the existing `rate_limit_round_trip_seconds` /
23141        // `rate_limit_round_trip_minutes` tests pin the
23142        // serialize-then-deserialize property at the codec layer; this
23143        // test pins the validate-side complement so a future tightening
23144        // of the canonical set — e.g. dropping `:hour` — surfaces here
23145        // as a test failure rather than a silent contract narrowing).
23146        for secs in [1u64, 60, 3600] {
23147            let mut s = three_member_spec();
23148            s.politicas.rate_limit = Some(RateLimit {
23149                rate: 100,
23150                window: Duration::from_secs(secs),
23151            });
23152            s.validate().expect("canonical window must validate");
23153        }
23154    }
23155
23156    #[test]
23157    fn rate_limit_validated_value_round_trips_through_codec() {
23158        // The structural property the validate gate enforces:
23159        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
23160        // losslessly through the `rate_limit_codec` (serialize → string
23161        // → deserialize → equal value). Pin this end-to-end so a future
23162        // change to either side (the validate gate's accepted window
23163        // set, the codec's parse/render unit set) that breaks the
23164        // alignment surfaces here. The previous-state shape (typed
23165        // slot accepts arbitrary `Duration`, codec only round-trips
23166        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
23167        // window — the validate gate now forecloses that.
23168        for secs in [1u64, 60, 3600] {
23169            let mut s = three_member_spec();
23170            s.politicas.rate_limit = Some(RateLimit {
23171                rate: 250,
23172                window: Duration::from_secs(secs),
23173            });
23174            s.validate().unwrap();
23175            let json = serde_json::to_string(&s.politicas).unwrap();
23176            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
23177            assert_eq!(
23178                back.rate_limit, s.politicas.rate_limit,
23179                "every validated :rate-limit must round-trip losslessly through the codec"
23180            );
23181        }
23182    }
23183
23184    #[test]
23185    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
23186        // The hour-window canonical form (`"<n>/h"`) was missing from
23187        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
23188        // pair. Now that the validate gate pins 3600s as part of the
23189        // canonical set, pin its serialize-side render shape too so
23190        // the third leg of the s/m/h tripod is explicitly tested.
23191        let policy = MeshPolicy {
23192            rate_limit: Some(RateLimit {
23193                rate: 10000,
23194                window: Duration::from_secs(3600),
23195            }),
23196            ..Default::default()
23197        };
23198        let json = serde_json::to_string(&policy).unwrap();
23199        assert!(
23200            json.contains("\"10000/h\""),
23201            "hour-window canonical form must render with `h` suffix (got: {json})"
23202        );
23203        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
23204        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
23205    }
23206
23207    #[test]
23208    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
23209        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
23210        // typed accessor's accepted-window set against the codec's
23211        // accepted set explicitly. A future addition to the codec
23212        // (e.g. accepting `:day`/`:week` as authoring units) must be
23213        // accompanied by a parallel addition here, and a regression
23214        // that drops one of the three canonical units from either
23215        // side surfaces as a test failure. The accessor is the
23216        // single source of truth for the canonical-window set —
23217        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
23218        // gate and [`rate_limit_codec::render`]'s canonical arm both
23219        // read through it — this test enshrines that its
23220        // `Duration → Option<RateLimitUnit>` projection matches the
23221        // codec's parse / render arms' accepted-window set exactly.
23222        //
23223        // Predecessor: this pin previously read the module-private
23224        // free helper `is_canonical_rate_limit_window` — a delegate
23225        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
23226        // — but the helper had no production consumers left after the
23227        // validate-gate migration onto [`RateLimit::canonical_unit`]
23228        // and was deleted; the closed-set arm-window bijection now
23229        // lives on exactly one typed dispatch on the substrate
23230        // primitive.
23231        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
23232            RateLimit { rate: 1, window }.canonical_unit()
23233        };
23234        assert!(canonical_unit(Duration::from_secs(1)).is_some());
23235        assert!(canonical_unit(Duration::from_secs(60)).is_some());
23236        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
23237        // Non-canonical windows the accessor rejects.
23238        assert!(canonical_unit(Duration::ZERO).is_none());
23239        assert!(canonical_unit(Duration::from_secs(2)).is_none());
23240        assert!(canonical_unit(Duration::from_secs(30)).is_none());
23241        assert!(canonical_unit(Duration::from_secs(120)).is_none());
23242        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
23243        // Sub-second windows: even `Duration::from_millis(1000)` is
23244        // exactly 1s and accepted; `Duration::from_millis(500)` is
23245        // sub-second and rejected.
23246        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
23247        assert!(canonical_unit(Duration::from_millis(500)).is_none());
23248        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
23249    }
23250
23251    #[test]
23252    fn rate_limit_unit_table_projections_are_mutual_inverses() {
23253        // Bidirection pin against the closed-set typed enum
23254        // [`RateLimitUnit`] arm-table (the canonical
23255        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
23256        // of the rate-limit unit surface reads from). The two
23257        // projection directions [`RateLimitUnit::from_suffix`] /
23258        // [`RateLimitUnit::window`] (str → Duration, exposed as one
23259        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
23260        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
23261        // (Duration → str, exposed as one typed dispatch through
23262        // [`RateLimit::canonical_unit`] composed with
23263        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
23264        // codec's parse arm ([`rate_limit_codec::parse`] via
23265        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
23266        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
23267        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
23268        // via [`RateLimit::canonical_unit`]) all key off. A future
23269        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
23270        // sub-second window) is one variant + one arm per method on the
23271        // closed-set enum; the compiler-enforced exhaustiveness on
23272        // every consumer's `match self` arms picks it up by
23273        // construction. This pin enshrines that both projection
23274        // directions agree on every canonical arm row and neither
23275        // leaks a spurious entry the other doesn't recognize.
23276        //
23277        // Predecessor: this test previously read the two vestigial
23278        // module-private free helpers `rate_limit_window_unit` and
23279        // `rate_limit_window_from_unit` on the `Duration → &str` and
23280        // `&str → Duration` axes; the former was deleted after its
23281        // sole production consumer ([`rate_limit_codec::render`])
23282        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
23283        // the latter is folded here into the substrate primitive
23284        // [`RateLimitUnit::window_from_suffix`] so both projection
23285        // directions live on the closed-set enum's arm-table.
23286        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
23287            let window = super::RateLimitUnit::window_from_suffix(unit)
23288                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
23289            assert_eq!(
23290                window,
23291                Duration::from_secs(secs),
23292                "unit {unit:?} must resolve to {secs}s"
23293            );
23294            let projected_suffix = RateLimit { rate: 1, window }
23295                .canonical_unit()
23296                .map(super::RateLimitUnit::as_suffix);
23297            assert_eq!(
23298                projected_suffix,
23299                Some(unit),
23300                "Duration({secs}s) must render as {unit:?} \
23301                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
23302            );
23303        }
23304        // Non-table units yield None on the `unit → Duration`
23305        // projection — a future `"d"` addition to the table would
23306        // flip this arm; today it pins the current three-row table's
23307        // rejection semantics.
23308        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
23309        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
23310        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
23311        // Non-table Durations yield None on the `Duration → unit`
23312        // projection — pins that the two projections agree on the
23313        // "not in the table" semantic too, so a drift where the
23314        // parse-side accepts a value the render-side can't emit is
23315        // a build error at the two-arm pair, not a silent codec
23316        // round-trip break.
23317        let projected_suffix = |window: Duration| -> Option<&'static str> {
23318            RateLimit { rate: 1, window }
23319                .canonical_unit()
23320                .map(super::RateLimitUnit::as_suffix)
23321        };
23322        assert!(projected_suffix(Duration::from_secs(2)).is_none());
23323        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
23324        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
23325    }
23326
23327    #[test]
23328    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
23329        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
23330        // substrate-primitive `&str → Duration` associated method the
23331        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
23332        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
23333        // to the same [`Duration`] the two-step composition
23334        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
23335        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
23336        // `"MIN"`) must project to [`None`] on both paths. A future
23337        // implementation of `window_from_suffix` that took a shortcut
23338        // through a per-suffix `match` table (bypassing the arm-table's
23339        // `Self::from_suffix` scan and the arm-table's `Self::window`
23340        // dispatch) would silently split the accept-set — the parse
23341        // arm would accept a suffix the enum's arm-table doesn't know,
23342        // or reject a suffix the enum's arm-table does; this pin
23343        // surfaces that drift at caixa-core build time rather than at a
23344        // downstream serde round-trip audit on a live `MeshPolicy`.
23345        //
23346        // Same byte-parity discipline the sibling
23347        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
23348        // pin carries on the peer `Duration → RateLimitUnit` axis via
23349        // [`RateLimit::canonical_unit`], and the peer
23350        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
23351        // carries on the bidirectional arm-table axis — extended here
23352        // onto the fifth (and last unlifted) projection axis on the
23353        // closed-set enum's arm-table.
23354        let composition = |suffix: &str| -> Option<Duration> {
23355            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
23356        };
23357        for suffix in ["s", "m", "h"] {
23358            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
23359            let via_composition = composition(suffix);
23360            assert_eq!(
23361                via_method, via_composition,
23362                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
23363                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
23364                 method must delegate to the arm-table's two typed dispatches, \
23365                 not shortcut through a per-suffix match table"
23366            );
23367            assert!(
23368                via_method.is_some(),
23369                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
23370                 RateLimitUnit::window_from_suffix"
23371            );
23372        }
23373        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
23374            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
23375            let via_composition = composition(suffix);
23376            assert_eq!(
23377                via_method, via_composition,
23378                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
23379                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
23380                 axis too"
23381            );
23382            assert!(
23383                via_method.is_none(),
23384                "non-arm suffix {suffix:?} must project to None via \
23385                 RateLimitUnit::window_from_suffix — a future extension that \
23386                 accepted this suffix without a corresponding arm on the enum \
23387                 would split the codec's parse-accepted set from the enum's \
23388                 arm-table"
23389            );
23390        }
23391        // And the codec's parse arm now reads through this method: a
23392        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
23393        // the same `Duration` the method returns for its unit, closing
23394        // the two-consumer drift surface (the codec's parse arm and the
23395        // enum's arm-table) with one typed dispatch on the substrate
23396        // primitive.
23397        for suffix in ["s", "m", "h"] {
23398            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
23399            let mp: MeshPolicy = serde_json::from_str(&wire)
23400                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
23401            let parsed = mp.rate_limit().expect("rate_limit payload present");
23402            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
23403                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
23404            assert_eq!(
23405                parsed.window(),
23406                via_method,
23407                "codec parse arm on {wire:?} must resolve the window through \
23408                 RateLimitUnit::window_from_suffix, not a divergent path"
23409            );
23410        }
23411    }
23412
23413    #[test]
23414    fn rate_limit_unit_all_enumerates_every_arm_once() {
23415        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
23416        // enumerate every arm of the closed-set enum exactly once, in
23417        // the canonical shortest-to-longest window order (Second before
23418        // Minute before Hour) — the same order the sibling
23419        // [`crate::supervisor::RestartStrategy`] /
23420        // [`crate::supervisor::RestartPolicy`] /
23421        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
23422        // typed enums carry (the arm declared first is the arm listed
23423        // first). A future variant addition that extends the enum
23424        // without appending to [`RateLimitUnit::ALL`] leaves the
23425        // exhaustive iteration surface silently short one arm — the
23426        // codec's parse arm would then reject the new suffix even
23427        // though the enum knows it. This pin closes the drift.
23428        assert_eq!(
23429            super::RateLimitUnit::ALL,
23430            &[
23431                super::RateLimitUnit::Second,
23432                super::RateLimitUnit::Minute,
23433                super::RateLimitUnit::Hour,
23434            ],
23435            "RateLimitUnit::ALL must enumerate every arm exactly once, \
23436             in canonical shortest-to-longest window order"
23437        );
23438    }
23439
23440    #[test]
23441    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
23442        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
23443        // every arm's [`RateLimitUnit::as_suffix`] output must parse
23444        // back through [`RateLimitUnit::from_suffix`] to the same
23445        // variant. A future arm addition that lands `as_suffix` but
23446        // forgets `from_suffix` (`from_suffix` iterates
23447        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
23448        // is the load-bearing carrier of the round-trip; the sibling
23449        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
23450        // the `ALL` half) trips here at caixa-core build time rather
23451        // than surfacing as a codec round-trip miss (a `render` emit
23452        // that lands a suffix the paired `parse` cannot decode).
23453        for unit in super::RateLimitUnit::ALL {
23454            let suffix = unit.as_suffix();
23455            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
23456                panic!(
23457                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
23458                     RateLimitUnit::as_suffix output — got None for {unit:?}"
23459                )
23460            });
23461            assert_eq!(
23462                parsed, *unit,
23463                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
23464                 must return RateLimitUnit::{unit:?}"
23465            );
23466        }
23467    }
23468
23469    #[test]
23470    fn rate_limit_unit_from_window_and_window_round_trip() {
23471        // Total round-trip pin on the `(from_window, window)` pair:
23472        // every arm's [`RateLimitUnit::window`] output must parse back
23473        // through [`RateLimitUnit::from_window`] to the same variant.
23474        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
23475        // on the peer `Duration` axis — the two round-trip pins
23476        // together enshrine that both projections of the typed
23477        // canonical-unit bijection are total on the arm-set.
23478        for unit in super::RateLimitUnit::ALL {
23479            let window = unit.window();
23480            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
23481                panic!(
23482                    "RateLimitUnit::from_window({window:?}) must accept every \
23483                     RateLimitUnit::window output — got None for {unit:?}"
23484                )
23485            });
23486            assert_eq!(
23487                parsed, *unit,
23488                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
23489                 must return RateLimitUnit::{unit:?}"
23490            );
23491        }
23492    }
23493
23494    #[test]
23495    fn rate_limit_unit_from_window_accessor_is_const_fn() {
23496        // Fail-before-pass-after pin: witnesses the
23497        // [`RateLimitUnit::from_window`] `const`-eval posture via a
23498        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
23499        // -> Option<RateLimitUnit>` whose body calls
23500        // `RateLimitUnit::from_window(window)`, well-formed only when
23501        // the callee is itself `const fn` (any future downgrade to
23502        // non-`const` fails at caixa-core build time with E0015 `cannot
23503        // call non-const function`, strictly stronger than a runtime
23504        // `assert!`, side-stepping the destructor-in-const restriction
23505        // that blocks direct `const _: Option<RateLimitUnit> =
23506        // RateLimitUnit::from_window(...)` items on `Duration`'s
23507        // carrier). The runtime body sweeps every closed-set
23508        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
23509        // rejection sample (`Duration::from_millis(500)` sub-second
23510        // residue) and asserts the wrapped and direct dispatches agree
23511        // — a violation means the wrapper stopped compiling under a
23512        // future `const`-posture downgrade, or the reverse resolver's
23513        // arm-set silently split from the peer `Self::window` emitter's
23514        // arm-set. Peer of the sibling
23515        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
23516        // (152c868) /
23517        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
23518        // (152c868) /
23519        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
23520        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
23521        // `const`-eval-surface pins on the peer M2 / M3 substrate-
23522        // primitive `Copy`-return accessor axes, extended onto the
23523        // reverse `Duration → RateLimitUnit` projection axis on the
23524        // M3 mesh-slot rate-limit closed-set typed enum.
23525        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
23526            super::RateLimitUnit::from_window(window)
23527        }
23528        for unit in super::RateLimitUnit::ALL {
23529            let window = unit.window();
23530            let via_wrapper = from_window_via_const_fn(window);
23531            let direct = super::RateLimitUnit::from_window(window);
23532            assert_eq!(
23533                via_wrapper, direct,
23534                "RateLimitUnit::from_window({window:?}) via const fn \
23535                 wrapper must agree with direct dispatch for {unit:?}"
23536            );
23537            assert_eq!(
23538                via_wrapper,
23539                Some(*unit),
23540                "RateLimitUnit::from_window({window:?}) via const fn \
23541                 wrapper must return Some({unit:?}) for the peer \
23542                 window() output"
23543            );
23544        }
23545        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
23546        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
23547    }
23548
23549    #[test]
23550    fn rate_limit_unit_from_window_composes_through_window_accessor() {
23551        // Composition-witness pin on the routing-through-peer discipline:
23552        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
23553        // through the peer `pub const fn` [`RateLimitUnit::window`]
23554        // canonical-`Duration` projection rather than a hand-authored
23555        // per-arm second-magnitude literal — a future arm-magnitude edit
23556        // on the sibling `window()` accessor (a `Second → 2s` typo, a
23557        // `Hour → 3599s` off-by-one) must therefore reach this reverse
23558        // resolver by construction. A pin that hard-coded the three
23559        // second-magnitudes here would silently split from the peer
23560        // emitter on any such edit; instead, this pin asserts the
23561        // composition invariant `from_window(u.window()) == Some(u)`
23562        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
23563        // arm — a violation means either the peer `Self::window`
23564        // accessor drifted (breaking every downstream consumer that
23565        // reads through it), or the reverse resolver stopped routing
23566        // through the peer (introducing a hand-authored literal that
23567        // silently disagrees with the emitter). Either failure is a
23568        // caixa-core-build-time surface, not a downstream renderer
23569        // round-trip regression.
23570        //
23571        // Peer of the sibling
23572        // [`crate::render::assert_str_reexport_identity`] discipline on
23573        // the substrate-primitive `&'static str` re-export axis and the
23574        // [`rate_limit_unit_from_window_and_window_round_trip`]
23575        // round-trip pin on the peer projection direction; extends the
23576        // one-canonical-dispatch-per-projection discipline onto the
23577        // reverse-resolver's per-arm probe axis.
23578        for unit in super::RateLimitUnit::ALL {
23579            let window_via_peer = unit.window();
23580            let resolved = super::RateLimitUnit::from_window(window_via_peer);
23581            assert_eq!(
23582                resolved,
23583                Some(*unit),
23584                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
23585                 must return Some({unit:?}) — the reverse resolver's per-arm \
23586                 probes must route through the peer `Self::window` accessor \
23587                 so any future arm-magnitude edit reaches both projection \
23588                 directions by construction"
23589            );
23590        }
23591    }
23592
23593    #[test]
23594    fn rate_limit_canonical_unit_accessor_is_const_fn() {
23595        // Fail-before-pass-after pin: witnesses the
23596        // [`RateLimit::canonical_unit`] `const`-eval posture via a
23597        // `const fn` wrapper
23598        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
23599        // whose body calls `rl.canonical_unit()`, well-formed only when
23600        // the callee is itself `const fn` (any future downgrade to
23601        // non-`const` fails at caixa-core build time with E0015 `cannot
23602        // call non-const method`). The runtime body sweeps every
23603        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
23604        // constructs a typed [`RateLimit`] with the peer `Self::window`
23605        // canonical `Duration`, then asserts both the wrapper and the
23606        // direct dispatch agree and both return `Some(unit)`. Composes
23607        // with the sibling
23608        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
23609        // typed [`RateLimit`] projection layer's `const`-posture is
23610        // load-bearing on the reverse resolver's `const`-posture, and
23611        // both must migrate together (a downgrade of either surface
23612        // splits the paired `const`-eval-surface pass on the M3
23613        // mesh-slot rate-limit `Duration ↔ Self` bijection).
23614        const fn canonical_unit_via_const_fn(
23615            rl: &super::RateLimit,
23616        ) -> Option<super::RateLimitUnit> {
23617            rl.canonical_unit()
23618        }
23619        for unit in super::RateLimitUnit::ALL {
23620            let rl = super::RateLimit {
23621                rate: 1,
23622                window: unit.window(),
23623            };
23624            let via_wrapper = canonical_unit_via_const_fn(&rl);
23625            let direct = rl.canonical_unit();
23626            assert_eq!(
23627                via_wrapper, direct,
23628                "RateLimit::canonical_unit() via const fn wrapper must \
23629                 agree with direct dispatch for {unit:?}"
23630            );
23631            assert_eq!(
23632                via_wrapper,
23633                Some(*unit),
23634                "RateLimit::canonical_unit() via const fn wrapper must \
23635                 return Some({unit:?}) for a RateLimit whose window is \
23636                 the peer RateLimitUnit::{unit:?}.window() output"
23637            );
23638        }
23639    }
23640
23641    #[test]
23642    fn rate_limit_unit_projections_are_pairwise_distinct() {
23643        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
23644        // [`RateLimitUnit::window`] outputs must be pairwise distinct
23645        // across every arm — an accidental copy-paste flip that
23646        // reroutes one arm's suffix or window to also match another
23647        // silently collapses two arms onto one, so
23648        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
23649        // (both using `find` on `Self::ALL`) would return whichever
23650        // arm the linear scan lands on first — a match-arm-ordering-
23651        // dependent outcome the closed-set typed-enum shape is meant
23652        // to rule out structurally. Peer of the sibling
23653        // `caixa_kind_wire_consts_are_pairwise_distinct` /
23654        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
23655        // other closed-set typed-enum discriminator axes.
23656        let all = super::RateLimitUnit::ALL;
23657        for (i, a) in all.iter().enumerate() {
23658            for (j, b) in all.iter().enumerate() {
23659                if i != j {
23660                    assert_ne!(
23661                        a.as_suffix(),
23662                        b.as_suffix(),
23663                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
23664                         must be distinct — a collision silently collapses two \
23665                         arms onto one under from_suffix's linear scan"
23666                    );
23667                    assert_ne!(
23668                        a.window(),
23669                        b.window(),
23670                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
23671                         must be distinct — a collision silently collapses two \
23672                         arms onto one under from_window's linear scan"
23673                    );
23674                }
23675            }
23676        }
23677    }
23678
23679    #[test]
23680    fn rate_limit_unit_display_routes_through_as_suffix() {
23681        // Route pin: [`std::fmt::Display`] must byte-equal
23682        // [`RateLimitUnit::as_suffix`] on every arm — the single
23683        // source of truth for the canonical suffix. A future
23684        // reimplementation that hand-rolls the arms instead of
23685        // delegating to [`RateLimitUnit::as_suffix`] would silently
23686        // desynchronize `format!("{u}")` from the codec's parse arm
23687        // (which uses `as_suffix` to compare suffixes). Peer of the
23688        // sibling `caixa_kind_display_routes_through_as_str_helper` /
23689        // `placement_strategy_display_routes_through_as_str_helper`
23690        // pins on the peer closed-set typed-enum Display axes.
23691        for unit in super::RateLimitUnit::ALL {
23692            assert_eq!(
23693                unit.to_string(),
23694                unit.as_suffix(),
23695                "RateLimitUnit::{unit:?} Display must route through \
23696                 as_suffix (single source of truth: the canonical suffix \
23697                 the codec parses and renders)"
23698            );
23699        }
23700    }
23701
23702    #[test]
23703    fn rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor() {
23704        // Fail-before-pass-after byte-parity pin on the lifted
23705        // `impl AsRef<str> for RateLimitUnit` — asserts the standard-
23706        // library trait impl and the substrate-primitive
23707        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
23708        // resolve to the same `&str` per instance across the three-arm
23709        // closed set, so any future silent detour that routes the impl
23710        // through a divergent projection (a per-arm inline
23711        // `match self { RateLimitUnit::Second => "s", … }` re-inlining
23712        // that opens a compile-time link to the un-lifted arm-literal,
23713        // a swap onto the second-magnitude
23714        // [`super::RateLimitUnit::window`] axis that would collide the
23715        // canonical-suffix / token-bucket-refill two-axis split) trips
23716        // at caixa-core test time under `PartialEq` rather than at a
23717        // downstream `impl AsRef<str>`-bound consumer's silent split.
23718        // Sweeps every one of the three arms
23719        // [`super::RateLimitUnit::ALL`] carries so no arm's projection
23720        // is covered only by the sibling `Display` path. Peer of the
23721        // sibling
23722        // `placement_strategy_as_ref_str_routes_through_as_str_accessor`
23723        // (d86edd2) on the M3 mesh-placement closed-set typed enum,
23724        // and the peer
23725        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
23726        // (cd2091f) pin on the top-level closed-set typed
23727        // discriminator — the pins together close the substrate
23728        // primitive's `AsRef<str>` projection axis on every closed-set
23729        // typed enum with a `fmt::Display` surface across the M2 / M3
23730        // typed slots plus the top-level `:kind` + `:versao`
23731        // primitives.
23732        for &unit in super::RateLimitUnit::ALL {
23733            assert_eq!(
23734                <super::RateLimitUnit as AsRef<str>>::as_ref(&unit),
23735                unit.as_suffix(),
23736                "AsRef<str> impl on RateLimitUnit::{unit:?} must \
23737                 byte-equal RateLimitUnit::as_suffix on the same \
23738                 instance — divergence signals a silent detour off the \
23739                 substrate-primitive accessor"
23740            );
23741        }
23742    }
23743
23744    #[test]
23745    fn rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor() {
23746        // Fail-before-pass-after byte-parity pin on the three-path
23747        // convergence discipline the M3 `:politicas :rate-limit`
23748        // canonical-unit primitive now carries on the `&str`-projection
23749        // axis: `<RateLimitUnit as AsRef<str>>::as_ref(&v)` (the newly
23750        // lifted impl), `format!("{v}")` (the pre-existing
23751        // [`fmt::Display`] impl), and `v.as_suffix()` (the substrate-
23752        // primitive `pub const fn` accessor both trait impls delegate
23753        // through) must resolve to the same byte-string on every
23754        // instance across the three-arm closed set. Refuses any future
23755        // divergence between the two trait impls (a stray
23756        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
23757        // rather than delegating through the shared accessor; a
23758        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
23759        // literal cascade) that would silently split the two
23760        // projection paths of the same closed-set typed enum. Mirrors
23761        // the sibling three-path-convergence discipline the peer
23762        // [`super::PlacementStrategy`] typed enum carries
23763        // (`placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
23764        // d86edd2), the peer [`crate::CaixaKind`] triple
23765        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
23766        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
23767        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
23768        // 16d5c7e).
23769        for &unit in super::RateLimitUnit::ALL {
23770            let via_as_ref: &str = <super::RateLimitUnit as AsRef<str>>::as_ref(&unit);
23771            let via_display: String = format!("{unit}");
23772            let via_accessor: &str = unit.as_suffix();
23773            assert_eq!(via_as_ref, via_accessor);
23774            assert_eq!(via_display, via_accessor);
23775            assert_eq!(via_as_ref, via_display.as_str());
23776        }
23777    }
23778
23779    #[test]
23780    fn rate_limit_unit_from_window_rejects_non_canonical() {
23781        // Rejection pin on the parser's accept-set: any Duration
23782        // outside the three-arm [`RateLimitUnit::window`] output set
23783        // (sub-second residue, or a second-magnitude outside `{1, 60,
23784        // 3600}`) must return `None`. A future accidental widening of
23785        // the accept-set (rounding down sub-second residue to the
23786        // nearest arm, admitting `Duration::from_secs(30)` as a
23787        // half-minute unit) would silently drift the parser's accept-
23788        // set from the emitter's — a validated slot with a
23789        // non-canonical window would then round-trip through the
23790        // codec to a canonical form the author never wrote.
23791        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
23792        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
23793        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
23794        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
23795        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
23796        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
23797        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
23798    }
23799
23800    #[test]
23801    fn rate_limit_unit_from_suffix_rejects_unknown() {
23802        // Rejection pin on the suffix parser's accept-set: any string
23803        // outside the three-arm [`RateLimitUnit::as_suffix`] output
23804        // set must return `None`. Peer of the sibling
23805        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
23806        // the [`crate::CaixaKind`] `from_wire` accept-set.
23807        for bad in [
23808            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
23809            " s",
23810        ] {
23811            assert!(
23812                super::RateLimitUnit::from_suffix(bad).is_none(),
23813                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
23814                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
23815                 outputs"
23816            );
23817        }
23818    }
23819
23820    #[test]
23821    fn rate_limit_unit_try_from_str_routes_through_from_suffix_accessor() {
23822        // Fail-before-pass-after byte-parity pin on the newly lifted
23823        // `impl TryFrom<&str> for RateLimitUnit` — asserts the standard-
23824        // library trait impl and the substrate-primitive
23825        // [`super::RateLimitUnit::from_suffix`] `Option<Self>` accessor
23826        // resolve to the same three-arm accept-set across every arm the
23827        // exhaustive [`super::RateLimitUnit::ALL`] slice enumerates. Any
23828        // future silent detour that routes the trait impl through a
23829        // divergent projection (a per-arm inline
23830        // `match s { "s" => Ok(Self::Second), … }` re-inlining that
23831        // opens a compile-time link to the un-lifted arm-literal, a
23832        // silent case-fold that admits `"S"` / `"M"` / `"H"` and would
23833        // collide the canonical-suffix accept-set the codec's parse arm
23834        // dispatches on) trips at caixa-core test time under
23835        // `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
23836        // bound consumer's silent split. Sweeps every one of the three
23837        // arms [`super::RateLimitUnit::ALL`] carries so no arm's
23838        // projection is covered only by the sibling method-named
23839        // `from_suffix` path. Peer of the sibling
23840        // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
23841        // (3c83606),
23842        // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
23843        // (bf33136), and
23844        // `placement_strategy_try_from_str_routes_through_from_wire_accessor`
23845        // (6fd00cd) — extends the trait-idiomatic reverse-projection
23846        // axis onto the third M3-mesh-primitive-defining slot enum on
23847        // the caixa surface (the `:politicas :rate-limit` unit-suffix
23848        // closed set the caixa-mesh renderer keys off end-to-end).
23849        for &unit in super::RateLimitUnit::ALL {
23850            let suffix = unit.as_suffix();
23851            assert_eq!(
23852                <super::RateLimitUnit as TryFrom<&str>>::try_from(suffix),
23853                Ok(unit),
23854                "TryFrom<&str> impl on RateLimitUnit must round-trip \
23855                 RateLimitUnit::{unit:?}.as_suffix() = {suffix:?} back to \
23856                 Ok(RateLimitUnit::{unit:?}) — divergence from \
23857                 RateLimitUnit::from_suffix signals a silent detour off \
23858                 the substrate-primitive accessor"
23859            );
23860            assert_eq!(
23861                <super::RateLimitUnit as TryFrom<&str>>::try_from(suffix).ok(),
23862                super::RateLimitUnit::from_suffix(suffix),
23863                "TryFrom<&str> ok()-projection on {suffix:?} must \
23864                 byte-equal RateLimitUnit::from_suffix on the same input"
23865            );
23866        }
23867    }
23868
23869    #[test]
23870    fn rate_limit_unit_try_from_str_rejects_unknown_byte_strings() {
23871        // Rejection witness on the `impl TryFrom<&str> for RateLimitUnit`
23872        // — sweeps a candidate set of byte-strings outside the three-arm
23873        // canonical-suffix wire accept-set the sibling
23874        // [`super::RateLimitUnit::as_suffix`] emits and asserts every
23875        // one lands on `Err(())`, so a future accidental widening of the
23876        // trait impl's accept-set (a stray additional
23877        // `_ if s.eq_ignore_ascii_case("s") => Ok(…)` case-fold path, a
23878        // silent inclusion of a long-form English rebrand of the
23879        // canonical suffix like `"second"` / `"minute"` / `"hour"` that
23880        // would collide the one-letter-suffix discipline the sibling
23881        // [`super::RateLimitUnit::from_suffix`] carries, a silent
23882        // acceptance of the `"1s"` / `"1m"` / `"1h"` full-rate-limit
23883        // shape that would collide the codec-composed `<n>/<unit>` axis
23884        // onto the unit-suffix axis) trips at caixa-core test time. The
23885        // candidate set includes the empty string, whitespace-only
23886        // padding, uppercase rebrand candidates, long-form English
23887        // rebrand candidates (`"second"`, `"minute"`, `"hour"`),
23888        // trailing/leading-whitespace-padded canonical suffixes,
23889        // sub-second and multi-day trajectory-item candidates
23890        // (`"ms"`, `"d"`, `"week"`), digits-prefixed shapes that would
23891        // collide with the `<n>/<unit>` parent codec, the quoted-shape
23892        // (`"\"s\""`) that would signal a stray serde-quote survival,
23893        // and the `"?"` sentinel. Peer of the sibling
23894        // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
23895        // (3c83606) rejection witness, and
23896        // `placement_strategy_try_from_str_rejects_unknown_byte_strings`
23897        // (6fd00cd).
23898        let rejected: &[&str] = &[
23899            "", " ", "\n", "\t", "S", "M", "H", "s ", " s", "m ", " h", "s\n", "second", "minute",
23900            "hour", "sec", "min", "hr", "d", "ms", "ns", "us", "week", "1s", "1m", "1h", "100/s",
23901            "s/", "?", "\"s\"",
23902        ];
23903        for &input in rejected {
23904            assert_eq!(
23905                <super::RateLimitUnit as TryFrom<&str>>::try_from(input),
23906                Err(()),
23907                "TryFrom<&str> impl on RateLimitUnit must reject the \
23908                 non-suffix byte-string {input:?} — silent acceptance \
23909                 signals an accept-set widening off the paired \
23910                 RateLimitUnit::from_suffix resolver"
23911            );
23912        }
23913    }
23914
23915    #[test]
23916    fn rate_limit_unit_try_from_str_and_from_suffix_partition_the_accept_set() {
23917        // Cross-axis partition pin on the two `str → Option<Self>` /
23918        // `str → Result<Self, ()>` projections on
23919        // [`super::RateLimitUnit`]: the trait-idiomatic
23920        // [`TryFrom<&str>`] axis (newly lifted) and the method-named
23921        // [`super::RateLimitUnit::from_suffix`] axis (pre-existing) must
23922        // partition every input into the same accept-set / reject-set
23923        // — a `TryFrom<&str>` `Ok(v)` outcome iff `from_suffix` returns
23924        // `Some(v)`, and a `TryFrom<&str>` `Err(())` outcome iff
23925        // `from_suffix` returns `None`. Sweeps a mixed input set of
23926        // canonical accepts + rejections so any future divergence
23927        // between the two projection paths (a hand-rolled `try_from`
23928        // rewrite that no longer routes through `from_suffix`, a
23929        // hypothetical `from_suffix` widening that admits a byte-string
23930        // the trait impl still rejects) surfaces here at caixa-core
23931        // test time rather than at a downstream consumer's silent
23932        // split. Peer of the sibling
23933        // `wit_shape_try_from_str_and_from_wire_partition_the_accept_set`
23934        // (5472902) cross-axis partition pin on the sibling M3-mesh-
23935        // primitive closed-set typed enum.
23936        let inputs: &[&str] = &[
23937            "s", "m", "h", "", " ", "S", "second", "d", "ms", "1s", "?", "\"s\"", "sec",
23938        ];
23939        for &input in inputs {
23940            let via_try_from: Option<super::RateLimitUnit> =
23941                <super::RateLimitUnit as TryFrom<&str>>::try_from(input).ok();
23942            let via_from_suffix: Option<super::RateLimitUnit> =
23943                super::RateLimitUnit::from_suffix(input);
23944            assert_eq!(
23945                via_try_from, via_from_suffix,
23946                "TryFrom<&str> and from_suffix must partition the \
23947                 accept-set identically on input {input:?} — got \
23948                 TryFrom = {via_try_from:?}, from_suffix = {via_from_suffix:?}"
23949            );
23950        }
23951    }
23952
23953    #[test]
23954    fn rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor() {
23955        // Fail-before-pass-after byte-parity pin on the newly lifted
23956        // `impl From<RateLimitUnit> for &'static str` — asserts the
23957        // standard-library trait impl and the substrate-primitive
23958        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
23959        // resolve to the same three-arm canonical-suffix emit-set across
23960        // every arm the exhaustive [`super::RateLimitUnit::ALL`] slice
23961        // enumerates. Any future silent detour that routes the trait
23962        // impl through a divergent projection (a per-arm inline
23963        // `match unit { Second => "s", … }` re-inlining that opens a
23964        // compile-time link to the un-lifted arm-literal outside the
23965        // paired [`super::RateLimitUnit::as_suffix`] dispatch, a swap
23966        // onto the second-magnitude [`super::RateLimitUnit::window`]
23967        // axis that would collide the canonical-suffix /
23968        // token-bucket-refill two-axis split) trips at caixa-core test
23969        // time under `assert_eq!` rather than at a downstream
23970        // `impl Into<&'static str>`-bound consumer's silent split.
23971        // Sweeps every one of the three arms
23972        // [`super::RateLimitUnit::ALL`] carries so no arm's projection
23973        // is covered only by the sibling method-named `as_suffix` /
23974        // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
23975        // `<&'static str as From<RateLimitUnit>>::from` output in three
23976        // `const`-shape bindings against the paired
23977        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
23978        // make the `'static` lifetime promise a build-time invariant —
23979        // a future accidental downgrade of any of the three arms'
23980        // inline canonical-suffix byte-strings to a non-`&'static str`
23981        // (a `String::leak()`-produced return, a `Box::leak`-cast, an
23982        // intermediate lifetime-erasing helper) trips at caixa-core
23983        // build time rather than at a downstream `'static`-bound
23984        // consumer.
23985        //
23986        // Peer of the sibling
23987        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
23988        // (523157d),
23989        // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
23990        // (9fb37d0),
23991        // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
23992        // (edb827b),
23993        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
23994        // (c189a6f),
23995        // [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
23996        // (afa3562), and
23997        // [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
23998        // (56998ec) pins on the sibling closed-set typed-enum forward-
23999        // projection axes — extends the trait-idiomatic forward-
24000        // projection axis onto the seventh closed-set fieldless typed
24001        // enum on the caixa surface (the third M3-mesh-primitive-
24002        // defining slot enum, the `:politicas :rate-limit`
24003        // canonical-suffix axis the caixa-mesh renderer keys off end-
24004        // to-end for per-Aplicacao Envoy
24005        // `local_rate_limit.token_bucket.fill_interval` overlay
24006        // emission).
24007        const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
24008        const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
24009        const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
24010        for &unit in super::RateLimitUnit::ALL {
24011            let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
24012            let via_method: &'static str = unit.as_suffix();
24013            assert_eq!(
24014                via_trait, via_method,
24015                "From<RateLimitUnit> for &'static str impl must \
24016                 round-trip RateLimitUnit::{unit:?} to the same \
24017                 canonical-suffix byte-string RateLimitUnit::as_suffix \
24018                 returns — divergence signals a silent detour off the \
24019                 substrate-primitive accessor"
24020            );
24021            let via_into: &'static str = unit.into();
24022            assert_eq!(
24023                via_into, via_method,
24024                "Into<&'static str>::into on RateLimitUnit::{unit:?} \
24025                 must byte-equal RateLimitUnit::as_suffix on the same \
24026                 input — the blanket-derived Into shape must resolve to \
24027                 the same as_suffix dispatch as the explicit From impl"
24028            );
24029        }
24030        assert_eq!(
24031            [SECOND, MINUTE, HOUR],
24032            ["s", "m", "h"],
24033            "const-context RateLimitUnit::as_suffix must resolve to the \
24034             three canonical-suffix byte-strings — a future accidental \
24035             downgrade of any arm to a non-const or non-static \
24036             byte-string breaks the `&'static str`-lifetime promise the \
24037             paired From<RateLimitUnit> for &'static str impl carries \
24038             by construction"
24039        );
24040    }
24041
24042    #[test]
24043    fn rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set() {
24044        // Cross-axis partition pin: the paired trait-idiomatic
24045        // `From<RateLimitUnit> for &'static str` forward projection and
24046        // the method-named [`super::RateLimitUnit::as_suffix`] forward
24047        // projection must resolve identically on *every* arm, not just
24048        // the ones named in the primary byte-parity pin above. Sweeps
24049        // every [`super::RateLimitUnit::ALL`] arm and asserts the
24050        // trait's `From::from` output byte-equals the method-named
24051        // accessor's return-value on each, locking the two forward-
24052        // projection paths together by construction so any future
24053        // detour (a stray `From` special-case that lands on a divergent
24054        // per-arm literal outside the paired `as_suffix` dispatch, a
24055        // hypothetical rebrand touching one axis without the other)
24056        // trips at caixa-core test time.
24057        //
24058        // Peer of the sibling forward-projection partition pins
24059        // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
24060        // (523157d),
24061        // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
24062        // (9fb37d0),
24063        // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
24064        // (edb827b),
24065        // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
24066        // (c189a6f),
24067        // [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
24068        // (afa3562), and
24069        // [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
24070        // (56998ec) — extends the round-trip discipline onto the seventh
24071        // closed-set typed enum on the caixa surface, closing the two-
24072        // way `Self ↔ &'static str` round-trip on the trait-idiomatic
24073        // pair (`From<Self> for &'static str` + `TryFrom<&str> for
24074        // Self`) as well as the pre-existing method-named pair
24075        // (`as_suffix` + `from_suffix`).
24076        for &unit in super::RateLimitUnit::ALL {
24077            let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
24078            let via_method: &'static str = unit.as_suffix();
24079            assert_eq!(
24080                via_trait, via_method,
24081                "From<RateLimitUnit> for &'static str and \
24082                 RateLimitUnit::as_suffix must resolve identically on \
24083                 RateLimitUnit::{unit:?} — divergence signals the two \
24084                 forward-projection paths have drifted onto different \
24085                 emit-sets"
24086            );
24087        }
24088        // Round-trip witness: every arm's forward `From` output re-parses
24089        // through the paired trait-idiomatic reverse `TryFrom<&str>` back
24090        // to the original variant. Closes the two-way `RateLimitUnit ↔
24091        // &'static str` round-trip on the trait-idiomatic axis pair
24092        // directly (no wire-vocab intermediate the peer [`CaixaKind`]
24093        // axis pair requires — the emit-side
24094        // [`super::RateLimitUnit::as_suffix`] and the parse-side
24095        // [`super::RateLimitUnit::from_suffix`] dispatch on the same
24096        // three inline canonical-suffix byte-strings by construction),
24097        // mirroring the pre-existing method-named `as_suffix` +
24098        // `from_suffix` round-trip on the substrate-primitive axis pair
24099        // and the peer [`super::WitShape`] round-trip (56998ec) on the
24100        // sibling M3-mesh-primitive-defining slot enum.
24101        for &unit in super::RateLimitUnit::ALL {
24102            let emitted: &'static str = unit.into();
24103            let re_parsed: Result<super::RateLimitUnit, ()> =
24104                <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
24105            assert_eq!(
24106                re_parsed,
24107                Ok(unit),
24108                "trait-idiomatic axis pair must round-trip \
24109                 RateLimitUnit::{unit:?} through `.into::<&'static \
24110                 str>()` and back through `TryFrom<&str>` — a break \
24111                 signals the forward-emit and reverse-parse axes have \
24112                 drifted onto different vocabularies"
24113            );
24114        }
24115    }
24116
24117    #[test]
24118    fn rate_limit_unit_from_borrowed_into_static_str_routes_through_as_suffix_accessor() {
24119        // Fail-before-pass-after byte-parity pin on the newly lifted
24120        // `impl From<&RateLimitUnit> for &'static str` — asserts the
24121        // borrowed-input standard-library trait impl and the substrate-
24122        // primitive [`super::RateLimitUnit::as_suffix`] `pub const fn`
24123        // accessor resolve to the same three-arm canonical-suffix
24124        // emit-set across every arm the exhaustive
24125        // [`super::RateLimitUnit::ALL`] slice enumerates. Rust's `From`
24126        // trait does not auto-derive the borrowed-input sibling from a
24127        // paired owned-input impl (no `impl<T, U> From<&T> for U where
24128        // T: Copy, U: From<T>` blanket in `core`), so the borrowed-input
24129        // axis is a distinct trait-idiomatic surface that a
24130        // `.iter().map(Into::into)` shape over
24131        // [`super::RateLimitUnit::ALL`] (whose iterator yields
24132        // `&RateLimitUnit`, not `RateLimitUnit`) reaches through this
24133        // impl and no other — the paired owned-input
24134        // [`From<RateLimitUnit>`] impl requires an explicit `.copied()`
24135        // / dereference before the trait fires. Materializes the
24136        // `<&'static str as From<&RateLimitUnit>>::from` output in three
24137        // `const`-shape bindings against the paired
24138        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
24139        // make the `'static` lifetime promise a build-time invariant —
24140        // a future accidental downgrade of any of the three arms'
24141        // inline canonical-suffix byte-strings to a non-`&'static str`
24142        // (a `String::leak()`-produced return, a `Box::leak`-cast, an
24143        // intermediate lifetime-erasing helper) trips at caixa-core
24144        // build time rather than at a downstream `'static`-bound
24145        // consumer.
24146        //
24147        // Peer of the sibling
24148        // [`crate::dep::tests::dep_list_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24149        // (64aa742),
24150        // [`crate::kind::tests::caixa_kind_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24151        // (5ab993a),
24152        // [`crate::dialeto::tests::caixa_dialeto_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24153        // (807b0b5),
24154        // [`crate::supervisor::tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24155        // (e941836),
24156        // [`crate::supervisor::tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24157        // (842c7f3),
24158        // [`tests::placement_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24159        // (4d941d8), and
24160        // [`tests::wit_shape_from_borrowed_into_static_str_routes_through_as_str_accessor`]
24161        // (3187bd0) pins on the sibling closed-set typed-enum
24162        // borrowed-input forward-projection axes — extends the
24163        // borrowed-input axis onto the third (and last) M3-mesh-
24164        // primitive-defining closed-set typed enum on the caixa surface
24165        // (the `:politicas :rate-limit` canonical-suffix axis the
24166        // caixa-mesh renderer keys off end-to-end for per-Aplicacao
24167        // Envoy `local_rate_limit.token_bucket.fill_interval` overlay
24168        // emission).
24169        const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
24170        const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
24171        const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
24172        for unit in super::RateLimitUnit::ALL {
24173            let via_trait: &'static str = <&'static str as From<&super::RateLimitUnit>>::from(unit);
24174            let via_method: &'static str = unit.as_suffix();
24175            assert_eq!(
24176                via_trait, via_method,
24177                "From<&RateLimitUnit> for &'static str impl must \
24178                 round-trip &RateLimitUnit::{unit:?} to the same \
24179                 canonical-suffix byte-string RateLimitUnit::as_suffix \
24180                 returns — divergence signals a silent detour off the \
24181                 substrate-primitive accessor"
24182            );
24183            let via_into: &'static str = unit.into();
24184            assert_eq!(
24185                via_into, via_method,
24186                "Into<&'static str>::into on &RateLimitUnit::{unit:?} \
24187                 must byte-equal RateLimitUnit::as_suffix on the same \
24188                 input — the blanket-derived Into shape must resolve to \
24189                 the same as_suffix dispatch as the explicit From impl"
24190            );
24191        }
24192        assert_eq!(
24193            [SECOND, MINUTE, HOUR],
24194            ["s", "m", "h"],
24195            "const-context RateLimitUnit::as_suffix must resolve to the \
24196             three canonical-suffix byte-strings — the borrowed-input \
24197             From<&RateLimitUnit> for &'static str impl inherits its \
24198             `'static` lifetime promise from the same accessor the \
24199             owned-input sibling routes through"
24200        );
24201    }
24202
24203    #[test]
24204    fn rate_limit_unit_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
24205        // Cross-axis partition pin: the paired trait-idiomatic
24206        // owned-input `From<RateLimitUnit> for &'static str` (7fdfbf4
24207        // campaign-shape) and borrowed-input `From<&RateLimitUnit> for
24208        // &'static str` (this lift) forward projections must resolve
24209        // identically on every arm, locking the two input-shape paths
24210        // together so any future detour trips at caixa-core test time.
24211        // Then a witness that a `.iter().map(Into::into)` pipe over
24212        // [`super::RateLimitUnit::ALL`] (whose iterator yields
24213        // `&RateLimitUnit`) materializes the three-arm accept-set
24214        // through the borrowed-input axis alone — the exact shape a
24215        // future M4 admission-webhook rejection body's accepted-set
24216        // enumeration, a future substrate-wide per-arm diagnostic
24217        // column, or a `HashMap::<&'static str,
24218        // RateLimitUnit>::from_iter(RateLimitUnit::ALL.iter().map(|u|
24219        // (u.into(), *u)))`-style per-unit lookup reaches through —
24220        // closing the two-way owned/borrowed input-shape symmetry on
24221        // the M3 slot enum's forward-projection trait-idiomatic axis.
24222        // Peer of the sibling
24223        // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24224        // (64aa742),
24225        // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24226        // (5ab993a),
24227        // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24228        // (807b0b5),
24229        // [`crate::supervisor::tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24230        // (e941836),
24231        // [`crate::supervisor::tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24232        // (842c7f3),
24233        // [`tests::placement_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24234        // (4d941d8), and
24235        // [`tests::wit_shape_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
24236        // (3187bd0) partition pins on the sibling closed-set typed-enum
24237        // discriminator axes — extends the borrowed-input axis
24238        // discipline onto the third (and last) M3-mesh-primitive-
24239        // defining closed-set typed enum on the caixa surface (the
24240        // `:politicas :rate-limit` canonical-suffix axis). Also closes
24241        // the direct two-way `&Self → &'static str → Self` round-trip
24242        // via the paired [`TryFrom<&str>`] axis — unlike the peer
24243        // [`crate::CaixaKind`] axis pair (whose forward `From` emits
24244        // lowercase Portuguese diagnostic bytes while the reverse
24245        // `TryFrom` parses `PascalCase` wire bytes, forcing the
24246        // round-trip through an intermediate wire-vocab hop), the
24247        // [`super::RateLimitUnit::as_suffix`] emit and
24248        // [`super::RateLimitUnit::from_suffix`] parse share the same
24249        // three inline canonical-suffix byte-strings by construction,
24250        // so the borrowed-input forward axis and the reverse axis
24251        // compose directly.
24252        for &unit in super::RateLimitUnit::ALL {
24253            let owned: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
24254            let borrowed: &'static str = <&'static str as From<&super::RateLimitUnit>>::from(&unit);
24255            assert_eq!(
24256                owned, borrowed,
24257                "From<RateLimitUnit> and From<&RateLimitUnit> for \
24258                 &'static str must resolve identically on \
24259                 RateLimitUnit::{unit:?} — divergence signals the \
24260                 owned-input and borrowed-input forward-projection paths \
24261                 have drifted onto different emit-sets"
24262            );
24263        }
24264        let via_iter: Vec<&'static str> =
24265            super::RateLimitUnit::ALL.iter().map(Into::into).collect();
24266        let via_method: Vec<&'static str> = super::RateLimitUnit::ALL
24267            .iter()
24268            .map(|u| u.as_suffix())
24269            .collect();
24270        assert_eq!(
24271            via_iter, via_method,
24272            "`.iter().map(Into::into)` over RateLimitUnit::ALL must \
24273             byte-equal `.iter().map(|u| u.as_suffix())` on every arm — \
24274             the borrowed-input `From<&RateLimitUnit> for &'static str` \
24275             axis is what makes the `.iter().map(Into::into)` shape \
24276             route through the substrate-primitive \
24277             RateLimitUnit::as_suffix accessor rather than through a \
24278             per-call-site `.copied()` / dereference detour"
24279        );
24280        for unit in super::RateLimitUnit::ALL {
24281            let emitted: &'static str = unit.into();
24282            let re_parsed: Result<super::RateLimitUnit, ()> =
24283                <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
24284            assert_eq!(
24285                re_parsed,
24286                Ok(*unit),
24287                "trait-idiomatic borrowed-input forward-projection + \
24288                 reverse-projection axis pair must round-trip \
24289                 &RateLimitUnit::{unit:?} through `.into::<&'static \
24290                 str>()` (via the borrowed-input axis) and back through \
24291                 `TryFrom<&str>` — a break signals the borrowed-input \
24292                 forward-emit and reverse-parse axes have drifted onto \
24293                 different vocabularies"
24294            );
24295        }
24296    }
24297
24298    #[test]
24299    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
24300        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
24301        // every canonical `:window` magnitude the validate gate
24302        // accepts must map to the paired [`RateLimitUnit`] arm through
24303        // this accessor. A future validate-gate rebrand that widened
24304        // the accepted-window set without extending [`RateLimitUnit`]
24305        // would silently split the accessor's `Some`-return set from
24306        // the validate gate's accept-set — a slot that satisfies
24307        // validate would land at the accessor with `None`, so a
24308        // consumer past validate that pattern-matches on the returned
24309        // `Some` would silently miss the newly-accepted magnitude.
24310        for (window_secs, expected) in [
24311            (1u64, super::RateLimitUnit::Second),
24312            (60, super::RateLimitUnit::Minute),
24313            (3600, super::RateLimitUnit::Hour),
24314        ] {
24315            let rl = RateLimit {
24316                rate: 100,
24317                window: Duration::from_secs(window_secs),
24318            };
24319            assert_eq!(
24320                rl.canonical_unit(),
24321                Some(expected),
24322                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
24323                 must return Some({expected:?})"
24324            );
24325        }
24326        // Non-canonical windows the validate gate rejects also return
24327        // None here — the accessor is the typed-enum projection of
24328        // the sibling `is_canonical_rate_limit_window` predicate.
24329        let bad = RateLimit {
24330            rate: 100,
24331            window: Duration::from_secs(30),
24332        };
24333        assert!(
24334            bad.canonical_unit().is_none(),
24335            "RateLimit with a non-canonical window must return None from \
24336             canonical_unit — the validate gate rejects the same set"
24337        );
24338    }
24339
24340    #[test]
24341    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
24342        // Fail-before-pass-after byte-parity pin: for every canonical
24343        // window the [`rate_limit_codec::render`] arm's emitted string
24344        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
24345        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
24346        // the vestigial free helper [`rate_limit_window_unit`] (a
24347        // `find_map`-walked `Duration → &'static str` delegate) onto the
24348        // substrate primitive [`RateLimit::canonical_unit`] typed method
24349        // (a closed-set `match self.window` arm on
24350        // [`RateLimitUnit::from_window`], projected through
24351        // [`RateLimitUnit::as_suffix`] via the enum's
24352        // [`std::fmt::Display`] impl). A future re-routing of the render
24353        // arm through a differently-computed unit projection would break
24354        // this pin at build time rather than as a silent per-consumer
24355        // codec round-trip drift far from the substrate primitive edit.
24356        //
24357        // Sibling to the peer
24358        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
24359        // on the free-helper axis: that pin locks the two projections
24360        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
24361        // on the closed-set arm table; this pin locks the codec's render
24362        // arm reads through the typed accessor rather than the free
24363        // helper. Two production consumers of the canonical-unit axis
24364        // now key off one typed dispatch on the substrate primitive.
24365        for (window_secs, unit) in [
24366            (1u64, super::RateLimitUnit::Second),
24367            (60, super::RateLimitUnit::Minute),
24368            (3600, super::RateLimitUnit::Hour),
24369        ] {
24370            let rl = RateLimit {
24371                rate: 42,
24372                window: Duration::from_secs(window_secs),
24373            };
24374            let policy = MeshPolicy {
24375                rate_limit: Some(rl),
24376                ..Default::default()
24377            };
24378            let json = serde_json::to_string(&policy).unwrap();
24379            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
24380            assert!(
24381                json.contains(&expected),
24382                "rate_limit_codec::render must emit {expected} (via \
24383                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
24384                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
24385            );
24386            // And the accessor route resolves to the same typed unit
24387            // the render arm's Display formatting is asked to produce —
24388            // so a future edit that split the two paths (one through
24389            // the accessor, one through a re-introduced free helper)
24390            // trips this pin.
24391            assert_eq!(
24392                rl.canonical_unit(),
24393                Some(unit),
24394                "RateLimit::canonical_unit must return Some({unit:?}) for a \
24395                 {window_secs}s window; the codec render arm reads the same \
24396                 typed unit through this accessor"
24397            );
24398        }
24399    }
24400
24401    #[test]
24402    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
24403        // Fail-before-pass-after byte-parity pin on the validate gate's
24404        // canonical-window shape probe: every non-canonical `:window`
24405        // the free-helper predicate [`is_canonical_rate_limit_window`]
24406        // rejects is also rejected by the substrate primitive
24407        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
24408        // gate now reads through, and vice versa on the accepted set
24409        // (the three canonical windows). Locks the migration from the
24410        // free helper onto the substrate primitive: a future re-routing
24411        // of one of the two paths through a differently-computed unit
24412        // projection would silently split the codec's accepted set from
24413        // the validate gate's accepted set — a two-consumer drift the
24414        // codec-round-trip pin
24415        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
24416        // above closes on the render arm and this pin closes on the
24417        // validate arm.
24418        for canonical_window_secs in [1u64, 60, 3600] {
24419            let mut s = three_member_spec();
24420            let rl = RateLimit {
24421                rate: 100,
24422                window: Duration::from_secs(canonical_window_secs),
24423            };
24424            s.politicas.rate_limit = Some(rl);
24425            assert!(
24426                s.validate().is_ok(),
24427                "canonical {canonical_window_secs}s window must pass \
24428                 validate_politicas — the validate gate now reads \
24429                 RateLimit::canonical_unit().is_none() and the accessor \
24430                 returns Some on every canonical arm"
24431            );
24432            assert!(
24433                rl.canonical_unit().is_some(),
24434                "canonical {canonical_window_secs}s window must resolve to \
24435                 Some on RateLimit::canonical_unit — the validate gate reads \
24436                 this accessor directly"
24437            );
24438        }
24439        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
24440            let mut s = three_member_spec();
24441            let rl = RateLimit {
24442                rate: 100,
24443                window: Duration::from_secs(non_canonical_window_secs),
24444            };
24445            s.politicas.rate_limit = Some(rl);
24446            assert_eq!(
24447                s.validate().unwrap_err(),
24448                AplicacaoError::PolicyRateLimitWindowNotCanonical {
24449                    window: rl.window(),
24450                },
24451                "non-canonical {non_canonical_window_secs}s window must be \
24452                 rejected by validate_politicas — the validate gate now \
24453                 keys off RateLimit::canonical_unit().is_none()"
24454            );
24455            assert!(
24456                rl.canonical_unit().is_none(),
24457                "non-canonical {non_canonical_window_secs}s window must \
24458                 resolve to None on RateLimit::canonical_unit — the two \
24459                 paths (the free helper the validate gate previously read \
24460                 and the substrate primitive the validate gate now reads) \
24461                 must agree on the same rejected set"
24462            );
24463        }
24464        // And the substrate-primitive [`RateLimit::canonical_unit`]
24465        // accessor's accepted-window set matches the codec's parse arm's
24466        // accepted-suffix set on every canonical / non-canonical shape,
24467        // so a future silent drift between the codec's accepted set and
24468        // the validate gate's accepted set is a build error at test time
24469        // (both consumers key off the same closed-set enum's `match self`
24470        // arms). The predecessor free helper `is_canonical_rate_limit_window`
24471        // — a delegate that composed [`RateLimitUnit::from_window`] with
24472        // `.is_some()` — was deleted after this migration; the
24473        // canonical-window set now lives on exactly one typed dispatch
24474        // on the substrate primitive.
24475        for (secs, expected) in [
24476            (1u64, true),
24477            (60, true),
24478            (3600, true),
24479            (2, false),
24480            (30, false),
24481            (86_400, false),
24482        ] {
24483            let window = Duration::from_secs(secs);
24484            let rl = RateLimit { rate: 1, window };
24485            assert_eq!(
24486                rl.canonical_unit().is_some(),
24487                expected,
24488                "RateLimit::canonical_unit().is_some() must agree with the \
24489                 codec-accepted canonical-window set on {secs}s"
24490            );
24491            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
24492                1 => "s",
24493                60 => "m",
24494                3600 => "h",
24495                _ => return,
24496            })
24497            .is_some_and(|d| d == window);
24498            if expected {
24499                assert!(
24500                    suffix_from_axis,
24501                    "the codec's `&str → Duration` axis \
24502                     ({secs}s) must round-trip to the same Duration the \
24503                     substrate primitive's accessor returns Some on"
24504                );
24505            }
24506        }
24507    }
24508
24509    #[test]
24510    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
24511        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
24512        // derive: for each of the three variants, exactly one of the
24513        // generated `is_second` / `is_minute` / `is_hour` predicates
24514        // returns `true` and the other two return `false`. Peer of
24515        // the sibling
24516        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
24517        // sibling `IsVariant`-derived closed-set typed-enum pins.
24518        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
24519            (super::RateLimitUnit::Second, [true, false, false]),
24520            (super::RateLimitUnit::Minute, [false, true, false]),
24521            (super::RateLimitUnit::Hour, [false, false, true]),
24522        ];
24523        for (variant, expected) in rows {
24524            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
24525            assert_eq!(
24526                observed, expected,
24527                "RateLimitUnit::{variant:?} is_* predicates must partition \
24528                 the arm set (second, minute, hour); got {observed:?}"
24529            );
24530        }
24531    }
24532
24533    #[test]
24534    fn rejects_policy_timeout_sub_millisecond() {
24535        // A purely sub-millisecond `Duration` (`from_micros(500)` =
24536        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
24537        // arm passes — but `as_millis() == 0`, so the shared codec's
24538        // `render` arm returns the literal `"0s"`, which the
24539        // codec's `parse` arm then deserializes as `Duration::ZERO`
24540        // and the `PolicyTimeoutZero` zero-floor gate would reject
24541        // on re-validate. Pin the rejection at the typed slot's
24542        // canonical-floor gate so the round-trip break surfaces at
24543        // validate time, naming the offending `Duration`, rather
24544        // than at the next serialize → deserialize round-trip far
24545        // from the source `caixa.lisp`.
24546        let mut s = three_member_spec();
24547        let timeout = Duration::from_micros(500);
24548        s.politicas.timeout = Some(timeout);
24549        assert_eq!(
24550            s.validate().unwrap_err(),
24551            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
24552        );
24553    }
24554
24555    #[test]
24556    fn rejects_policy_timeout_non_integer_millisecond() {
24557        // A `Duration` with non-integer-millisecond residue
24558        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
24559        // through the shared codec's `render` arm as `"1ms"` (the
24560        // `as_millis()` floor truncates), which the codec's `parse`
24561        // arm then deserializes as `Duration::from_millis(1)` =
24562        // 1_000_000 ns — silently *different* from the original.
24563        // Pin the rejection so this round-trip break surfaces at
24564        // validate time, where the offending `Duration` is named,
24565        // rather than as a silent value-laundered round-trip on the
24566        // next codec round-trip.
24567        let mut s = three_member_spec();
24568        let timeout = Duration::from_micros(1500);
24569        s.politicas.timeout = Some(timeout);
24570        assert_eq!(
24571            s.validate().unwrap_err(),
24572            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
24573        );
24574    }
24575
24576    #[test]
24577    fn accepts_policy_timeout_integer_millisecond_forms() {
24578        // The codec's accepted set — integer multiples of 1ms — is
24579        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
24580        // `1h` all pass the canonical gate. Pin the canonical-forms
24581        // sweep so a future tightening of the codec's grammar (e.g.
24582        // dropping `:ms`) surfaces here as a test failure rather
24583        // than a silent contract narrowing on the typed slot.
24584        for timeout in [
24585            Duration::from_millis(1),
24586            Duration::from_millis(500),
24587            Duration::from_millis(1500),
24588            Duration::from_secs(30),
24589            Duration::from_secs(120),
24590            Duration::from_secs(3600),
24591        ] {
24592            let mut s = three_member_spec();
24593            s.politicas.timeout = Some(timeout);
24594            s.validate()
24595                .expect("integer-millisecond :timeout must validate");
24596        }
24597    }
24598
24599    #[test]
24600    fn policy_timeout_zero_takes_precedence_over_canonical() {
24601        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
24602        // pass the canonical-millisecond gate; the more self-locating
24603        // `PolicyTimeoutZero` arm (which names the omit-axis
24604        // remediation directly) must fire first. Pin the ordering so
24605        // a future refactor that reorders the arms surfaces here as a
24606        // test failure rather than a silent diagnostic regression.
24607        let mut s = three_member_spec();
24608        s.politicas.timeout = Some(Duration::ZERO);
24609        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
24610    }
24611
24612    #[test]
24613    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
24614        // The diagnostic envelope carries the offending `Duration`
24615        // verbatim so the author can grep their `caixa.lisp` for
24616        // `:timeout "<value>"` and fix it in one edit. Same
24617        // diagnostic shape every other typed-slot canonical-form
24618        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
24619        // peer `:rate-limit :window` axis.
24620        let mut s = three_member_spec();
24621        let timeout = Duration::from_nanos(1_000_001);
24622        s.politicas.timeout = Some(timeout);
24623        match s.validate().unwrap_err() {
24624            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
24625                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
24626            }
24627            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
24628        }
24629    }
24630
24631    #[test]
24632    fn rejects_policy_timeout_above_cap() {
24633        // The fail-before-pass-after pin: 3601s = 1h + 1s is
24634        // structurally one canonical-tick past the
24635        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
24636        // integer-millisecond magnitude the canonical-form arm above
24637        // accepts cleanly, that the codec round-trips losslessly as
24638        // `"3601s"`, and that silently passed validate on every
24639        // pre-gate codebase because the typed slot's only checks were
24640        // the zero-floor and canonical-form arms. The mesh-level
24641        // deadline degenerates only at the runtime substrate (Envoy
24642        // / Cilium L7 timeout overlay) far from the source
24643        // `caixa.lisp` with no field naming the offending policy.
24644        let mut s = three_member_spec();
24645        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
24646        s.politicas.timeout = Some(timeout);
24647        assert_eq!(
24648            s.validate().unwrap_err(),
24649            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
24650        );
24651    }
24652
24653    #[test]
24654    fn rejects_policy_timeout_one_millisecond_above_cap() {
24655        // Boundary case: exactly 1ms past the cap (the granularity
24656        // the canonical-form gate enforces). Catches a future
24657        // "strictly less than" half-measure and pins the diagnostic
24658        // to name the offending `Duration` verbatim. Peer of
24659        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
24660        // boundary pin on the sibling `:limits :memory` top edge.
24661        let mut s = three_member_spec();
24662        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
24663        s.politicas.timeout = Some(timeout);
24664        assert_eq!(
24665            s.validate().unwrap_err(),
24666            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
24667        );
24668    }
24669
24670    #[test]
24671    fn rejects_policy_timeout_far_above_cap() {
24672        // The "obvious authoring footgun" case: a `(:timeout "24h")`
24673        // or `(:timeout "86400s")` — values the canonical-form arm
24674        // accepts as integer-millisecond magnitudes, the codec
24675        // round-trips losslessly through serde, but the mesh-level
24676        // policy cannot honor (a 24-hour synchronous-`:contratos`
24677        // deadline is operationally indistinguishable from
24678        // omit-the-axis). Until this gate landed validate accepted
24679        // it. Pin both common above-cap values (24h, 7d) so a future
24680        // relaxation that drops the upper bound surfaces here.
24681        for timeout in [
24682            Duration::from_secs(86_400),    // 24h
24683            Duration::from_secs(604_800),   // 7d
24684            Duration::from_secs(1_000_000), // ~11.5 days
24685        ] {
24686            let mut s = three_member_spec();
24687            s.politicas.timeout = Some(timeout);
24688            assert_eq!(
24689                s.validate().unwrap_err(),
24690                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
24691            );
24692        }
24693    }
24694
24695    #[test]
24696    fn accepts_policy_timeout_at_cap() {
24697        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
24698        // must validate. The cap is inclusive on the top edge,
24699        // matching the [`POLICY_RETRIES_MAX`] /
24700        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
24701        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
24702        // sibling capped axes. Pin the boundary explicitly so a
24703        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
24704        // instead of `>`) surfaces here as a test failure rather
24705        // than a silent contract narrowing.
24706        let mut s = three_member_spec();
24707        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24708        s.validate()
24709            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
24710    }
24711
24712    #[test]
24713    fn accepts_policy_timeout_typical_values() {
24714        // The documented production-playbook band positive-control
24715        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
24716        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
24717        // plus a sweep through the long-running-workflow band
24718        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
24719        // validated set explicitly so a future tightening of the
24720        // ceiling surfaces here as a deliberate test edit, not a
24721        // silent contract narrowing.
24722        for timeout in [
24723            Duration::from_millis(1),
24724            Duration::from_millis(500),
24725            Duration::from_secs(1),
24726            Duration::from_secs(10),
24727            Duration::from_secs(15), // Envoy default
24728            Duration::from_secs(30),
24729            Duration::from_secs(60), // AWS App Mesh typical
24730            Duration::from_secs(300),
24731            Duration::from_secs(900),
24732            Duration::from_secs(1800),
24733            Duration::from_secs(3600), // exactly 1h, the cap
24734        ] {
24735            let mut s = three_member_spec();
24736            s.politicas.timeout = Some(timeout);
24737            s.validate()
24738                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
24739        }
24740    }
24741
24742    #[test]
24743    fn policy_timeout_zero_takes_precedence_over_cap() {
24744        // The cross-arm ordering pin: `Duration::ZERO` is
24745        // structurally outside both `>= 1ms` (zero-floor) and
24746        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
24747        // diagnostic is the more self-locating one (it directly
24748        // names the omit-axis remediation), so the validate gate
24749        // must fire on zero first. Same shape every other
24750        // zero-then-shape ordering on this surface uses
24751        // ([`AplicacaoError::PolicyRetriesZero`] then
24752        // [`AplicacaoError::PolicyRetriesExceedsCap`];
24753        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
24754        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
24755        let mut s = three_member_spec();
24756        s.politicas.timeout = Some(Duration::ZERO);
24757        assert_eq!(
24758            s.validate().unwrap_err(),
24759            AplicacaoError::PolicyTimeoutZero,
24760            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
24761        );
24762    }
24763
24764    #[test]
24765    fn policy_timeout_canonical_takes_precedence_over_cap() {
24766        // The cross-arm ordering pin: a `Duration` that is *both*
24767        // sub-millisecond (non-canonical-form) and structurally
24768        // above the cap surfaces the canonical-form diagnostic
24769        // first, because the round-trip-shape break is the more
24770        // fundamental issue (the value can't even round-trip
24771        // through the codec, so the cap diagnostic naming
24772        // `1ms..=1h` would be misleading — there's no integer-ms
24773        // form of the offending value). Pin the order so a future
24774        // refactor that reorders the arms surfaces here as a test
24775        // failure rather than a silent diagnostic regression.
24776        let mut s = three_member_spec();
24777        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
24778        // *and* total magnitude above the 1h cap.
24779        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
24780        s.politicas.timeout = Some(timeout);
24781        assert_eq!(
24782            s.validate().unwrap_err(),
24783            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
24784            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
24785        );
24786    }
24787
24788    #[test]
24789    fn policy_timeout_cap_diagnostic_carries_offending_value() {
24790        // The diagnostic-shape pin: the offending `Duration` is
24791        // carried verbatim into the
24792        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
24793        // surfaced error message names the value the author wrote
24794        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
24795        // exceeds the mesh-policy ceiling …"`), not just the cap.
24796        // Same self-locating diagnostic shape every other typed-cap
24797        // arm on this surface carries
24798        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
24799        // offending retry count verbatim).
24800        let mut s = three_member_spec();
24801        let timeout = Duration::from_secs(7200); // 2h
24802        s.politicas.timeout = Some(timeout);
24803        let err = s.validate().unwrap_err();
24804        assert!(
24805            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
24806            "got {err:?}"
24807        );
24808        let msg = err.to_string();
24809        assert!(
24810            msg.contains("7200"),
24811            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
24812        );
24813    }
24814
24815    #[test]
24816    fn policy_timeout_cap_pins_canonical_value() {
24817        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
24818        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
24819        // the shared duration codec emits as a clean canonical
24820        // string (`"<n>h"`). Pinning the literal value here surfaces
24821        // a future drift (a relaxation to 24h, a tightening to 5m)
24822        // as a deliberate test edit, not a silent contract
24823        // narrowing. Same shape every other typed-cap value pin on
24824        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
24825        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
24826        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
24827    }
24828
24829    #[test]
24830    fn policy_timeout_cap_value_round_trips_through_codec() {
24831        // The codec round-trip property the cap arm preserves: the
24832        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
24833        // the shared duration codec — every value at the cap renders
24834        // to a clean canonical string (`"1h"`) and parses back to
24835        // the same `Duration`. Pin this so a future drift between
24836        // the cap constant and the codec's largest emitted unit
24837        // surfaces here. Same shape every other typed boundary pin
24838        // on this surface uses
24839        // (`wasm32_memory_cap_matches_parsed_4_gib`).
24840        let policy = MeshPolicy {
24841            timeout: Some(POLICY_TIMEOUT_MAX),
24842            ..Default::default()
24843        };
24844        let json = serde_json::to_string(&policy).unwrap();
24845        // The codec emits `"1h"` for the canonical 1-hour magnitude.
24846        assert!(
24847            json.contains("\"1h\""),
24848            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
24849        );
24850        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24851        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
24852    }
24853
24854    #[test]
24855    fn rejects_circuit_breaker_window_sub_millisecond() {
24856        // Peer of the `:timeout` sub-millisecond arm on the second
24857        // typed-`Duration` `:politicas` axis: a purely sub-ms
24858        // `Duration` (`from_micros(500)`) renders through the shared
24859        // codec as `"0s"`, which the codec parses back to
24860        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
24861        // zero-floor gate then rejects on re-validate.
24862        let mut s = three_member_spec();
24863        let window = Duration::from_micros(500);
24864        s.politicas.circuit_breaker = Some(CircuitBreaker {
24865            max_failures: 5,
24866            window,
24867        });
24868        assert_eq!(
24869            s.validate().unwrap_err(),
24870            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
24871        );
24872    }
24873
24874    #[test]
24875    fn rejects_circuit_breaker_window_non_integer_millisecond() {
24876        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
24877        // with non-integer-millisecond residue renders through the
24878        // shared codec as the truncated `"<n>ms"` form, parsing back
24879        // to a *different* `Duration` on the next round-trip.
24880        let mut s = three_member_spec();
24881        let window = Duration::from_micros(1500);
24882        s.politicas.circuit_breaker = Some(CircuitBreaker {
24883            max_failures: 5,
24884            window,
24885        });
24886        assert_eq!(
24887            s.validate().unwrap_err(),
24888            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
24889        );
24890    }
24891
24892    #[test]
24893    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
24894        // The canonical-forms sweep on the breaker axis: every
24895        // integer-ms multiple the codec round-trips losslessly
24896        // passes the canonical gate.
24897        //
24898        // Clears `:timeout` from the fixture so this per-axis sweep
24899        // covers windows shorter than the fixture's 30s timeout
24900        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
24901        // structurally-inert breaker
24902        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
24903        // the cross-axis gate at the end of
24904        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
24905        // `(:timeout, :window)` shape, not on the per-axis
24906        // integer-millisecond canonical-form shape this test pins.
24907        // The paired shape is covered by
24908        // `rejects_circuit_breaker_window_below_timeout`.
24909        for window in [
24910            Duration::from_millis(1),
24911            Duration::from_millis(500),
24912            Duration::from_millis(1500),
24913            Duration::from_secs(30),
24914            Duration::from_secs(60),
24915            Duration::from_secs(3600),
24916        ] {
24917            let mut s = three_member_spec();
24918            s.politicas.timeout = None;
24919            s.politicas.circuit_breaker = Some(CircuitBreaker {
24920                max_failures: 5,
24921                window,
24922            });
24923            s.validate()
24924                .expect("integer-millisecond :circuit-breaker :window must validate");
24925        }
24926    }
24927
24928    #[test]
24929    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
24930        // `Duration::ZERO` would pass the canonical-ms gate (the
24931        // sub-ns residue is zero) but must surface the narrower
24932        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
24933        // remediation.
24934        let mut s = three_member_spec();
24935        s.politicas.circuit_breaker = Some(CircuitBreaker {
24936            max_failures: 5,
24937            window: Duration::ZERO,
24938        });
24939        assert_eq!(
24940            s.validate().unwrap_err(),
24941            AplicacaoError::PolicyBreakerZeroWindow
24942        );
24943    }
24944
24945    #[test]
24946    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
24947        // Both axes invalid: max_failures == 0 *and* window is
24948        // sub-ms. The validate gate must fire on max_failures first
24949        // (matching the existing ordering pin
24950        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
24951        // the existing diagnostic continues to lead with the simpler
24952        // "zero threshold" framing.
24953        let mut s = three_member_spec();
24954        s.politicas.circuit_breaker = Some(CircuitBreaker {
24955            max_failures: 0,
24956            window: Duration::from_micros(500),
24957        });
24958        assert_eq!(
24959            s.validate().unwrap_err(),
24960            AplicacaoError::PolicyBreakerZeroFailures
24961        );
24962    }
24963
24964    #[test]
24965    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
24966        let mut s = three_member_spec();
24967        let window = Duration::from_nanos(60_000_000_001);
24968        s.politicas.circuit_breaker = Some(CircuitBreaker {
24969            max_failures: 5,
24970            window,
24971        });
24972        match s.validate().unwrap_err() {
24973            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
24974                assert_eq!(w, window, "diagnostic must carry the offending Duration");
24975            }
24976            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
24977        }
24978    }
24979
24980    #[test]
24981    fn rejects_circuit_breaker_window_above_cap() {
24982        // The fail-before-pass-after pin: 3601s = 1h + 1s is
24983        // structurally one canonical-tick past the
24984        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
24985        // integer-millisecond magnitude the canonical-form arm above
24986        // accepts cleanly, that the codec round-trips losslessly as
24987        // `"3601s"`, and that silently passed validate on every
24988        // pre-gate codebase because the typed slot's only checks were
24989        // the zero-floor and canonical-form arms. The
24990        // rolling-window-to-lifetime-counter degeneration surfaces
24991        // only at the runtime substrate (Envoy's outlier_detection
24992        // interval, the future CiliumClusterwideEnvoyConfig overlay)
24993        // far from the source `caixa.lisp` with no field naming the
24994        // offending policy.
24995        let mut s = three_member_spec();
24996        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
24997        s.politicas.circuit_breaker = Some(CircuitBreaker {
24998            max_failures: 5,
24999            window,
25000        });
25001        assert_eq!(
25002            s.validate().unwrap_err(),
25003            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
25004        );
25005    }
25006
25007    #[test]
25008    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
25009        // Boundary case: exactly 1ms past the cap (the granularity the
25010        // canonical-form gate enforces). Catches a future "strictly
25011        // less than" half-measure and pins the diagnostic to name the
25012        // offending `Duration` verbatim. Peer of
25013        // `rejects_policy_timeout_one_millisecond_above_cap` on the
25014        // sibling duration-typed `:politicas :timeout` top edge.
25015        let mut s = three_member_spec();
25016        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
25017        s.politicas.circuit_breaker = Some(CircuitBreaker {
25018            max_failures: 5,
25019            window,
25020        });
25021        assert_eq!(
25022            s.validate().unwrap_err(),
25023            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
25024        );
25025    }
25026
25027    #[test]
25028    fn rejects_circuit_breaker_window_far_above_cap() {
25029        // The "obvious authoring footgun" case: a `(:window "24h")` or
25030        // `(:window "86400s")` — values the canonical-form arm
25031        // accepts as integer-millisecond magnitudes, the codec
25032        // round-trips losslessly through serde, but the
25033        // rolling-window breaker contract cannot honor (a 24-hour
25034        // rolling failure window is operationally a lifetime counter).
25035        // Until this gate landed validate accepted it. Pin both common
25036        // above-cap values (24h, 7d) so a future relaxation that
25037        // drops the upper bound surfaces here.
25038        for window in [
25039            Duration::from_secs(86_400),    // 24h
25040            Duration::from_secs(604_800),   // 7d
25041            Duration::from_secs(1_000_000), // ~11.5 days
25042        ] {
25043            let mut s = three_member_spec();
25044            s.politicas.circuit_breaker = Some(CircuitBreaker {
25045                max_failures: 5,
25046                window,
25047            });
25048            assert_eq!(
25049                s.validate().unwrap_err(),
25050                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
25051            );
25052        }
25053    }
25054
25055    #[test]
25056    fn accepts_circuit_breaker_window_at_cap() {
25057        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
25058        // (1h) — must validate. The cap is inclusive on the top edge,
25059        // matching the [`POLICY_TIMEOUT_MAX`] /
25060        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
25061        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
25062        // sibling capped axes. Pin the boundary explicitly so a
25063        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
25064        // instead of `>`) surfaces here as a test failure rather than
25065        // a silent contract narrowing.
25066        let mut s = three_member_spec();
25067        s.politicas.circuit_breaker = Some(CircuitBreaker {
25068            max_failures: 5,
25069            window: POLICY_BREAKER_WINDOW_MAX,
25070        });
25071        s.validate()
25072            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
25073    }
25074
25075    #[test]
25076    fn accepts_circuit_breaker_window_typical_values() {
25077        // The documented production-playbook band positive-control
25078        // sweep — every value Hystrix / resilience4j / Istio / Envoy
25079        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
25080        // through the long-tail failure-detection band (15m, 30m, 1h)
25081        // the cap accepts. Pin the inclusive validated set explicitly
25082        // so a future tightening of the ceiling surfaces here as a
25083        // deliberate test edit, not a silent contract narrowing.
25084        //
25085        // Clears `:timeout` from the fixture so this per-axis sweep
25086        // covers windows shorter than the fixture's 30s timeout
25087        // (Hystrix's 10s default, resilience4j's 30s, and the
25088        // sub-second warm-up band) — every such value is a
25089        // structurally-inert breaker under the cross-axis gate at the
25090        // end of [`AplicacaoSpec::validate_politicas`]
25091        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
25092        // the paired `(:timeout, :window)` shape is covered by
25093        // `rejects_circuit_breaker_window_below_timeout`; this
25094        // per-axis pin ranges only over the per-axis-bracket accept set.
25095        for window in [
25096            Duration::from_millis(1),
25097            Duration::from_millis(500),
25098            Duration::from_secs(1),
25099            Duration::from_secs(10), // Hystrix / Istio / Envoy default
25100            Duration::from_secs(30),
25101            Duration::from_secs(60),  // resilience4j typical
25102            Duration::from_secs(300), // AWS App Mesh typical
25103            Duration::from_secs(900),
25104            Duration::from_secs(1800),
25105            Duration::from_secs(3600), // exactly 1h, the cap
25106        ] {
25107            let mut s = three_member_spec();
25108            s.politicas.timeout = None;
25109            s.politicas.circuit_breaker = Some(CircuitBreaker {
25110                max_failures: 5,
25111                window,
25112            });
25113            s.validate()
25114                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
25115        }
25116    }
25117
25118    #[test]
25119    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
25120        // The cross-arm ordering pin: `Duration::ZERO` is structurally
25121        // outside both `>= 1ms` (zero-floor) and
25122        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
25123        // diagnostic is the more self-locating one (it directly names
25124        // the omit-axis remediation), so the validate gate must fire
25125        // on zero first. Same shape every other zero-then-cap
25126        // ordering on this surface uses
25127        // ([`AplicacaoError::PolicyTimeoutZero`] then
25128        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
25129        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
25130        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
25131        let mut s = three_member_spec();
25132        s.politicas.circuit_breaker = Some(CircuitBreaker {
25133            max_failures: 5,
25134            window: Duration::ZERO,
25135        });
25136        assert_eq!(
25137            s.validate().unwrap_err(),
25138            AplicacaoError::PolicyBreakerZeroWindow,
25139            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
25140        );
25141    }
25142
25143    #[test]
25144    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
25145        // The cross-arm ordering pin: a `Duration` that is *both*
25146        // sub-millisecond (non-canonical-form) and structurally above
25147        // the cap surfaces the canonical-form diagnostic first,
25148        // because the round-trip-shape break is the more fundamental
25149        // issue (the value can't even round-trip through the codec, so
25150        // the cap diagnostic naming `1ms..=1h` would be misleading —
25151        // there's no integer-ms form of the offending value). Pin the
25152        // order so a future refactor that reorders the arms surfaces
25153        // here as a test failure rather than a silent diagnostic
25154        // regression. Peer of
25155        // `policy_timeout_canonical_takes_precedence_over_cap` on the
25156        // sibling duration-typed `:politicas :timeout` axis.
25157        let mut s = three_member_spec();
25158        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
25159        s.politicas.circuit_breaker = Some(CircuitBreaker {
25160            max_failures: 5,
25161            window,
25162        });
25163        assert_eq!(
25164            s.validate().unwrap_err(),
25165            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
25166            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
25167        );
25168    }
25169
25170    #[test]
25171    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
25172        // The cross-arm ordering pin between the two breaker axes: a
25173        // `CircuitBreaker` whose *both* `max_failures` is above its
25174        // cap *and* `window` is above its cap surfaces the
25175        // max-failures cap diagnostic first, because the validate
25176        // gate visits the failures arm before the window arm. Pin the
25177        // order so a future refactor that reorders the breaker arms
25178        // surfaces here.
25179        let mut s = three_member_spec();
25180        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
25181        s.politicas.circuit_breaker = Some(CircuitBreaker {
25182            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
25183            window,
25184        });
25185        assert_eq!(
25186            s.validate().unwrap_err(),
25187            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
25188                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
25189            },
25190            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
25191        );
25192    }
25193
25194    #[test]
25195    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
25196        // The diagnostic-shape pin: the offending `Duration` is
25197        // carried verbatim into the
25198        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
25199        // the surfaced error message names the value the author wrote
25200        // (`":politicas :circuit-breaker :window (Duration { secs:
25201        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
25202        // just the cap. Same self-locating diagnostic shape every
25203        // other typed-cap arm on this surface carries
25204        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
25205        // offending `Duration` verbatim).
25206        let mut s = three_member_spec();
25207        let window = Duration::from_secs(7200); // 2h
25208        s.politicas.circuit_breaker = Some(CircuitBreaker {
25209            max_failures: 5,
25210            window,
25211        });
25212        let err = s.validate().unwrap_err();
25213        assert!(
25214            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
25215            "got {err:?}"
25216        );
25217        let msg = err.to_string();
25218        assert!(
25219            msg.contains("7200"),
25220            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
25221        );
25222    }
25223
25224    #[test]
25225    fn circuit_breaker_window_cap_pins_canonical_value() {
25226        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
25227        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
25228        // shared duration codec emits as a clean canonical string
25229        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
25230        // the sibling duration-typed `:politicas :timeout` axis (the
25231        // two duration-typed `:politicas` axes share a uniform top
25232        // edge). Pinning the literal value here surfaces a future
25233        // drift (a relaxation to 24h, a tightening to 5m) as a
25234        // deliberate test edit, not a silent contract narrowing. Same
25235        // shape every other typed-cap value pin on this surface uses
25236        // (`policy_timeout_cap_pins_canonical_value`).
25237        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
25238        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
25239        assert_eq!(
25240            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
25241            "the two duration-typed `:politicas` caps share the same top edge"
25242        );
25243    }
25244
25245    #[test]
25246    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
25247        // The codec round-trip property the cap arm preserves: the
25248        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
25249        // through the shared duration codec — every value at the cap
25250        // renders to a clean canonical string (`"1h"`) and parses back
25251        // to the same `Duration`. Pin this so a future drift between
25252        // the cap constant and the codec's largest emitted unit
25253        // surfaces here. Same shape every other typed boundary pin on
25254        // this surface uses
25255        // (`policy_timeout_cap_value_round_trips_through_codec`).
25256        let policy = MeshPolicy {
25257            circuit_breaker: Some(CircuitBreaker {
25258                max_failures: 5,
25259                window: POLICY_BREAKER_WINDOW_MAX,
25260            }),
25261            ..Default::default()
25262        };
25263        let json = serde_json::to_string(&policy).unwrap();
25264        // The codec emits `"1h"` for the canonical 1-hour magnitude.
25265        assert!(
25266            json.contains("\"1h\""),
25267            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
25268        );
25269        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25270        assert_eq!(
25271            back.circuit_breaker.unwrap().window,
25272            POLICY_BREAKER_WINDOW_MAX
25273        );
25274    }
25275
25276    #[test]
25277    fn is_integer_millisecond_duration_predicate_tracks_codec() {
25278        // Pin the predicate's accepted set against the codec's
25279        // accepted set explicitly. The codec parses
25280        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
25281        // accepted value is an integer-millisecond multiple — so the
25282        // predicate must accept exactly that set. Same shape every
25283        // other predicate-on-the-typed-slot helper carries
25284        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
25285        // Read directly from the codec-owned predicate — the crate's
25286        // single source of truth every typed-`Duration` axis now routes
25287        // through via
25288        // [`crate::render::require_positive_canonical_bounded_duration`].
25289        use super::supervisor::duration_codec::is_integer_millisecond_duration;
25290        assert!(is_integer_millisecond_duration(Duration::ZERO));
25291        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
25292        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
25293        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
25294        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
25295        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
25296        // Non-integer-millisecond residue: rejected.
25297        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
25298        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
25299        assert!(!is_integer_millisecond_duration(Duration::from_micros(
25300            1500
25301        )));
25302        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
25303        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
25304            999_999
25305        )));
25306        // The 1-ns-past-1ms boundary: rejected (no longer a clean
25307        // integer-millisecond multiple).
25308        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
25309            1_000_001
25310        )));
25311    }
25312
25313    #[test]
25314    fn policy_timeout_validated_value_round_trips_through_codec() {
25315        // The structural property the canonical-ms gate enforces:
25316        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
25317        // round-trips losslessly through the shared `duration_codec`
25318        // (serialize → string → deserialize → equal value). Pin this
25319        // end-to-end so a future change to either side (the validate
25320        // gate's accepted granularity, the codec's parse/render unit
25321        // set) that breaks the alignment surfaces here. The
25322        // previous-state shape (typed slot accepts arbitrary
25323        // `Duration`, codec only round-trips integer-ms) would fail
25324        // this test for any `Duration::from_micros(1500)` timeout —
25325        // the validate gate now forecloses that.
25326        for timeout in [
25327            Duration::from_millis(1),
25328            Duration::from_millis(1500),
25329            Duration::from_secs(30),
25330            Duration::from_secs(3600),
25331        ] {
25332            let mut s = three_member_spec();
25333            s.politicas.timeout = Some(timeout);
25334            s.validate().unwrap();
25335            let json = serde_json::to_string(&s.politicas).unwrap();
25336            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25337            assert_eq!(
25338                back.timeout, s.politicas.timeout,
25339                "every validated :timeout must round-trip losslessly through the codec"
25340            );
25341        }
25342    }
25343
25344    #[test]
25345    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
25346        // Peer of the `:timeout` round-trip property on the breaker
25347        // axis.
25348        //
25349        // Clears `:timeout` from the fixture so the round-trip pin
25350        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
25351        // cross-axis gate would otherwise reject as structurally-inert
25352        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
25353        // the paired `(:timeout, :window)` cross-axis relation is
25354        // pinned separately by
25355        // `rejects_circuit_breaker_window_below_timeout`, and this
25356        // property is a pure serde-codec round-trip on the per-axis
25357        // slot.
25358        for window in [
25359            Duration::from_millis(1),
25360            Duration::from_millis(1500),
25361            Duration::from_secs(30),
25362            Duration::from_secs(3600),
25363        ] {
25364            let mut s = three_member_spec();
25365            s.politicas.timeout = None;
25366            s.politicas.circuit_breaker = Some(CircuitBreaker {
25367                max_failures: 5,
25368                window,
25369            });
25370            s.validate().unwrap();
25371            let json = serde_json::to_string(&s.politicas).unwrap();
25372            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25373            assert_eq!(
25374                back.circuit_breaker.unwrap().window,
25375                window,
25376                "every validated :circuit-breaker :window must round-trip losslessly"
25377            );
25378        }
25379    }
25380
25381    #[test]
25382    fn rejects_circuit_breaker_window_below_timeout() {
25383        // The fail-before-pass-after pin on the cross-axis
25384        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
25385        // is individually well-formed under its own per-axis bracket
25386        // (both integer-millisecond, both above the zero floor, both
25387        // below the cap), but the pair is a structurally-inert
25388        // breaker: a call dispatched at t=0 is declared failed at
25389        // t=30s, by which point the 10s rolling window open at
25390        // dispatch has already rolled twice, so no window can hold
25391        // a timeout-derived failure however high the call volume.
25392        //
25393        // Envoy's `outlier_detection.interval` against the per-route
25394        // request timeout carries the identical relation; Hystrix
25395        // ships the canonical ratio in its defaults (10s window
25396        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
25397        //
25398        // Pin both the diagnostic arm and the payload values so a
25399        // future re-shape of the arm surfaces here as a deliberate
25400        // test edit.
25401        let mut s = three_member_spec();
25402        s.politicas.timeout = Some(Duration::from_secs(30));
25403        s.politicas.circuit_breaker = Some(CircuitBreaker {
25404            max_failures: 5,
25405            window: Duration::from_secs(10),
25406        });
25407        assert_eq!(
25408            s.validate().unwrap_err(),
25409            AplicacaoError::PolicyBreakerWindowBelowTimeout {
25410                window: Duration::from_secs(10),
25411                timeout: Duration::from_secs(30),
25412            }
25413        );
25414    }
25415
25416    #[test]
25417    fn accepts_circuit_breaker_window_equal_to_timeout() {
25418        // Boundary pin: `:window == :timeout` is the smallest window
25419        // that structurally admits at least one full timeout-derived
25420        // failure before the rolling interval closes (the invariant
25421        // is `:window >= :timeout`, not strict inequality). Catches
25422        // a future off-by-one tightening that would drift the accept
25423        // set away from the codified [`MeshPolicy::breaker_window_
25424        // observes_timeout`] predicate.
25425        let mut s = three_member_spec();
25426        s.politicas.timeout = Some(Duration::from_secs(30));
25427        s.politicas.circuit_breaker = Some(CircuitBreaker {
25428            max_failures: 5,
25429            window: Duration::from_secs(30),
25430        });
25431        s.validate()
25432            .expect("window == timeout is the boundary accept case");
25433    }
25434
25435    #[test]
25436    fn accepts_circuit_breaker_window_above_timeout() {
25437        // Positive-control sweep across the production-playbook band —
25438        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
25439        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
25440        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
25441        // playbook recommends must validate under the cross-axis gate.
25442        for (timeout, window) in [
25443            (Duration::from_secs(1), Duration::from_secs(10)),
25444            (Duration::from_secs(5), Duration::from_secs(30)),
25445            (Duration::from_secs(10), Duration::from_secs(60)),
25446            (Duration::from_secs(30), Duration::from_secs(300)),
25447            (Duration::from_secs(60), Duration::from_secs(300)),
25448        ] {
25449            let mut s = three_member_spec();
25450            s.politicas.timeout = Some(timeout);
25451            s.politicas.circuit_breaker = Some(CircuitBreaker {
25452                max_failures: 5,
25453                window,
25454            });
25455            s.validate().unwrap_or_else(|e| {
25456                panic!(
25457                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
25458                     validate; got {e:?}"
25459                )
25460            });
25461        }
25462    }
25463
25464    #[test]
25465    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
25466        // Off-by-one boundary pin: a window exactly 1ms shy of the
25467        // timeout is still structurally inert under the invariant
25468        // (the dispatch-to-report lag is `timeout`, so the window
25469        // must span at least one such lag). Catches a future
25470        // strict-inequality relaxation that would silently drift
25471        // the accept boundary.
25472        let timeout = Duration::from_secs(30);
25473        let window = Duration::from_millis(29_999);
25474        let mut s = three_member_spec();
25475        s.politicas.timeout = Some(timeout);
25476        s.politicas.circuit_breaker = Some(CircuitBreaker {
25477            max_failures: 5,
25478            window,
25479        });
25480        assert_eq!(
25481            s.validate().unwrap_err(),
25482            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
25483        );
25484    }
25485
25486    #[test]
25487    fn cross_axis_gate_vacuous_when_timeout_absent() {
25488        // The predicate is vacuously `true` when `:timeout` is None —
25489        // a `:circuit-breaker` alone declares no relation to a
25490        // substrate-imposed deadline (the failure signal reaches the
25491        // breaker from the transport's own error surface, so no
25492        // dispatch-to-report lag is knowable at author time). Pin so
25493        // a future tightening that made the gate opinionated on
25494        // half-declared pairs surfaces here.
25495        let mut s = three_member_spec();
25496        s.politicas.timeout = None;
25497        s.politicas.circuit_breaker = Some(CircuitBreaker {
25498            max_failures: 5,
25499            window: Duration::from_millis(1),
25500        });
25501        s.validate().expect(
25502            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
25503        );
25504    }
25505
25506    #[test]
25507    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
25508        // Peer of the sibling `:timeout`-absent case: a `:timeout`
25509        // without a `:circuit-breaker` declares a per-call deadline
25510        // without any rolling-window failure accounting, so the pair
25511        // is undeclared and the cross-axis gate has nothing to check.
25512        let mut s = three_member_spec();
25513        s.politicas.timeout = Some(Duration::from_secs(3600));
25514        s.politicas.circuit_breaker = None;
25515        s.validate().expect(
25516            "cross-axis gate must be vacuous when :circuit-breaker is None, \
25517             however large :timeout is",
25518        );
25519    }
25520
25521    #[test]
25522    fn cross_axis_gate_runs_after_per_axis_brackets() {
25523        // Ordering pin: a pair whose window is *both* zero-floor-
25524        // violating and structurally below the timeout must surface
25525        // the per-axis zero-floor arm first — the zero-floor
25526        // diagnostic is more self-locating (its omit-axis remediation
25527        // is directly named), where the cross-axis arm would send the
25528        // author to reconcile two values one of which is not a
25529        // meaningful window at all. Same ordering discipline every
25530        // per-axis bracket carries internally (zero-floor before
25531        // canonical-form before cap).
25532        let mut s = three_member_spec();
25533        s.politicas.timeout = Some(Duration::from_secs(30));
25534        s.politicas.circuit_breaker = Some(CircuitBreaker {
25535            max_failures: 5,
25536            window: Duration::ZERO,
25537        });
25538        assert_eq!(
25539            s.validate().unwrap_err(),
25540            AplicacaoError::PolicyBreakerZeroWindow,
25541            "per-axis zero-floor arm must fire before the cross-axis gate"
25542        );
25543    }
25544
25545    #[test]
25546    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
25547        // Equivalence pin: the substrate-canonical
25548        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
25549        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
25550        // arm must discriminate the same set on every pair covered
25551        // by their shared invariant. A future refactor of either
25552        // side that breaks the equivalence trips here rather than as
25553        // a divergence between the predicate's Boolean answer and
25554        // the validate gate's Ok/Err arm — the same
25555        // predicate-vs-gate coherence discipline the peer
25556        // [`PlacementStrategy::is_shard_keyed`] predicate carries
25557        // against `AplicacaoSpec::validate_placement`. The sweep
25558        // covers both arms of the invariant (below, equal, above)
25559        // and both vacuous arms (None `:timeout`, None
25560        // `:circuit-breaker`), so the equivalence holds
25561        // exhaustively over the axis-covered accept and reject sets.
25562        let cases: &[(Option<Duration>, Option<Duration>)] = &[
25563            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
25564            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
25565            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
25566            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
25567            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
25568            (None, Some(Duration::from_secs(1))),
25569            (Some(Duration::from_secs(30)), None),
25570            (None, None),
25571        ];
25572        for (timeout, window) in cases.iter().copied() {
25573            let politicas = MeshPolicy {
25574                timeout,
25575                circuit_breaker: window.map(|w| CircuitBreaker {
25576                    max_failures: 5,
25577                    window: w,
25578                }),
25579                ..Default::default()
25580            };
25581            let predicate = politicas.breaker_window_observes_timeout();
25582
25583            let mut s = three_member_spec();
25584            s.politicas = politicas.clone();
25585            let gate_ok = !matches!(
25586                s.validate(),
25587                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
25588            );
25589
25590            assert_eq!(
25591                predicate, gate_ok,
25592                "predicate must agree with validate arm on pair \
25593                 (timeout={timeout:?}, window={window:?})"
25594            );
25595        }
25596    }
25597
25598    #[test]
25599    fn rejects_rate_limit_starves_circuit_breaker() {
25600        // The fail-before-pass-after pin on the cross-axis
25601        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
25602        // individually well-formed under its own per-axis bracket
25603        // (both above the zero floor, both below the cap, rate-limit
25604        // window canonical), but the pair is a structurally-inert
25605        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
25606        // calls per rolling breaker window, so no window can
25607        // accumulate five failures however catastrophic the upstream
25608        // failure rate.
25609        //
25610        // Envoy's `outlier_detection.consecutive_5xx` paired against
25611        // `local_rate_limit.token_bucket.max_tokens` /
25612        // `fill_interval` carries the identical relation; every
25613        // production playbook that pairs the two axes (Envoy, Istio,
25614        // AWS App Mesh, Kong) sizes the rate at or above the
25615        // breaker's minimum-request-volume threshold for exactly this
25616        // reason.
25617        //
25618        // Pin both the diagnostic arm and the payload values so a
25619        // future re-shape of the arm surfaces here as a deliberate
25620        // test edit. Clears `:timeout` so the sibling
25621        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
25622        // does not fire first on the ordering-precedent it holds
25623        // over this arm.
25624        let mut s = three_member_spec();
25625        s.politicas.timeout = None;
25626        s.politicas.circuit_breaker = Some(CircuitBreaker {
25627            max_failures: 5,
25628            window: Duration::from_secs(10),
25629        });
25630        s.politicas.rate_limit = Some(RateLimit {
25631            rate: 1,
25632            window: Duration::from_secs(3600),
25633        });
25634        assert_eq!(
25635            s.validate().unwrap_err(),
25636            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
25637                rate: 1,
25638                rl_window: Duration::from_secs(3600),
25639                max_failures: 5,
25640                cb_window: Duration::from_secs(10),
25641            }
25642        );
25643    }
25644
25645    #[test]
25646    fn accepts_rate_limit_can_trip_circuit_breaker() {
25647        // Positive-control sweep across the production-playbook band
25648        // — every pair a real playbook recommends where the rate
25649        // clearly admits enough calls per breaker window to reach
25650        // `:max-failures` must validate. Envoy default 5 failures
25651        // in 10s with 100/s (1000 calls / window, 200× the threshold),
25652        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
25653        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
25654        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
25655        // the sibling cross-axis arm is vacuous on this sweep.
25656        for (rate, rl_window, max_failures, cb_window) in [
25657            (
25658                100u32,
25659                Duration::from_secs(1),
25660                5u32,
25661                Duration::from_secs(10),
25662            ),
25663            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
25664            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
25665            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
25666            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
25667        ] {
25668            let mut s = three_member_spec();
25669            s.politicas.timeout = None;
25670            s.politicas.circuit_breaker = Some(CircuitBreaker {
25671                max_failures,
25672                window: cb_window,
25673            });
25674            s.politicas.rate_limit = Some(RateLimit {
25675                rate,
25676                window: rl_window,
25677            });
25678            s.validate().unwrap_or_else(|e| {
25679                panic!(
25680                    "production-playbook pair rate={rate}/{rl_window:?} \
25681                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
25682                )
25683            });
25684        }
25685    }
25686
25687    #[test]
25688    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
25689        // Boundary pin: `rate × cb_window == max_failures × rl_window`
25690        // is the smallest bucket capacity that structurally admits
25691        // exactly `max_failures` calls per rolling breaker window
25692        // (the invariant is `≥`, not strict inequality). Catches a
25693        // future off-by-one tightening to strict inequality that
25694        // would drift the accept set away from the codified
25695        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
25696        // 5 calls/s over a 1s breaker window == 5 max_failures.
25697        let mut s = three_member_spec();
25698        s.politicas.timeout = None;
25699        s.politicas.circuit_breaker = Some(CircuitBreaker {
25700            max_failures: 5,
25701            window: Duration::from_secs(1),
25702        });
25703        s.politicas.rate_limit = Some(RateLimit {
25704            rate: 5,
25705            window: Duration::from_secs(1),
25706        });
25707        s.validate()
25708            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
25709    }
25710
25711    #[test]
25712    fn rejects_rate_limit_one_call_short_per_cb_window() {
25713        // Off-by-one boundary pin: exactly one call short of the trip
25714        // threshold per breaker window is still structurally inert
25715        // (the invariant is `≥`, so `<` refuses even a one-call
25716        // shortfall). 4 calls/s over a 1s window == 4 admissible
25717        // failures, one shy of the 5-`max_failures` threshold.
25718        // Catches a future strict-inequality relaxation that would
25719        // silently drift the accept boundary.
25720        let mut s = three_member_spec();
25721        s.politicas.timeout = None;
25722        s.politicas.circuit_breaker = Some(CircuitBreaker {
25723            max_failures: 5,
25724            window: Duration::from_secs(1),
25725        });
25726        s.politicas.rate_limit = Some(RateLimit {
25727            rate: 4,
25728            window: Duration::from_secs(1),
25729        });
25730        assert_eq!(
25731            s.validate().unwrap_err(),
25732            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
25733                rate: 4,
25734                rl_window: Duration::from_secs(1),
25735                max_failures: 5,
25736                cb_window: Duration::from_secs(1),
25737            }
25738        );
25739    }
25740
25741    #[test]
25742    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
25743        // The predicate is vacuously `true` when `:rate-limit` is
25744        // None — a `:circuit-breaker` alone declares no relation to
25745        // a substrate-imposed call rate (the failure signal reaches
25746        // the breaker from the transport's own error surface, at
25747        // whatever rate upstream callers push traffic). Pin so a
25748        // future tightening that made the gate opinionated on
25749        // half-declared pairs surfaces here.
25750        let mut s = three_member_spec();
25751        s.politicas.timeout = None;
25752        s.politicas.circuit_breaker = Some(CircuitBreaker {
25753            max_failures: 1000,
25754            window: Duration::from_millis(1),
25755        });
25756        s.politicas.rate_limit = None;
25757        s.validate().expect(
25758            "cross-axis starve gate must be vacuous when :rate-limit is None, \
25759             however high :max-failures and however small :window are",
25760        );
25761    }
25762
25763    #[test]
25764    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
25765        // Peer of the sibling `:rate-limit`-absent case: a
25766        // `:rate-limit` without a `:circuit-breaker` declares a
25767        // per-edge token-bucket rate without any failure counter to
25768        // starve, so the pair is undeclared and the cross-axis gate
25769        // has nothing to check.
25770        //
25771        // Also clears the fixture's `:retries` (which is `Some(3)`) so
25772        // the sibling cross-axis
25773        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
25774        // (which reasons across the paired `(:retries, :rate-limit)`
25775        // pair independent of `:circuit-breaker`) is vacuous on this
25776        // pin — this test names the *starve* arm's vacuity on the
25777        // `:circuit-breaker`-absent case, not the burst arm's.
25778        let mut s = three_member_spec();
25779        s.politicas.timeout = None;
25780        s.politicas.retries = None;
25781        s.politicas.circuit_breaker = None;
25782        s.politicas.rate_limit = Some(RateLimit {
25783            rate: 1,
25784            window: Duration::from_secs(3600),
25785        });
25786        s.validate().expect(
25787            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
25788             however low :rate is",
25789        );
25790    }
25791
25792    #[test]
25793    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
25794        // Ordering pin: a pair whose rate is *both* zero-floor-
25795        // violating and structurally below the trip threshold must
25796        // surface the per-axis zero-floor arm first — the zero-floor
25797        // diagnostic is more self-locating (its omit-axis remediation
25798        // is directly named), where the cross-axis arm would send the
25799        // author to reconcile four values one of which is not a
25800        // meaningful rate at all. Same ordering discipline every
25801        // per-axis bracket carries internally (zero-floor before
25802        // canonical-form before cap), and the sibling cross-axis
25803        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
25804        // ordering pins on the `(:timeout, :window)` pair.
25805        let mut s = three_member_spec();
25806        s.politicas.timeout = None;
25807        s.politicas.circuit_breaker = Some(CircuitBreaker {
25808            max_failures: 5,
25809            window: Duration::from_secs(10),
25810        });
25811        s.politicas.rate_limit = Some(RateLimit {
25812            rate: 0,
25813            window: Duration::from_secs(1),
25814        });
25815        assert_eq!(
25816            s.validate().unwrap_err(),
25817            AplicacaoError::PolicyRateLimitZero,
25818            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
25819        );
25820    }
25821
25822    #[test]
25823    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
25824        // Cross-axis ordering pin: a `:politicas` whose axes trip
25825        // BOTH cross-axis arms — `:window < :timeout` (the sibling
25826        // `PolicyBreakerWindowBelowTimeout` invariant) AND
25827        // `:rate-limit` starves the breaker within `:window` (this
25828        // arm) — must surface the timeout-relation diagnostic first.
25829        // The timeout arm is the per-call-deadline invariant every
25830        // synchronous edge carries whether or not `:rate-limit` is
25831        // declared, so its diagnostic is more self-locating; the
25832        // starve arm needs the reader to reason across three axes,
25833        // where the timeout arm names only two.
25834        //
25835        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
25836        // pair trips both: the window is below the timeout, and the
25837        // rate (1 call/hour) admits far fewer than 5 calls per 10s
25838        // breaker window.
25839        let mut s = three_member_spec();
25840        s.politicas.timeout = Some(Duration::from_secs(30));
25841        s.politicas.circuit_breaker = Some(CircuitBreaker {
25842            max_failures: 5,
25843            window: Duration::from_secs(10),
25844        });
25845        s.politicas.rate_limit = Some(RateLimit {
25846            rate: 1,
25847            window: Duration::from_secs(3600),
25848        });
25849        assert_eq!(
25850            s.validate().unwrap_err(),
25851            AplicacaoError::PolicyBreakerWindowBelowTimeout {
25852                window: Duration::from_secs(10),
25853                timeout: Duration::from_secs(30),
25854            },
25855            "sibling :window<:timeout cross-axis arm must fire before the \
25856             starve arm when both apply"
25857        );
25858    }
25859
25860    #[test]
25861    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
25862        // Equivalence pin: the substrate-canonical
25863        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
25864        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
25865        // arm must discriminate the same set on every pair covered
25866        // by their shared invariant. A future refactor of either
25867        // side that breaks the equivalence trips here rather than as
25868        // a divergence between the predicate's Boolean answer and
25869        // the validate gate's Ok/Err arm — the same
25870        // predicate-vs-gate coherence discipline the sibling
25871        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
25872        // carries against `AplicacaoSpec::validate_politicas`. The
25873        // sweep covers both arms of the invariant (strictly below,
25874        // exactly at, strictly above) and both vacuous arms (None
25875        // `:rate-limit`, None `:circuit-breaker`), so the
25876        // equivalence holds exhaustively over the axis-covered
25877        // accept and reject sets. Clears `:timeout` throughout so
25878        // the sibling `:window<:timeout` gate is vacuous on every
25879        // input.
25880        let rl = |rate: u32, secs: u64| {
25881            Some(RateLimit {
25882                rate,
25883                window: Duration::from_secs(secs),
25884            })
25885        };
25886        let cb = |max_failures: u32, secs: u64| {
25887            Some(CircuitBreaker {
25888                max_failures,
25889                window: Duration::from_secs(secs),
25890            })
25891        };
25892        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
25893            // starving pairs (predicate = false, gate = Err)
25894            (rl(1, 3600), cb(5, 10)),
25895            (rl(4, 1), cb(5, 1)),
25896            // boundary + coherent pairs (predicate = true, gate = Ok)
25897            (rl(5, 1), cb(5, 1)),
25898            (rl(100, 1), cb(5, 10)),
25899            // vacuous arms
25900            (None, cb(5, 10)),
25901            (rl(1, 3600), None),
25902            (None, None),
25903        ];
25904        for (rate_limit, circuit_breaker) in cases.iter().copied() {
25905            let politicas = MeshPolicy {
25906                circuit_breaker,
25907                rate_limit,
25908                ..Default::default()
25909            };
25910            let predicate = politicas.breaker_can_trip_under_rate_limit();
25911
25912            let mut s = three_member_spec();
25913            s.politicas = politicas.clone();
25914            s.politicas.timeout = None;
25915            let gate_ok = !matches!(
25916                s.validate(),
25917                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
25918            );
25919
25920            assert_eq!(
25921                predicate, gate_ok,
25922                "predicate must agree with validate arm on pair \
25923                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
25924            );
25925        }
25926    }
25927
25928    #[test]
25929    fn rejects_retries_saturate_breaker_trip_threshold() {
25930        // The fail-before-pass-after pin on the cross-axis
25931        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
25932        // axis is individually well-formed under its own per-axis
25933        // bracket (both above the zero floor, both below the cap), but
25934        // the pair is a structurally-truncated retry policy: one
25935        // client's `retries + 1 = 4` failing attempts hit the trip
25936        // threshold on the third attempt, the breaker opens, and the
25937        // fourth attempt (the last declared retry) is blocked by the
25938        // open breaker — the substrate declared four attempts and
25939        // structurally allows three.
25940        //
25941        // Envoy's `retry_policy.num_retries` paired against
25942        // `outlier_detection.consecutive_5xx` carries the identical
25943        // relation; every production playbook that pairs the two axes
25944        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
25945        // trip threshold strictly above any single client's retry
25946        // budget so the breaker distinguishes one persistently-failing
25947        // client from sustained multi-client failure.
25948        //
25949        // Pin both the diagnostic arm and the payload values so a
25950        // future re-shape of the arm surfaces here as a deliberate
25951        // test edit. Clears `:timeout` and `:rate-limit` so the
25952        // sibling cross-axis
25953        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
25954        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
25955        // arms do not fire first on the ordering-precedent they hold
25956        // over this arm.
25957        let mut s = three_member_spec();
25958        s.politicas.timeout = None;
25959        s.politicas.retries = Some(3);
25960        s.politicas.circuit_breaker = Some(CircuitBreaker {
25961            max_failures: 3,
25962            window: Duration::from_secs(1),
25963        });
25964        s.politicas.rate_limit = None;
25965        assert_eq!(
25966            s.validate().unwrap_err(),
25967            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
25968                retries: 3,
25969                max_failures: 3,
25970            }
25971        );
25972    }
25973
25974    #[test]
25975    fn accepts_retries_below_breaker_trip_threshold() {
25976        // Positive-control sweep across the production-playbook band
25977        // — every pair a real playbook recommends where the breaker's
25978        // trip threshold is strictly above the client's retry budget
25979        // must validate. Envoy default `num_retries: 3` with
25980        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
25981        // opens on multi-client failures beyond that); Istio
25982        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
25983        // `execution.isolation.thread.timeoutInMilliseconds` + 3
25984        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
25985        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
25986        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
25987        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
25988        // arms are vacuous on this sweep.
25989        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
25990        {
25991            let mut s = three_member_spec();
25992            s.politicas.timeout = None;
25993            s.politicas.retries = Some(retries);
25994            s.politicas.circuit_breaker = Some(CircuitBreaker {
25995                max_failures,
25996                window: Duration::from_secs(60),
25997            });
25998            s.politicas.rate_limit = None;
25999            s.validate().unwrap_or_else(|e| {
26000                panic!(
26001                    "production-playbook pair retries={retries} \
26002                     max_failures={max_failures} must validate; got {e:?}"
26003                )
26004            });
26005        }
26006    }
26007
26008    #[test]
26009    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
26010        // Boundary pin: `max_failures == retries + 1` is the smallest
26011        // trip threshold that admits one client's exhausted retries
26012        // through completion (the R+1th failure — the last declared
26013        // retry — trips the breaker exactly as it completes, so
26014        // retries fully executed). The invariant is `>`, not `>=`,
26015        // stated in the coherent direction `max_failures > retries`.
26016        // Catches a future off-by-one tightening to
26017        // `max_failures > retries + 1` that would drift the accept set
26018        // away from the codified
26019        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
26020        // predicate.
26021        let mut s = three_member_spec();
26022        s.politicas.timeout = None;
26023        s.politicas.retries = Some(3);
26024        s.politicas.circuit_breaker = Some(CircuitBreaker {
26025            max_failures: 4,
26026            window: Duration::from_secs(60),
26027        });
26028        s.politicas.rate_limit = None;
26029        s.validate()
26030            .expect("max_failures == retries + 1 is the boundary accept case");
26031    }
26032
26033    #[test]
26034    fn rejects_retries_equal_to_breaker_trip_threshold() {
26035        // Off-by-one boundary pin: exactly at the trip threshold is
26036        // still structurally truncating (the invariant is `>`, so `<=`
26037        // refuses even the tight boundary). `retries = 3` with
26038        // `max_failures = 3` means the breaker trips on the third
26039        // failure — the last declared retry attempt is blocked.
26040        // Catches a future relaxation to `>=` that would silently
26041        // drift the accept boundary.
26042        let mut s = three_member_spec();
26043        s.politicas.timeout = None;
26044        s.politicas.retries = Some(3);
26045        s.politicas.circuit_breaker = Some(CircuitBreaker {
26046            max_failures: 3,
26047            window: Duration::from_secs(60),
26048        });
26049        s.politicas.rate_limit = None;
26050        assert_eq!(
26051            s.validate().unwrap_err(),
26052            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
26053                retries: 3,
26054                max_failures: 3,
26055            }
26056        );
26057    }
26058
26059    #[test]
26060    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
26061        // The predicate is vacuously `true` when `:retries` is None —
26062        // a `:circuit-breaker` alone declares a failure counter whose
26063        // per-client attempt count is unconstrained by the substrate,
26064        // so no per-client saturation bound on failures-per-client-call
26065        // is knowable at author time. The substrate takes no position
26066        // on whether an omitted `:retries` axis means zero retries or
26067        // "the client picks its own retry policy" — either way, the
26068        // pair is undeclared and the cross-axis gate has nothing to
26069        // check. Pin so a future tightening that made the gate
26070        // opinionated on half-declared pairs surfaces here.
26071        let mut s = three_member_spec();
26072        s.politicas.timeout = None;
26073        s.politicas.retries = None;
26074        s.politicas.circuit_breaker = Some(CircuitBreaker {
26075            max_failures: 1,
26076            window: Duration::from_secs(60),
26077        });
26078        s.politicas.rate_limit = None;
26079        s.validate().expect(
26080            "cross-axis retries gate must be vacuous when :retries is None, \
26081             however low :max-failures is",
26082        );
26083    }
26084
26085    #[test]
26086    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
26087        // Peer of the sibling `:retries`-absent case: a `:retries`
26088        // without a `:circuit-breaker` declares a client-retry policy
26089        // with no failure counter to trip, so the pair is undeclared
26090        // and the cross-axis gate has nothing to check.
26091        let mut s = three_member_spec();
26092        s.politicas.timeout = None;
26093        s.politicas.retries = Some(POLICY_RETRIES_MAX);
26094        s.politicas.circuit_breaker = None;
26095        s.politicas.rate_limit = None;
26096        s.validate().expect(
26097            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
26098             however high :retries is",
26099        );
26100    }
26101
26102    #[test]
26103    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
26104        // Ordering pin: a pair whose retries is *both* zero-floor-
26105        // violating and structurally at-or-below the trip threshold
26106        // must surface the per-axis zero-floor arm first — the
26107        // zero-floor diagnostic is more self-locating (its omit-axis
26108        // remediation is directly named), where the cross-axis arm
26109        // would send the author to reconcile two values one of which
26110        // is not a meaningful retry count at all. Same ordering
26111        // discipline every per-axis bracket carries internally
26112        // (zero-floor before canonical-form before cap), and the
26113        // sibling cross-axis
26114        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
26115        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
26116        let mut s = three_member_spec();
26117        s.politicas.timeout = None;
26118        s.politicas.retries = Some(0);
26119        s.politicas.circuit_breaker = Some(CircuitBreaker {
26120            max_failures: 3,
26121            window: Duration::from_secs(60),
26122        });
26123        s.politicas.rate_limit = None;
26124        assert_eq!(
26125            s.validate().unwrap_err(),
26126            AplicacaoError::PolicyRetriesZero,
26127            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
26128        );
26129    }
26130
26131    #[test]
26132    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
26133        // Cross-axis ordering pin: a `:politicas` whose axes trip
26134        // BOTH cross-axis arms — `:rate-limit` starves the breaker
26135        // within `:window` (the sibling
26136        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
26137        // `:retries + 1` saturates `:max-failures` (this arm) — must
26138        // surface the rate-limit-starve diagnostic first. The
26139        // rate-limit-starve arm reasons across the token-bucket
26140        // admission axis every rate-limited edge carries whether or
26141        // not `:retries` is declared, so its diagnostic is more
26142        // self-locating; the retries-saturate arm reasons across a
26143        // per-client retry-policy budget the starve arm does not
26144        // touch.
26145        //
26146        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
26147        // pair trips both: the rate structurally cannot deliver 5
26148        // failures per 10s breaker window, and simultaneously
26149        // one client's `retries + 1 = 6` attempts alone would
26150        // saturate the 5-`max_failures` threshold.
26151        let mut s = three_member_spec();
26152        s.politicas.timeout = None;
26153        s.politicas.retries = Some(5);
26154        s.politicas.circuit_breaker = Some(CircuitBreaker {
26155            max_failures: 5,
26156            window: Duration::from_secs(10),
26157        });
26158        s.politicas.rate_limit = Some(RateLimit {
26159            rate: 1,
26160            window: Duration::from_secs(3600),
26161        });
26162        assert_eq!(
26163            s.validate().unwrap_err(),
26164            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26165                rate: 1,
26166                rl_window: Duration::from_secs(3600),
26167                max_failures: 5,
26168                cb_window: Duration::from_secs(10),
26169            },
26170            "sibling :rate-limit-starve cross-axis arm must fire before the \
26171             retries-saturate arm when both apply"
26172        );
26173    }
26174
26175    #[test]
26176    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
26177        // Equivalence pin: the substrate-canonical
26178        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
26179        // predicate and the [`AplicacaoSpec::validate_politicas`]
26180        // cross-axis arm must discriminate the same set on every pair
26181        // covered by their shared invariant. A future refactor of
26182        // either side that breaks the equivalence trips here rather
26183        // than as a divergence between the predicate's Boolean answer
26184        // and the validate gate's Ok/Err arm — the same
26185        // predicate-vs-gate coherence discipline the sibling
26186        // [`MeshPolicy::breaker_window_observes_timeout`] and
26187        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
26188        // carry against `AplicacaoSpec::validate_politicas`. The
26189        // sweep covers both arms of the invariant (strictly below,
26190        // exactly at the boundary, strictly above) and both vacuous
26191        // arms (None `:retries`, None `:circuit-breaker`), so the
26192        // equivalence holds exhaustively over the axis-covered accept
26193        // and reject sets. Clears `:timeout` and `:rate-limit`
26194        // throughout so the sibling cross-axis arms are vacuous on
26195        // every input.
26196        let cb = |max_failures: u32| {
26197            Some(CircuitBreaker {
26198                max_failures,
26199                window: Duration::from_secs(60),
26200            })
26201        };
26202        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
26203            // saturating pairs (predicate = false, gate = Err)
26204            (Some(3), cb(3)),
26205            (Some(3), cb(1)),
26206            (Some(10), cb(5)),
26207            // boundary + coherent pairs (predicate = true, gate = Ok)
26208            (Some(3), cb(4)),
26209            (Some(1), cb(5)),
26210            (Some(3), cb(20)),
26211            // vacuous arms
26212            (None, cb(1)),
26213            (Some(10), None),
26214            (None, None),
26215        ];
26216        for (retries, circuit_breaker) in cases.iter().copied() {
26217            let politicas = MeshPolicy {
26218                retries,
26219                circuit_breaker,
26220                ..Default::default()
26221            };
26222            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
26223
26224            let mut s = three_member_spec();
26225            s.politicas = politicas.clone();
26226            let gate_ok = !matches!(
26227                s.validate(),
26228                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
26229            );
26230
26231            assert_eq!(
26232                predicate, gate_ok,
26233                "predicate must agree with validate arm on pair \
26234                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
26235            );
26236        }
26237    }
26238
26239    #[test]
26240    fn rejects_rate_limit_cannot_admit_retry_burst() {
26241        // The fail-before-pass-after pin on the cross-axis
26242        // `(:retries, :rate-limit)` invariant. Each axis is
26243        // individually well-formed under its own per-axis bracket (both
26244        // above the zero floor, both below the cap), but the pair is a
26245        // structurally-truncated retry policy: one client's
26246        // `retries + 1 = 6` failing attempts consume 6 tokens from a
26247        // bucket that admits at most 3 per refill window, so the fourth
26248        // attempt onward is 429ed by the local rate limiter and the
26249        // declared retry policy is silently truncated by the same rate
26250        // limiter it feeds through — the substrate declared six
26251        // attempts and structurally allows three.
26252        //
26253        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
26254        // against `retry_policy.num_retries` carries the identical
26255        // relation; every production playbook that pairs the two axes
26256        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
26257        // capacity strictly above any single client's retry budget so
26258        // the limiter distinguishes one client's declared retries from
26259        // sustained multi-client load.
26260        //
26261        // Pin both the diagnostic arm and the payload values so a
26262        // future re-shape of the arm surfaces here as a deliberate
26263        // test edit. Clears `:timeout` and `:circuit-breaker` so the
26264        // sibling cross-axis
26265        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
26266        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
26267        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
26268        // arms do not fire first on the ordering-precedent they hold
26269        // over this arm.
26270        let mut s = three_member_spec();
26271        s.politicas.timeout = None;
26272        s.politicas.retries = Some(5);
26273        s.politicas.circuit_breaker = None;
26274        s.politicas.rate_limit = Some(RateLimit {
26275            rate: 3,
26276            window: Duration::from_secs(1),
26277        });
26278        assert_eq!(
26279            s.validate().unwrap_err(),
26280            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
26281                retries: 5,
26282                rate: 3,
26283            }
26284        );
26285    }
26286
26287    #[test]
26288    fn accepts_rate_limit_admits_retry_burst() {
26289        // Positive-control sweep across the production-playbook band
26290        // — every pair a real playbook recommends where the bucket
26291        // capacity is strictly above the client's retry budget must
26292        // validate. Envoy default `num_retries: 3` with 100/s (100
26293        // tokens per window admits 4 attempts per client with 96 to
26294        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
26295        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
26296        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
26297        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
26298        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
26299        // arms are vacuous on this sweep.
26300        for (retries, rate, secs) in [
26301            (3u32, 100u32, 1u64),
26302            (3, 50, 1),
26303            (2, 10, 1),
26304            (5, 1000, 1),
26305            (3, 1_000_000, 3600),
26306            (10, POLICY_RATE_LIMIT_MAX, 1),
26307        ] {
26308            let mut s = three_member_spec();
26309            s.politicas.timeout = None;
26310            s.politicas.retries = Some(retries);
26311            s.politicas.circuit_breaker = None;
26312            s.politicas.rate_limit = Some(RateLimit {
26313                rate,
26314                window: Duration::from_secs(secs),
26315            });
26316            s.validate().unwrap_or_else(|e| {
26317                panic!(
26318                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
26319                     must validate; got {e:?}"
26320                )
26321            });
26322        }
26323    }
26324
26325    #[test]
26326    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
26327        // Boundary pin: `rate == retries + 1` is the smallest bucket
26328        // capacity that structurally admits one client's exhausted
26329        // retries through completion (each attempt draws exactly one
26330        // token; `retries + 1` tokens available admits `retries + 1`
26331        // attempts, retries fully executed). The invariant is `>=`,
26332        // stated in the coherent direction `rate >= retries + 1`.
26333        // Catches a future off-by-one tightening to `rate > retries + 1`
26334        // that would drift the accept set away from the codified
26335        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
26336        let mut s = three_member_spec();
26337        s.politicas.timeout = None;
26338        s.politicas.retries = Some(3);
26339        s.politicas.circuit_breaker = None;
26340        s.politicas.rate_limit = Some(RateLimit {
26341            rate: 4,
26342            window: Duration::from_secs(1),
26343        });
26344        s.validate()
26345            .expect("rate == retries + 1 is the boundary accept case");
26346    }
26347
26348    #[test]
26349    fn rejects_rate_one_below_retry_burst() {
26350        // Off-by-one boundary pin: exactly one token short of the
26351        // retry burst is still structurally truncating (the invariant
26352        // is `>=`, so `<` refuses even a one-token shortfall).
26353        // `retries = 3` with `rate = 3` means one client's four
26354        // attempts consume four tokens from a three-token bucket —
26355        // the fourth attempt is 429ed. Catches a future relaxation to
26356        // `>` on the wrong side (`rate > retries`, accepting equal)
26357        // that would silently drift the accept boundary and admit a
26358        // structurally-truncated retry policy at the emit boundary.
26359        let mut s = three_member_spec();
26360        s.politicas.timeout = None;
26361        s.politicas.retries = Some(3);
26362        s.politicas.circuit_breaker = None;
26363        s.politicas.rate_limit = Some(RateLimit {
26364            rate: 3,
26365            window: Duration::from_secs(1),
26366        });
26367        assert_eq!(
26368            s.validate().unwrap_err(),
26369            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
26370                retries: 3,
26371                rate: 3,
26372            }
26373        );
26374    }
26375
26376    #[test]
26377    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
26378        // The predicate is vacuously `true` when `:retries` is None —
26379        // a `:rate-limit` alone declares a token-bucket rate whose
26380        // per-client attempt count is unconstrained by the substrate,
26381        // so no per-client saturation bound on tokens-per-client-call
26382        // is knowable at author time. The substrate takes no position
26383        // on whether an omitted `:retries` axis means zero retries or
26384        // "the client picks its own retry policy" — either way, the
26385        // pair is undeclared and the cross-axis gate has nothing to
26386        // check. Pin so a future tightening that made the gate
26387        // opinionated on half-declared pairs surfaces here.
26388        let mut s = three_member_spec();
26389        s.politicas.timeout = None;
26390        s.politicas.retries = None;
26391        s.politicas.circuit_breaker = None;
26392        s.politicas.rate_limit = Some(RateLimit {
26393            rate: 1,
26394            window: Duration::from_secs(1),
26395        });
26396        s.validate().expect(
26397            "cross-axis burst gate must be vacuous when :retries is None, \
26398             however low :rate is",
26399        );
26400    }
26401
26402    #[test]
26403    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
26404        // Peer of the sibling `:retries`-absent case: a `:retries`
26405        // without a `:rate-limit` declares a client-retry policy with
26406        // no rate limiter to saturate, so the pair is undeclared and
26407        // the cross-axis gate has nothing to check. Uses
26408        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
26409        // authored retry budget the per-axis cap admits — a `:retries
26410        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
26411        // or not `:rate-limit` is declared.
26412        let mut s = three_member_spec();
26413        s.politicas.timeout = None;
26414        s.politicas.retries = Some(POLICY_RETRIES_MAX);
26415        s.politicas.circuit_breaker = None;
26416        s.politicas.rate_limit = None;
26417        s.validate().expect(
26418            "cross-axis burst gate must be vacuous when :rate-limit is None, \
26419             however high :retries is",
26420        );
26421    }
26422
26423    #[test]
26424    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
26425        // Ordering pin: a pair whose retries is *both* zero-floor-
26426        // violating and structurally below the retry-burst threshold
26427        // must surface the per-axis zero-floor arm first — the
26428        // zero-floor diagnostic is more self-locating (its omit-axis
26429        // remediation is directly named), where the cross-axis arm
26430        // would send the author to reconcile two values one of which
26431        // is not a meaningful retry count at all. Same ordering
26432        // discipline every per-axis bracket carries internally
26433        // (zero-floor before canonical-form before cap), and the
26434        // sibling cross-axis
26435        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
26436        // ordering pin on the `(:retries, :max-failures)` pair.
26437        let mut s = three_member_spec();
26438        s.politicas.timeout = None;
26439        s.politicas.retries = Some(0);
26440        s.politicas.circuit_breaker = None;
26441        s.politicas.rate_limit = Some(RateLimit {
26442            rate: 1,
26443            window: Duration::from_secs(1),
26444        });
26445        assert_eq!(
26446            s.validate().unwrap_err(),
26447            AplicacaoError::PolicyRetriesZero,
26448            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
26449        );
26450    }
26451
26452    #[test]
26453    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
26454        // Cross-axis ordering pin: a `:politicas` whose axes trip
26455        // BOTH cross-axis arms — `:rate-limit` starves the breaker
26456        // within `:window` (the sibling
26457        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
26458        // `:retries + 1` exceeds the bucket capacity (this arm) —
26459        // must surface the rate-limit-starve diagnostic first. The
26460        // starve arm is the token-bucket admission invariant every
26461        // rate-limited edge carries against the breaker whether or
26462        // not `:retries` is declared, so its diagnostic is more
26463        // self-locating; the burst arm reasons across a per-client
26464        // retry-policy budget the starve arm does not touch. Same
26465        // "more foundational cross-axis first" ordering discipline the
26466        // sibling
26467        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
26468        // pin on the peer pair carries.
26469        //
26470        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
26471        // pair trips both: the rate structurally cannot deliver 5
26472        // failures per 10s breaker window (starve arm), and
26473        // simultaneously one client's `retries + 1 = 6` attempts alone
26474        // would exhaust the 1-token bucket (burst arm).
26475        let mut s = three_member_spec();
26476        s.politicas.timeout = None;
26477        s.politicas.retries = Some(5);
26478        s.politicas.circuit_breaker = Some(CircuitBreaker {
26479            max_failures: 5,
26480            window: Duration::from_secs(10),
26481        });
26482        s.politicas.rate_limit = Some(RateLimit {
26483            rate: 1,
26484            window: Duration::from_secs(3600),
26485        });
26486        assert_eq!(
26487            s.validate().unwrap_err(),
26488            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26489                rate: 1,
26490                rl_window: Duration::from_secs(3600),
26491                max_failures: 5,
26492                cb_window: Duration::from_secs(10),
26493            },
26494            "sibling :rate-limit-starve cross-axis arm must fire before the \
26495             burst arm when both apply"
26496        );
26497    }
26498
26499    #[test]
26500    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
26501        // Cross-axis ordering pin: a `:politicas` whose axes trip
26502        // BOTH the retries-saturate arm and this burst arm — one
26503        // client's `retries + 1` failures saturate the breaker's trip
26504        // threshold (the sibling
26505        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
26506        // `retries + 1` exceeds the bucket capacity (this arm) —
26507        // must surface the retries-saturate diagnostic first. The
26508        // saturate arm is the per-client-vs-breaker relation every
26509        // retry-with-breaker pair carries whether or not `:rate-limit`
26510        // is declared, so its diagnostic is more self-locating; the
26511        // burst arm reasons across the rate-limit token-bucket
26512        // admission axis the saturate arm does not touch. Same
26513        // "more foundational cross-axis first" ordering discipline
26514        // carries here.
26515        //
26516        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
26517        // rate: 3/s }` pair trips both: the breaker's `max_failures
26518        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
26519        // one client's `retries + 1 = 6` attempts alone would exhaust
26520        // the 3-token bucket (burst arm). Clears `:timeout` so the
26521        // sibling `:window<:timeout` gate is vacuous, and the
26522        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
26523        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
26524        // the arm that fires first.
26525        let mut s = three_member_spec();
26526        s.politicas.timeout = None;
26527        s.politicas.retries = Some(5);
26528        s.politicas.circuit_breaker = Some(CircuitBreaker {
26529            max_failures: 3,
26530            window: Duration::from_secs(60),
26531        });
26532        s.politicas.rate_limit = Some(RateLimit {
26533            rate: 3,
26534            window: Duration::from_secs(1),
26535        });
26536        assert_eq!(
26537            s.validate().unwrap_err(),
26538            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
26539                retries: 5,
26540                max_failures: 3,
26541            },
26542            "sibling :retries-saturate cross-axis arm must fire before the \
26543             burst arm when both apply"
26544        );
26545    }
26546
26547    #[test]
26548    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
26549        // Equivalence pin: the substrate-canonical
26550        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
26551        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
26552        // must discriminate the same set on every pair covered by
26553        // their shared invariant. A future refactor of either side
26554        // that breaks the equivalence trips here rather than as a
26555        // divergence between the predicate's Boolean answer and the
26556        // validate gate's Ok/Err arm — the same predicate-vs-gate
26557        // coherence discipline the three sibling cross-axis
26558        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
26559        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
26560        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
26561        // carry against `AplicacaoSpec::validate_politicas`. The sweep
26562        // covers both arms of the invariant (strictly below, exactly
26563        // at the boundary, strictly above) and both vacuous arms
26564        // (None `:retries`, None `:rate-limit`), so the equivalence
26565        // holds exhaustively over the axis-covered accept and reject
26566        // sets. Clears `:timeout` and `:circuit-breaker` throughout
26567        // so the three sibling cross-axis arms are vacuous on every
26568        // input.
26569        let rl = |rate: u32, secs: u64| {
26570            Some(RateLimit {
26571                rate,
26572                window: Duration::from_secs(secs),
26573            })
26574        };
26575        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
26576            // burst-exceeding pairs (predicate = false, gate = Err)
26577            (Some(3), rl(3, 1)),
26578            (Some(5), rl(1, 1)),
26579            (Some(10), rl(5, 1)),
26580            // boundary + coherent pairs (predicate = true, gate = Ok)
26581            (Some(3), rl(4, 1)),
26582            (Some(1), rl(5, 1)),
26583            (Some(3), rl(1_000_000, 3600)),
26584            // vacuous arms
26585            (None, rl(1, 1)),
26586            (Some(10), None),
26587            (None, None),
26588        ];
26589        for (retries, rate_limit) in cases.iter().copied() {
26590            let politicas = MeshPolicy {
26591                retries,
26592                rate_limit,
26593                ..Default::default()
26594            };
26595            let predicate = politicas.rate_limit_admits_retry_burst();
26596
26597            let mut s = three_member_spec();
26598            s.politicas = politicas.clone();
26599            let gate_ok = !matches!(
26600                s.validate(),
26601                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
26602            );
26603
26604            assert_eq!(
26605                predicate, gate_ok,
26606                "predicate must agree with validate arm on pair \
26607                 (retries={retries:?}, rate_limit={rate_limit:?})"
26608            );
26609        }
26610    }
26611
26612    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
26613    /// equivalence pin — assert that on each `(label, politicas,
26614    /// expected)` case the substrate-canonical fold and the validate
26615    /// cascade agree byte-for-byte. Extracted so each pin's own body
26616    /// stays under `clippy::too_many_lines`.
26617    fn assert_first_cross_axis_violation_agrees_with_gate(
26618        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
26619    ) {
26620        for (label, politicas, expected) in cases {
26621            let fold = politicas.first_cross_axis_violation();
26622            assert_eq!(
26623                fold.as_ref(),
26624                expected.as_ref(),
26625                "fold must return {expected:?} on `{label}`; got {fold:?}"
26626            );
26627
26628            let mut s = three_member_spec();
26629            s.politicas = politicas.clone();
26630            let gate = s.validate();
26631            match expected {
26632                None => {
26633                    // No cross-axis violation: validate must pass (the
26634                    // per-axis brackets pass by construction on every
26635                    // fixture above; every fixture's non-`:politicas`
26636                    // slots come from `three_member_spec`).
26637                    gate.as_ref()
26638                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
26639                }
26640                Some(want) => {
26641                    let got =
26642                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
26643                    assert_eq!(
26644                        &got, want,
26645                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
26646                    );
26647                }
26648            }
26649        }
26650    }
26651
26652    #[test]
26653    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
26654        // Equivalence pin on the compound cross-axis fold: the
26655        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
26656        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
26657        // cascade must return identical `AplicacaoError` variants on
26658        // every axis-covered input — the "compound-fold ≡ gate"
26659        // contract that generalizes the four sibling per-arm pins
26660        // onto the compound primitive that folds all four. A future
26661        // refactor of either side that breaks the equivalence trips
26662        // here rather than as a divergence between what the substrate
26663        // primitive answers and what `feira build` accepts.
26664        //
26665        // Half-A of the sweep: every single-arm violation (one arm
26666        // fires with the three sibling arms vacuous), the vacuous
26667        // shape (empty policy — no arm fires), and the fully-coherent
26668        // shape (every axis declared inside the coherence surface —
26669        // no arm fires). Half-B (pairwise-ordering coverage — the
26670        // "which arm wins when two apply" contract) lives in the
26671        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
26672        // pin; splitting keeps each pin's body under
26673        // `clippy::too_many_lines`.
26674        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
26675            max_failures,
26676            window: Duration::from_secs(secs),
26677        };
26678        let rl = |rate: u32, secs: u64| RateLimit {
26679            rate,
26680            window: Duration::from_secs(secs),
26681        };
26682        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
26683            (
26684                "window-below-timeout only",
26685                MeshPolicy {
26686                    timeout: Some(Duration::from_secs(30)),
26687                    circuit_breaker: Some(cb(5, 10)),
26688                    ..Default::default()
26689                },
26690                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26691                    window: Duration::from_secs(10),
26692                    timeout: Duration::from_secs(30),
26693                }),
26694            ),
26695            (
26696                "starve only",
26697                MeshPolicy {
26698                    rate_limit: Some(rl(1, 3600)),
26699                    circuit_breaker: Some(cb(5, 10)),
26700                    ..Default::default()
26701                },
26702                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26703                    rate: 1,
26704                    rl_window: Duration::from_secs(3600),
26705                    max_failures: 5,
26706                    cb_window: Duration::from_secs(10),
26707                }),
26708            ),
26709            (
26710                "retries-saturate only",
26711                MeshPolicy {
26712                    retries: Some(3),
26713                    circuit_breaker: Some(cb(3, 60)),
26714                    ..Default::default()
26715                },
26716                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
26717                    retries: 3,
26718                    max_failures: 3,
26719                }),
26720            ),
26721            (
26722                "retries-burst only",
26723                MeshPolicy {
26724                    retries: Some(5),
26725                    rate_limit: Some(rl(3, 1)),
26726                    ..Default::default()
26727                },
26728                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
26729                    retries: 5,
26730                    rate: 3,
26731                }),
26732            ),
26733            ("empty policy", MeshPolicy::default(), None),
26734            (
26735                "fully-coherent policy",
26736                MeshPolicy {
26737                    timeout: Some(Duration::from_secs(30)),
26738                    retries: Some(3),
26739                    circuit_breaker: Some(cb(5, 60)),
26740                    mtls_required: Some(true),
26741                    rate_limit: Some(rl(100, 1)),
26742                },
26743                None,
26744            ),
26745        ];
26746        assert_first_cross_axis_violation_agrees_with_gate(cases);
26747    }
26748
26749    #[test]
26750    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
26751        // Half-B of the compound-fold ≡ gate equivalence pin: the
26752        // load-bearing pairwise-ordering coverage. Every ordered pair
26753        // of the four cross-axis arms — six combinations — where two
26754        // arms are simultaneously eligible must surface the
26755        // more-foundational arm's diagnostic verbatim. Pins the fold's
26756        // arm-ordering byte-for-byte against the validate cascade's
26757        // arm-ordering, so a future reshuffle of either side that
26758        // silently drifts the ordering trips here rather than as a
26759        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
26760        // pins cannot catch (they clear every sibling arm, so their
26761        // sweeps are pairwise-ordering-agnostic by construction).
26762        //
26763        // The six pairs the four-arm cascade admits:
26764        // window-before-starve, window-before-saturate,
26765        // window-before-burst, starve-before-saturate,
26766        // starve-before-burst, saturate-before-burst.
26767        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
26768            max_failures,
26769            window: Duration::from_secs(secs),
26770        };
26771        let rl = |rate: u32, secs: u64| RateLimit {
26772            rate,
26773            window: Duration::from_secs(secs),
26774        };
26775        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
26776            (
26777                "window+starve → window wins",
26778                MeshPolicy {
26779                    timeout: Some(Duration::from_secs(30)),
26780                    rate_limit: Some(rl(1, 3600)),
26781                    circuit_breaker: Some(cb(5, 10)),
26782                    ..Default::default()
26783                },
26784                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26785                    window: Duration::from_secs(10),
26786                    timeout: Duration::from_secs(30),
26787                }),
26788            ),
26789            (
26790                "window+retries-saturate → window wins",
26791                MeshPolicy {
26792                    timeout: Some(Duration::from_secs(30)),
26793                    retries: Some(5),
26794                    circuit_breaker: Some(cb(3, 10)),
26795                    ..Default::default()
26796                },
26797                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26798                    window: Duration::from_secs(10),
26799                    timeout: Duration::from_secs(30),
26800                }),
26801            ),
26802            (
26803                "window+retries-burst → window wins",
26804                MeshPolicy {
26805                    timeout: Some(Duration::from_secs(30)),
26806                    retries: Some(5),
26807                    rate_limit: Some(rl(3, 1)),
26808                    circuit_breaker: Some(cb(5, 10)),
26809                    ..Default::default()
26810                },
26811                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26812                    window: Duration::from_secs(10),
26813                    timeout: Duration::from_secs(30),
26814                }),
26815            ),
26816            (
26817                "starve+retries-saturate → starve wins",
26818                MeshPolicy {
26819                    retries: Some(5),
26820                    rate_limit: Some(rl(1, 3600)),
26821                    circuit_breaker: Some(cb(5, 10)),
26822                    ..Default::default()
26823                },
26824                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26825                    rate: 1,
26826                    rl_window: Duration::from_secs(3600),
26827                    max_failures: 5,
26828                    cb_window: Duration::from_secs(10),
26829                }),
26830            ),
26831            (
26832                "starve+retries-burst → starve wins",
26833                MeshPolicy {
26834                    retries: Some(5),
26835                    rate_limit: Some(rl(1, 3600)),
26836                    circuit_breaker: Some(cb(10, 10)),
26837                    ..Default::default()
26838                },
26839                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26840                    rate: 1,
26841                    rl_window: Duration::from_secs(3600),
26842                    max_failures: 10,
26843                    cb_window: Duration::from_secs(10),
26844                }),
26845            ),
26846            (
26847                "retries-saturate+retries-burst → saturate wins",
26848                MeshPolicy {
26849                    retries: Some(5),
26850                    rate_limit: Some(rl(3, 1)),
26851                    circuit_breaker: Some(cb(3, 60)),
26852                    ..Default::default()
26853                },
26854                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
26855                    retries: 5,
26856                    max_failures: 3,
26857                }),
26858            ),
26859        ];
26860        assert_first_cross_axis_violation_agrees_with_gate(cases);
26861    }
26862
26863    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
26864    /// equivalence pin — assert that on each `(label, politicas,
26865    /// expected)` case both the substrate primitive
26866    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
26867    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
26868    /// same `three_member_spec` fixture whose non-`:politicas` slots
26869    /// always validate cleanly) return identical `AplicacaoError` variants.
26870    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
26871    /// the sibling cross-axis-only surface — extended here onto the
26872    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
26873    /// own body stays under `clippy::too_many_lines`.
26874    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
26875        for (label, politicas, expected) in cases {
26876            let direct = politicas.validate();
26877            match (expected, &direct) {
26878                (None, Ok(())) => {}
26879                (None, Err(got)) => {
26880                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
26881                }
26882                (Some(want), Ok(())) => {
26883                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
26884                }
26885                (Some(want), Err(got)) => assert_eq!(
26886                    got, want,
26887                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
26888                ),
26889            }
26890
26891            let mut s = three_member_spec();
26892            s.politicas = politicas.clone();
26893            let gate = s.validate();
26894            match (expected, &gate) {
26895                (None, Ok(())) => {}
26896                (None, Err(got)) => {
26897                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
26898                }
26899                (Some(want), Ok(())) => {
26900                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
26901                }
26902                (Some(want), Err(got)) => assert_eq!(
26903                    got, want,
26904                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
26905                ),
26906            }
26907        }
26908    }
26909
26910    #[test]
26911    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
26912        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
26913        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
26914        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
26915        // :max-failures`, `:rate-limit` rate) that discriminate the
26916        // "per-axis phase fires" arm of the compound gate, plus one
26917        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
26918        // ZERO }`) that pins the phase-boundary ordering — the per-axis
26919        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
26920        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
26921        // diagnostic wins over the window-below-timeout diagnostic. Peer
26922        // of the sibling
26923        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
26924        // + `_on_pairwise_orderings` pins on the compound cross-axis
26925        // fold, extended here onto the outer compound entry gate that
26926        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
26927        // clean-pass surfaces) lives in the sibling
26928        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
26929        // pin; splitting keeps each pin's body under
26930        // `clippy::too_many_lines`.
26931        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
26932            (
26933                "per-axis: timeout zero",
26934                MeshPolicy {
26935                    timeout: Some(Duration::ZERO),
26936                    ..Default::default()
26937                },
26938                Some(AplicacaoError::PolicyTimeoutZero),
26939            ),
26940            (
26941                "per-axis: retries zero",
26942                MeshPolicy {
26943                    retries: Some(0),
26944                    ..Default::default()
26945                },
26946                Some(AplicacaoError::PolicyRetriesZero),
26947            ),
26948            (
26949                "per-axis: breaker max-failures zero",
26950                MeshPolicy {
26951                    circuit_breaker: Some(CircuitBreaker {
26952                        max_failures: 0,
26953                        window: Duration::from_secs(60),
26954                    }),
26955                    ..Default::default()
26956                },
26957                Some(AplicacaoError::PolicyBreakerZeroFailures),
26958            ),
26959            (
26960                "per-axis: rate-limit rate zero",
26961                MeshPolicy {
26962                    rate_limit: Some(RateLimit {
26963                        rate: 0,
26964                        window: Duration::from_secs(1),
26965                    }),
26966                    ..Default::default()
26967                },
26968                Some(AplicacaoError::PolicyRateLimitZero),
26969            ),
26970            (
26971                "per-axis before cross-axis: zero-window wins over window-below-timeout",
26972                MeshPolicy {
26973                    timeout: Some(Duration::from_secs(30)),
26974                    circuit_breaker: Some(CircuitBreaker {
26975                        max_failures: 5,
26976                        window: Duration::ZERO,
26977                    }),
26978                    ..Default::default()
26979                },
26980                Some(AplicacaoError::PolicyBreakerZeroWindow),
26981            ),
26982        ];
26983        assert_validate_matches_gate(cases);
26984    }
26985
26986    #[test]
26987    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
26988        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
26989        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
26990        // arm that discriminates the "cross-axis phase fires" arm of
26991        // the compound gate (window-below-timeout — sibling per-arm
26992        // coverage lives in the two
26993        // `first_cross_axis_violation_matches_gate_on_*` pins above),
26994        // plus the two clean-pass shapes (empty policy — every axis
26995        // absent — and fully-coherent — every axis inside the coherence
26996        // surface) that pin the compound gate's `Ok(())` arm. Half-A
26997        // (per-axis + phase-boundary surfaces) lives in the sibling
26998        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
26999        // pin; splitting keeps each pin's body under
27000        // `clippy::too_many_lines`.
27001        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
27002            (
27003                "cross-axis: window-below-timeout",
27004                MeshPolicy {
27005                    timeout: Some(Duration::from_secs(30)),
27006                    circuit_breaker: Some(CircuitBreaker {
27007                        max_failures: 5,
27008                        window: Duration::from_secs(10),
27009                    }),
27010                    ..Default::default()
27011                },
27012                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
27013                    window: Duration::from_secs(10),
27014                    timeout: Duration::from_secs(30),
27015                }),
27016            ),
27017            ("clean pass: empty policy", MeshPolicy::default(), None),
27018            (
27019                "clean pass: every axis coherent",
27020                MeshPolicy {
27021                    timeout: Some(Duration::from_secs(30)),
27022                    retries: Some(3),
27023                    circuit_breaker: Some(CircuitBreaker {
27024                        max_failures: 5,
27025                        window: Duration::from_secs(60),
27026                    }),
27027                    mtls_required: Some(true),
27028                    rate_limit: Some(RateLimit {
27029                        rate: 100,
27030                        window: Duration::from_secs(1),
27031                    }),
27032                },
27033                None,
27034            ),
27035        ];
27036        assert_validate_matches_gate(cases);
27037    }
27038
27039    #[test]
27040    fn empty_politicas_validates() {
27041        // Omitting every policy axis is fine — defaults express "no
27042        // policy on this axis", not "policy = 0". The fixture's typical
27043        // values continue to validate; this test pins that
27044        // MeshPolicy::default() is a clean pass through validate().
27045        let mut s = three_member_spec();
27046        s.politicas = MeshPolicy::default();
27047        s.validate().unwrap();
27048    }
27049
27050    #[test]
27051    fn typical_politicas_validates_with_every_axis_set() {
27052        // The full §III.1 example block (timeout + retries + breaker +
27053        // mtls + rate-limit) — every axis nonzero — must remain a
27054        // clean pass.
27055        let mut s = three_member_spec();
27056        s.politicas = MeshPolicy {
27057            timeout: Some(Duration::from_secs(30)),
27058            retries: Some(3),
27059            circuit_breaker: Some(CircuitBreaker {
27060                max_failures: 5,
27061                window: Duration::from_secs(60),
27062            }),
27063            mtls_required: Some(true),
27064            rate_limit: Some(RateLimit {
27065                rate: 100,
27066                window: Duration::from_secs(1),
27067            }),
27068        };
27069        s.validate().unwrap();
27070    }
27071
27072    #[test]
27073    fn rejects_empty_cluster_name() {
27074        let mut s = three_member_spec();
27075        s.placement.clusters = vec!["rio".into(), String::new()];
27076        assert_eq!(
27077            s.validate().unwrap_err(),
27078            AplicacaoError::PlacementClusterEmpty
27079        );
27080    }
27081
27082    #[test]
27083    fn rejects_duplicate_cluster_names() {
27084        let mut s = three_member_spec();
27085        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
27086        let err = s.validate().unwrap_err();
27087        assert!(
27088            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
27089            "got {err:?}"
27090        );
27091    }
27092
27093    #[test]
27094    fn rejects_placement_cluster_with_uppercase() {
27095        // The canonical "I copied the cluster's display name verbatim"
27096        // typo — K8s context names are lowercase per DNS-1123 label
27097        // rule, but org docs often round-trip a TitleCase identifier
27098        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
27099        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
27100        // on the peer name axis.
27101        let mut s = three_member_spec();
27102        s.placement.clusters = vec!["Rio".into(), "mar".into()];
27103        let err = s.validate().unwrap_err();
27104        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
27105            panic!("expected PlacementClusterInvalid, got other variant");
27106        };
27107        assert_eq!(cluster, "Rio");
27108        assert!(
27109            reason.contains("uppercase"),
27110            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
27111        );
27112        assert!(
27113            reason.contains("\"rio\""),
27114            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
27115        );
27116    }
27117
27118    #[test]
27119    fn rejects_placement_cluster_with_underscore() {
27120        // The canonical "I'm thinking of an env var / hostname slug"
27121        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
27122        // schema. K8s context filtering on `my_cluster` silently misses
27123        // the cluster the author intended; the gate moves it to caixa-
27124        // build time. Same shape as `rejects_membro_caixa_with_underscore`
27125        // (3f9d7a0).
27126        let mut s = three_member_spec();
27127        s.placement.clusters = vec!["my_cluster".into()];
27128        let err = s.validate().unwrap_err();
27129        assert!(
27130            matches!(
27131                err,
27132                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
27133                    if cluster == "my_cluster" && reason.contains('_')
27134            ),
27135            "got {err:?}"
27136        );
27137    }
27138
27139    #[test]
27140    fn rejects_placement_cluster_with_dot() {
27141        // A `:placement :clusters` entry is a single DNS-1123 *label*,
27142        // not a subdomain — even though K8s context names sometimes
27143        // carry a dotted form via kubeconfig conventions, the strictest
27144        // floor among the use sites (DNS-1035 cluster.x-k8s.io
27145        // `metadata.name`, Cilium identity label values) wins. The "I
27146        // want to namespace my cluster names with `.`" intent is
27147        // expressed via `-` (`mar-east`).
27148        let mut s = three_member_spec();
27149        s.placement.clusters = vec!["team.rio".into()];
27150        let err = s.validate().unwrap_err();
27151        assert!(
27152            matches!(
27153                err,
27154                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
27155                    if cluster == "team.rio" && reason.contains('.')
27156            ),
27157            "got {err:?}"
27158        );
27159    }
27160
27161    #[test]
27162    fn rejects_placement_cluster_with_leading_hyphen() {
27163        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
27164        // with an alphanumeric. The K8s apiserver rejects `-rio`
27165        // outright; the rendered fan-out would emit a `metadata.name:
27166        // "-rio"` that fails admission far from the source caixa.lisp.
27167        let mut s = three_member_spec();
27168        s.placement.clusters = vec!["-rio".into()];
27169        let err = s.validate().unwrap_err();
27170        assert!(
27171            matches!(
27172                err,
27173                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
27174                    if cluster == "-rio" && reason.contains("start and end")
27175            ),
27176            "got {err:?}"
27177        );
27178    }
27179
27180    #[test]
27181    fn rejects_placement_cluster_with_trailing_hyphen() {
27182        // The symmetric arm of the boundary rule. Pin separately so
27183        // both ends are covered against a future relaxation that only
27184        // checks one boundary (parallel to
27185        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
27186        let mut s = three_member_spec();
27187        s.placement.clusters = vec!["rio-".into()];
27188        let err = s.validate().unwrap_err();
27189        assert!(
27190            matches!(
27191                err,
27192                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
27193                    if cluster == "rio-"
27194            ),
27195            "got {err:?}"
27196        );
27197    }
27198
27199    #[test]
27200    fn rejects_placement_cluster_with_unicode() {
27201        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
27202        // before it reaches K8s. The byte-by-byte ASCII validity check
27203        // rejects multi-byte UTF-8 sequences by the first byte that
27204        // fails `[a-z0-9-]`.
27205        let mut s = three_member_spec();
27206        s.placement.clusters = vec!["rió".into()];
27207        let err = s.validate().unwrap_err();
27208        assert!(
27209            matches!(
27210                err,
27211                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
27212                    if cluster == "rió"
27213            ),
27214            "got {err:?}"
27215        );
27216    }
27217
27218    #[test]
27219    fn rejects_placement_cluster_with_whitespace() {
27220        // Whitespace is the canonical "I pasted from a sketch / doc"
27221        // footgun. The apiserver rejects every cluster `metadata.name`
27222        // value carrying whitespace.
27223        let mut s = three_member_spec();
27224        s.placement.clusters = vec!["rio cluster".into()];
27225        let err = s.validate().unwrap_err();
27226        assert!(
27227            matches!(
27228                err,
27229                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
27230                    if cluster == "rio cluster"
27231            ),
27232            "got {err:?}"
27233        );
27234    }
27235
27236    #[test]
27237    fn rejects_placement_cluster_too_long() {
27238        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
27239        // pin. The diagnostic names both the cap (63) and the actual
27240        // length so the author can shorten in one edit. Mirrors
27241        // `rejects_membro_caixa_too_long` (3f9d7a0).
27242        let mut s = three_member_spec();
27243        let too_long = "a".repeat(64);
27244        s.placement.clusters = vec![too_long.clone()];
27245        let err = s.validate().unwrap_err();
27246        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
27247            panic!("expected PlacementClusterInvalid");
27248        };
27249        assert_eq!(cluster, too_long);
27250        assert!(
27251            reason.contains("63") && reason.contains("64"),
27252            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
27253        );
27254    }
27255
27256    #[test]
27257    fn placement_cluster_max_length_validates() {
27258        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
27259        // future tightening (e.g. dropping to 62) surfaces here as a
27260        // regression, mirroring `membro_caixa_max_length_validates`
27261        // (3f9d7a0).
27262        let mut s = three_member_spec();
27263        s.placement.clusters = vec!["a".repeat(63)];
27264        s.validate().unwrap();
27265    }
27266
27267    #[test]
27268    fn accepts_canonical_placement_cluster_forms() {
27269        // The DNS-1123 label shapes a caixa author is realistically
27270        // going to write for cluster names: single-word lowercase
27271        // (`rio`), regional hyphen-joined (`mar-east`), single
27272        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
27273        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
27274        // Pin every leg so a future tightening that bans (e.g.) digit-
27275        // start identifiers surfaces here.
27276        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
27277            let mut s = three_member_spec();
27278            s.placement.clusters = vec![form.into()];
27279            s.validate().unwrap_or_else(|e| {
27280                panic!("canonical cluster form {form:?} must validate, got {e:?}")
27281            });
27282        }
27283    }
27284
27285    #[test]
27286    fn placement_cluster_empty_takes_precedence_over_invalid() {
27287        // Order pin: the existing `PlacementClusterEmpty` diagnostic
27288        // (which doesn't try to parse) fires before the new
27289        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
27290        // `:clusters` entry keeps its narrower error message — the new
27291        // gate would also reject `""`, but the empty-string arm is the
27292        // more self-locating diagnostic. Mirrors the
27293        // `membro_caixa_empty_takes_precedence_over_invalid` pin
27294        // (3f9d7a0).
27295        let mut s = three_member_spec();
27296        s.placement.clusters = vec!["rio".into(), String::new()];
27297        let err = s.validate().unwrap_err();
27298        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
27299    }
27300
27301    #[test]
27302    fn placement_cluster_invalid_fires_before_duplicate_check() {
27303        // Order pin: a malformed-shape `:clusters` entry surfaces *its
27304        // own* diagnostic, even when a later entry would otherwise
27305        // collapse onto a duplicate name. The per-entry shape gate runs
27306        // inline before the duplicate-key insert, parallel to
27307        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
27308        let mut s = three_member_spec();
27309        s.placement.clusters = vec!["Rio".into(), "rio".into()];
27310        let err = s.validate().unwrap_err();
27311        assert!(
27312            matches!(
27313                err,
27314                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
27315            ),
27316            "got {err:?}"
27317        );
27318    }
27319
27320    #[test]
27321    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
27322        // The diagnostic-shape pin: the error names the offending
27323        // `:clusters` value verbatim so the author can grep their
27324        // caixa.lisp without re-running the build, and carries a
27325        // non-empty `reason` naming the specific violation. Same shape
27326        // every typed-shape gate enshrines
27327        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
27328        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
27329        let mut s = three_member_spec();
27330        s.placement.clusters = vec!["BAD_CLUSTER".into()];
27331        let err = s.validate().unwrap_err();
27332        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
27333            panic!("expected PlacementClusterInvalid");
27334        };
27335        assert_eq!(cluster, "BAD_CLUSTER");
27336        assert!(
27337            !reason.is_empty(),
27338            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
27339        );
27340    }
27341
27342    #[test]
27343    fn rejects_sharded_with_empty_clusters() {
27344        // §III.1: Sharded uses :clusters as the shard pool. An empty
27345        // pool means "shard across no clusters" — meaningless, same as
27346        // Replicated with no hosts.
27347        let mut s = three_member_spec();
27348        s.placement.estrategia = PlacementStrategy::Sharded;
27349        s.placement.shard_key = Some("$tenantId".into());
27350        s.placement.clusters = vec![];
27351        assert!(matches!(
27352            s.validate().unwrap_err(),
27353            AplicacaoError::PlacementWithoutClusters {
27354                estrategia: PlacementStrategy::Sharded
27355            }
27356        ));
27357    }
27358
27359    #[test]
27360    fn rejects_sharded_with_empty_shard_key() {
27361        let mut s = three_member_spec();
27362        s.placement.estrategia = PlacementStrategy::Sharded;
27363        s.placement.shard_key = Some(String::new());
27364        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
27365    }
27366
27367    #[test]
27368    fn rejects_shard_key_under_replicated_strategy() {
27369        // The fail-before-pass-after pin: a `:placement (:estrategia
27370        // Replicated :shard-key "tenantId")` manifest carries the
27371        // hash-keyed-distribution slot on a strategy that never consumes
27372        // it. Before the gate the typed slot's value silently vanished
27373        // at the renderer layer (caixa-mesh emits `placement.shardKey`
27374        // verbatim regardless of strategy; the Akka-style cluster-
27375        // sharding reconciler keys off `estrategia == Sharded` and
27376        // ignores the slot otherwise), with no diagnostic. Lifting the
27377        // rejection to a build-time gate makes the
27378        // `shard_key.is_some() == matches!(estrategia, Sharded)`
27379        // partition a structural property of every validated
27380        // [`Placement`].
27381        let mut s = three_member_spec();
27382        // The fixture already uses Replicated; just add a shard-key.
27383        s.placement.shard_key = Some("$tenantId".into());
27384        let err = s.validate().unwrap_err();
27385        let AplicacaoError::ShardKeyOnNonSharded {
27386            estrategia,
27387            shard_key,
27388        } = err
27389        else {
27390            panic!("expected ShardKeyOnNonSharded, got {err:?}");
27391        };
27392        assert_eq!(estrategia, PlacementStrategy::Replicated);
27393        assert_eq!(shard_key, "$tenantId");
27394    }
27395
27396    #[test]
27397    fn rejects_shard_key_under_singlenode_strategy() {
27398        // Peer of the Replicated case above on the SingleNode arm: OTP
27399        // distributed-app takeover (one cluster runs at a time) has no
27400        // hash-keyed routing axis to consume `:shard-key` either, so
27401        // the rejection fires on both non-Sharded arms uniformly.
27402        let mut s = three_member_spec();
27403        s.placement.estrategia = PlacementStrategy::SingleNode;
27404        s.placement.shard_key = Some("$tenantId".into());
27405        let err = s.validate().unwrap_err();
27406        let AplicacaoError::ShardKeyOnNonSharded {
27407            estrategia,
27408            shard_key,
27409        } = err
27410        else {
27411            panic!("expected ShardKeyOnNonSharded, got {err:?}");
27412        };
27413        assert_eq!(estrategia, PlacementStrategy::SingleNode);
27414        assert_eq!(shard_key, "$tenantId");
27415    }
27416
27417    #[test]
27418    fn rejects_empty_shard_key_under_replicated_strategy() {
27419        // The `Some("")` case under non-Sharded is rejected by
27420        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
27421        // fires before the empty-value gate), not
27422        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
27423        // the `Sharded` arm). Pin the partition so a future reorder of
27424        // the validate_placement match arms doesn't silently swap which
27425        // diagnostic the author sees — both are author errors, but
27426        // ShardKeyOnNonSharded names which strategy is the actual fix
27427        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
27428        // only says "pick a non-empty key".
27429        let mut s = three_member_spec();
27430        s.placement.shard_key = Some(String::new());
27431        let err = s.validate().unwrap_err();
27432        assert!(
27433            matches!(
27434                err,
27435                AplicacaoError::ShardKeyOnNonSharded {
27436                    estrategia: PlacementStrategy::Replicated,
27437                    ref shard_key,
27438                } if shard_key.is_empty()
27439            ),
27440            "got {err:?}"
27441        );
27442    }
27443
27444    #[test]
27445    fn replicated_without_shard_key_validates() {
27446        // The complement of the rejection: `:placement :estrategia
27447        // Replicated` with `:shard-key None` is the canonical happy
27448        // path on every existing fixture. Pin the no-shard-key case so
27449        // the new gate doesn't accidentally fire on `None`.
27450        let mut s = three_member_spec();
27451        assert!(matches!(
27452            s.placement.estrategia,
27453            PlacementStrategy::Replicated
27454        ));
27455        s.placement.shard_key = None;
27456        s.validate().unwrap();
27457    }
27458
27459    #[test]
27460    fn singlenode_without_shard_key_validates() {
27461        // Peer of the Replicated no-shard-key case on the SingleNode
27462        // arm — both non-Sharded strategies must validate cleanly when
27463        // the slot is omitted.
27464        let mut s = three_member_spec();
27465        s.placement.estrategia = PlacementStrategy::SingleNode;
27466        s.placement.shard_key = None;
27467        s.validate().unwrap();
27468    }
27469
27470    #[test]
27471    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
27472        // Fail-before-pass-after pin on
27473        // [`AplicacaoError::shard_key_on_non_sharded`]'s
27474        // substrate-primitive posture: byte-identity + `Display`
27475        // byte-string parity against the open-coded struct-literal
27476        // for every non-`Sharded` [`PlacementStrategy`] arm across a
27477        // representative `:shard-key` value the sole in-crate wire-up
27478        // site (`AplicacaoSpec::validate_placement`'s
27479        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
27480        // arm) emits. Any wrapper-side silent normalization, `.into()`
27481        // divergence, or accidental field rebrand on the ctor body
27482        // surfaces at assert time rather than at a downstream consumer
27483        // that reads `err.estrategia` / `err.shard_key` back and gets a
27484        // different value than the one it stored.
27485        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
27486            let placement = Placement {
27487                estrategia,
27488                clusters: vec!["cluster-a".to_string()],
27489                shard_key: Some("$tenantId".to_string()),
27490                affinity: None,
27491            };
27492            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
27493            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
27494                estrategia,
27495                shard_key: "$tenantId".to_string(),
27496            };
27497            assert_eq!(
27498                via_ctor, via_literal,
27499                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
27500                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
27501            );
27502            assert_eq!(
27503                via_ctor.to_string(),
27504                via_literal.to_string(),
27505                "Display byte-string must byte-equal the open-coded struct-literal \
27506                 for {estrategia:?}"
27507            );
27508        }
27509    }
27510
27511    #[test]
27512    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
27513        // Boundary-sweep pin on the ctor's substrate-primitive
27514        // projection: the `estrategia` slot is stored verbatim from
27515        // [`Placement::estrategia`] on every arm the accessor can
27516        // return, and the `shard_key` slot preserves the caller-side
27517        // `&str` byte-for-byte. Sweeping every arm of
27518        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
27519        // current caller never reaches, since the ctor is a substrate
27520        // primitive independent of any single caller's dispatch gate)
27521        // catches a future silent field-rebrand or per-arm ctor
27522        // divergence at caixa-core build time rather than at a
27523        // downstream consumer far from the wire-up commit.
27524        for &estrategia in PlacementStrategy::ALL {
27525            let placement = Placement {
27526                estrategia,
27527                clusters: vec!["cluster-a".to_string()],
27528                shard_key: Some("$tenantId".to_string()),
27529                affinity: None,
27530            };
27531            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
27532            let AplicacaoError::ShardKeyOnNonSharded {
27533                estrategia: stored_estrategia,
27534                shard_key: stored_shard_key,
27535            } = err
27536            else {
27537                panic!(
27538                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
27539                );
27540            };
27541            assert_eq!(
27542                stored_estrategia, estrategia,
27543                "estrategia slot must round-trip verbatim through Placement::estrategia \
27544                 for {estrategia:?}"
27545            );
27546            assert_eq!(
27547                stored_shard_key, "$tenantId",
27548                "shard_key slot must preserve the caller-side &str byte-for-byte \
27549                 for {estrategia:?}"
27550            );
27551        }
27552    }
27553
27554    #[test]
27555    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
27556        // End-to-end pin: the sole in-crate wire-up site
27557        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
27558        // refusal) routes through
27559        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
27560        // `Err` byte-equals the ctor's output on the same non-`Sharded`
27561        // fixture. A future silent de-lift of the wire-up back to the
27562        // open-coded struct-literal trips this test at caixa-core build
27563        // time rather than at a downstream diagnostic consumer far from
27564        // the wire-up commit.
27565        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
27566            let mut s = three_member_spec();
27567            s.placement.estrategia = estrategia;
27568            s.placement.shard_key = Some("$tenantId".to_string());
27569            let observed = s.validate().unwrap_err();
27570            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
27571            assert_eq!(
27572                observed, expected,
27573                "validate_placement's non-Sharded-arm Err must byte-equal \
27574                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
27575            );
27576            assert_eq!(
27577                observed.to_string(),
27578                expected.to_string(),
27579                "Display byte-string parity for {estrategia:?}"
27580            );
27581        }
27582    }
27583
27584    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
27585        // Fixture builder for the `:placement :shard-key` shape gate
27586        // tests: a three-member Aplicacao on the `Sharded` strategy
27587        // with the supplied `:shard-key` slot. Co-locates the
27588        // arm-construction so every test below carries one line of
27589        // setup (the offending `:shard-key` value) and the assertion.
27590        let mut s = three_member_spec();
27591        s.placement.estrategia = PlacementStrategy::Sharded;
27592        s.placement.shard_key = Some(key.into());
27593        s
27594    }
27595
27596    #[test]
27597    fn rejects_shard_key_with_embedded_space() {
27598        // The canonical paste-from-aligned-doc footgun:
27599        // `:shard-key "$tenant Id"` — the Akka-style entity-id
27600        // extractor reads the slot as a single-token reference, and an
27601        // embedded space breaks the token boundary at the runtime
27602        // hash-extractor pass with no diagnostic naming the offending
27603        // entry.
27604        let s = sharded_spec_with_key("$tenant Id");
27605        let err = s.validate().unwrap_err();
27606        assert!(
27607            matches!(
27608                err,
27609                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
27610                    if shard_key == "$tenant Id" && reason.contains("space")
27611            ),
27612            "got {err:?}"
27613        );
27614    }
27615
27616    #[test]
27617    fn rejects_shard_key_with_leading_space() {
27618        // Leading-space arm of the embedded-whitespace footgun — the
27619        // paste-from-aligned-doc / paste-from-CSV-cell variant where
27620        // the leading column-padding leaked into the slot.
27621        let s = sharded_spec_with_key(" $tenantId");
27622        let err = s.validate().unwrap_err();
27623        assert!(
27624            matches!(
27625                err,
27626                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
27627                    if shard_key == " $tenantId"
27628            ),
27629            "got {err:?}"
27630        );
27631    }
27632
27633    #[test]
27634    fn rejects_shard_key_with_trailing_newline() {
27635        // The canonical paste-from-shell-heredoc footgun — every
27636        // `<<EOF` heredoc terminator paste leaves a trailing newline
27637        // the YAML emitter then folds away inconsistently across
27638        // emitter implementations.
27639        let s = sharded_spec_with_key("$tenantId\n");
27640        let err = s.validate().unwrap_err();
27641        assert!(
27642            matches!(
27643                err,
27644                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
27645                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
27646            ),
27647            "got {err:?}"
27648        );
27649    }
27650
27651    #[test]
27652    fn rejects_shard_key_with_embedded_tab() {
27653        // The paste-from-aligned-doc tab-stop variant — tabs land
27654        // alongside spaces in copy-paste from formatted columns.
27655        let s = sharded_spec_with_key("$tenant\tId");
27656        let err = s.validate().unwrap_err();
27657        assert!(
27658            matches!(
27659                err,
27660                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
27661                    if shard_key == "$tenant\tId" && reason.contains("tab")
27662            ),
27663            "got {err:?}"
27664        );
27665    }
27666
27667    #[test]
27668    fn rejects_shard_key_with_control_character() {
27669        // The paste-from-binary / paste-from-screen-cleared-terminal
27670        // footgun — an embedded `\x01` (SOH) byte that some YAML
27671        // emitters silently strip and others escape as ``,
27672        // breaking round-trip across emitter implementations.
27673        let s = sharded_spec_with_key("$tenant\u{0001}Id");
27674        let err = s.validate().unwrap_err();
27675        assert!(
27676            matches!(
27677                err,
27678                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
27679                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
27680            ),
27681            "got {err:?}"
27682        );
27683    }
27684
27685    #[test]
27686    fn rejects_shard_key_with_non_ascii() {
27687        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
27688        // footgun — non-ASCII bytes normalize differently between the
27689        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
27690        // YAML parser, the same entity ID can silently map to two
27691        // distinct shards on a re-render.
27692        let s = sharded_spec_with_key("$tenàntId");
27693        let err = s.validate().unwrap_err();
27694        assert!(
27695            matches!(
27696                err,
27697                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
27698                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
27699            ),
27700            "got {err:?}"
27701        );
27702    }
27703
27704    #[test]
27705    fn rejects_shard_key_too_long() {
27706        // Length cap pin: 64 bytes — one byte over the
27707        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
27708        // here is a paste-from-doc multi-line blob landing in
27709        // `:shard-key` instead of a single-token extractor expression.
27710        let too_long = "a".repeat(64);
27711        let s = sharded_spec_with_key(&too_long);
27712        let err = s.validate().unwrap_err();
27713        let AplicacaoError::ShardKeyInvalid {
27714            ref shard_key,
27715            ref reason,
27716        } = err
27717        else {
27718            panic!("expected ShardKeyInvalid, got {err:?}");
27719        };
27720        assert_eq!(shard_key, &too_long);
27721        assert!(
27722            reason.contains("63") && reason.contains("64"),
27723            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
27724        );
27725    }
27726
27727    #[test]
27728    fn shard_key_max_length_validates() {
27729        // Boundary pin: 63 bytes exactly — the
27730        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
27731        // dropping to 62) surfaces here as a regression, mirroring
27732        // `placement_cluster_max_length_validates` /
27733        // `placement_affinity_max_length_validates` on the peer
27734        // identifier-shaped slots.
27735        let s = sharded_spec_with_key(&"a".repeat(63));
27736        s.validate().unwrap();
27737    }
27738
27739    #[test]
27740    fn accepts_canonical_shard_key_forms() {
27741        // The Akka-style entity-id extractor shapes a caixa author is
27742        // realistically going to write — pin every leg so a future
27743        // tightening that bans (e.g.) the `${...}` interpolation
27744        // variant or the `metadata.<field>` JSONPath form surfaces
27745        // here as a regression. The canonical forms span:
27746        //
27747        //   - bare property name (`tenantId`, `customerId`)
27748        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
27749        //   - JSONPath-style nested reference (`metadata.tenantId`,
27750        //     `$.user.id`)
27751        //   - interpolation-style template (`${tenant}`)
27752        //   - snake_case property name (`customer_id`)
27753        //   - kebab-case property name (`customer-id` — accepted
27754        //     because the slot is a printable-ASCII single-token
27755        //     reference, not a DNS-1123 label like
27756        //     `:placement :affinity` / `:clusters`)
27757        //   - single character (`a`, `$` — boundary)
27758        for form in [
27759            "tenantId",
27760            "customerId",
27761            "$tenantId",
27762            "metadata.tenantId",
27763            "$.user.id",
27764            "${tenant}",
27765            "customer_id",
27766            "customer-id",
27767            "a",
27768            "$",
27769        ] {
27770            let s = sharded_spec_with_key(form);
27771            s.validate().unwrap_or_else(|e| {
27772                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
27773            });
27774        }
27775    }
27776
27777    #[test]
27778    fn shard_key_empty_takes_precedence_over_invalid() {
27779        // Order pin: the existing `ShardedKeyEmpty` diagnostic
27780        // (reserved for the `Sharded` `Some("")` arm) fires before the
27781        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
27782        // `:shard-key` keeps its narrower error message — the new gate
27783        // would also reject `""` defensively, but the empty-string arm
27784        // is the more self-locating diagnostic. Mirrors the
27785        // `placement_cluster_empty_takes_precedence_over_invalid` pin
27786        // on the peer identifier-shaped slot.
27787        let s = sharded_spec_with_key("");
27788        let err = s.validate().unwrap_err();
27789        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
27790    }
27791
27792    #[test]
27793    fn shard_key_invalid_diagnostic_carries_offending_value() {
27794        // The diagnostic-shape pin: the error names the offending
27795        // `:shard-key` value verbatim so the author can grep their
27796        // caixa.lisp without re-running the build, and carries a
27797        // parser-shaped `reason:` naming the specific violation —
27798        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
27799        // on the peer identifier-shaped slot.
27800        let s = sharded_spec_with_key("$tenant Id");
27801        let err = s.validate().unwrap_err();
27802        let AplicacaoError::ShardKeyInvalid {
27803            ref shard_key,
27804            ref reason,
27805        } = err
27806        else {
27807            panic!("expected ShardKeyInvalid, got {err:?}");
27808        };
27809        assert_eq!(shard_key, "$tenant Id");
27810        assert!(
27811            !reason.is_empty(),
27812            "reason must name the specific violation, got empty string"
27813        );
27814    }
27815
27816    #[test]
27817    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
27818        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
27819        // `:shard-key` carried on non-Sharded strategies) fires before
27820        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
27821        // a `Replicated` strategy surfaces the more self-locating
27822        // strategy-mismatch diagnostic (naming the actual fix — drop
27823        // the slot, or switch to Sharded) rather than the shape
27824        // diagnostic. The strategy-mismatch arm is the more actionable
27825        // diagnostic: a malformed shard-key on Replicated is "you
27826        // shouldn't have a :shard-key here at all", not "your
27827        // :shard-key value is malformed".
27828        let mut s = three_member_spec();
27829        // Replicated is the default fixture strategy.
27830        s.placement.shard_key = Some("$tenant Id".into());
27831        let err = s.validate().unwrap_err();
27832        assert!(
27833            matches!(
27834                err,
27835                AplicacaoError::ShardKeyOnNonSharded {
27836                    estrategia: PlacementStrategy::Replicated,
27837                    ..
27838                }
27839            ),
27840            "got {err:?}"
27841        );
27842    }
27843
27844    #[test]
27845    fn rejects_empty_affinity_hint() {
27846        let mut s = three_member_spec();
27847        s.placement.affinity = Some(String::new());
27848        assert_eq!(
27849            s.validate().unwrap_err(),
27850            AplicacaoError::PlacementAffinityEmpty
27851        );
27852    }
27853
27854    #[test]
27855    fn placement_without_affinity_validates() {
27856        // Omitting :affinity is fine — the placement engine falls back
27857        // to the default heuristic. Pin the no-hint case so the
27858        // affinity-empty rejection doesn't accidentally fire on `None`.
27859        let mut s = three_member_spec();
27860        s.placement.affinity = None;
27861        s.validate().unwrap();
27862    }
27863
27864    #[test]
27865    fn rejects_placement_affinity_with_uppercase() {
27866        // The canonical "I copied the ADR's display name verbatim" typo
27867        // — placement hints land verbatim in K8s label-selector
27868        // territory, where the apiserver enforces the DNS-1123 label
27869        // rule (lowercase-only) on every identity-keyed admission axis.
27870        // Mirrors `rejects_placement_cluster_with_uppercase` on the
27871        // sibling slot.
27872        let mut s = three_member_spec();
27873        s.placement.affinity = Some("DataLocality".into());
27874        let err = s.validate().unwrap_err();
27875        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
27876            panic!("expected PlacementAffinityInvalid, got other variant");
27877        };
27878        assert_eq!(affinity, "DataLocality");
27879        assert!(
27880            reason.contains("uppercase"),
27881            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
27882        );
27883        assert!(
27884            reason.contains("\"datalocality\""),
27885            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
27886        );
27887    }
27888
27889    #[test]
27890    fn rejects_placement_affinity_with_underscore() {
27891        // The canonical "I'm thinking of an env var / Python identifier"
27892        // leak — `_` is forbidden by every DNS-1123 label schema. Same
27893        // shape as `rejects_placement_cluster_with_underscore` on the
27894        // sibling slot.
27895        let mut s = three_member_spec();
27896        s.placement.affinity = Some("data_locality".into());
27897        let err = s.validate().unwrap_err();
27898        assert!(
27899            matches!(
27900                err,
27901                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
27902                    if affinity == "data_locality" && reason.contains('_')
27903            ),
27904            "got {err:?}"
27905        );
27906    }
27907
27908    #[test]
27909    fn rejects_placement_affinity_with_dot() {
27910        // A `:placement :affinity` value is a single DNS-1123 *label*
27911        // (it lands as a K8s label value selector key), not a subdomain.
27912        // The "I want to namespace my hint with `.`" intent is expressed
27913        // via `-` (`data-locality-east`).
27914        let mut s = three_member_spec();
27915        s.placement.affinity = Some("data.locality".into());
27916        let err = s.validate().unwrap_err();
27917        assert!(
27918            matches!(
27919                err,
27920                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
27921                    if affinity == "data.locality" && reason.contains('.')
27922            ),
27923            "got {err:?}"
27924        );
27925    }
27926
27927    #[test]
27928    fn rejects_placement_affinity_with_unicode() {
27929        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
27930        // before it reaches K8s. The byte-by-byte ASCII validity check
27931        // rejects multi-byte UTF-8 sequences by the first byte that
27932        // fails `[a-z0-9-]`.
27933        let mut s = three_member_spec();
27934        s.placement.affinity = Some("data-localité".into());
27935        let err = s.validate().unwrap_err();
27936        assert!(
27937            matches!(
27938                err,
27939                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
27940                    if affinity == "data-localité"
27941            ),
27942            "got {err:?}"
27943        );
27944    }
27945
27946    #[test]
27947    fn rejects_placement_affinity_with_leading_hyphen() {
27948        // DNS-1123 boundary rule: labels must start with an
27949        // alphanumeric. Pin separately from the trailing-hyphen arm so
27950        // a future relaxation that only checks one boundary surfaces
27951        // here as a regression (parallel to
27952        // `rejects_placement_cluster_with_leading_hyphen`).
27953        let mut s = three_member_spec();
27954        s.placement.affinity = Some("-data-locality".into());
27955        let err = s.validate().unwrap_err();
27956        assert!(
27957            matches!(
27958                err,
27959                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
27960                    if affinity == "-data-locality" && reason.contains("start and end")
27961            ),
27962            "got {err:?}"
27963        );
27964    }
27965
27966    #[test]
27967    fn rejects_placement_affinity_with_trailing_hyphen() {
27968        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
27969        // ends are covered against a future relaxation.
27970        let mut s = three_member_spec();
27971        s.placement.affinity = Some("data-locality-".into());
27972        let err = s.validate().unwrap_err();
27973        assert!(
27974            matches!(
27975                err,
27976                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
27977                    if affinity == "data-locality-"
27978            ),
27979            "got {err:?}"
27980        );
27981    }
27982
27983    #[test]
27984    fn rejects_placement_affinity_with_whitespace() {
27985        // Whitespace is the canonical "I pasted from a sketch / doc"
27986        // footgun. The apiserver rejects every label-selector value
27987        // carrying whitespace.
27988        let mut s = three_member_spec();
27989        s.placement.affinity = Some("data locality".into());
27990        let err = s.validate().unwrap_err();
27991        assert!(
27992            matches!(
27993                err,
27994                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
27995                    if affinity == "data locality"
27996            ),
27997            "got {err:?}"
27998        );
27999    }
28000
28001    #[test]
28002    fn rejects_placement_affinity_too_long() {
28003        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
28004        // pin. The diagnostic names both the cap (63) and the actual
28005        // length so the author can shorten in one edit. Mirrors
28006        // `rejects_placement_cluster_too_long`.
28007        let mut s = three_member_spec();
28008        let too_long = "a".repeat(64);
28009        s.placement.affinity = Some(too_long.clone());
28010        let err = s.validate().unwrap_err();
28011        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
28012            panic!("expected PlacementAffinityInvalid");
28013        };
28014        assert_eq!(affinity, too_long);
28015        assert!(
28016            reason.contains("63") && reason.contains("64"),
28017            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
28018        );
28019    }
28020
28021    #[test]
28022    fn placement_affinity_max_length_validates() {
28023        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
28024        // future tightening (e.g. dropping to 62) surfaces here as a
28025        // regression, mirroring `placement_cluster_max_length_validates`.
28026        let mut s = three_member_spec();
28027        s.placement.affinity = Some("a".repeat(63));
28028        s.validate().unwrap();
28029    }
28030
28031    #[test]
28032    fn accepts_canonical_placement_affinity_forms() {
28033        // The DNS-1123 label shapes a caixa author is realistically
28034        // going to write for placement hints: the M3 canonical examples
28035        // (`data-locality`, `low-latency`, `anti-affinity`), the
28036        // single-token form (`affinity`), the single-character boundary
28037        // (`a`), the digit-start (DNS-1123 allows this, unlike
28038        // DNS-1035), and a regional-suffixed form. Pin every leg so a
28039        // future tightening that bans (e.g.) digit-start identifiers
28040        // surfaces here.
28041        for form in [
28042            "data-locality",
28043            "low-latency",
28044            "anti-affinity",
28045            "affinity",
28046            "a",
28047            "3-tier",
28048            "locality-east",
28049        ] {
28050            let mut s = three_member_spec();
28051            s.placement.affinity = Some(form.into());
28052            s.validate().unwrap_or_else(|e| {
28053                panic!("canonical affinity form {form:?} must validate, got {e:?}")
28054            });
28055        }
28056    }
28057
28058    #[test]
28059    fn placement_affinity_empty_takes_precedence_over_invalid() {
28060        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
28061        // (which doesn't try to parse) fires before the new
28062        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
28063        // `:affinity` keeps its narrower error message — the new gate
28064        // would also reject `""`, but the empty-string arm is the more
28065        // self-locating diagnostic. Mirrors the
28066        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
28067        let mut s = three_member_spec();
28068        s.placement.affinity = Some(String::new());
28069        let err = s.validate().unwrap_err();
28070        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
28071    }
28072
28073    #[test]
28074    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
28075        // The diagnostic shape pin: every rejection carries the offending
28076        // `affinity:` verbatim plus a parser-shaped `reason:` so the
28077        // author can grep their caixa.lisp for `:affinity "<hint>"` and
28078        // fix it in one edit. Mirrors the
28079        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
28080        // pin on the sibling slot.
28081        let mut s = three_member_spec();
28082        s.placement.affinity = Some("Data_Locality".into());
28083        let err = s.validate().unwrap_err();
28084        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
28085            panic!("expected PlacementAffinityInvalid");
28086        };
28087        assert_eq!(affinity, "Data_Locality");
28088        assert!(
28089            !reason.is_empty(),
28090            "diagnostic reason must not be empty (got: {reason:?})"
28091        );
28092    }
28093
28094    #[test]
28095    fn singlenode_with_takeover_candidates_validates() {
28096        // OTP distributed-application convention (MESH-COMPOSITION
28097        // §II.1): SingleNode runs on one cluster at a time but the
28098        // :clusters list enumerates the takeover candidates. Multiple
28099        // entries are not a contradiction — they are the failover pool.
28100        let mut s = three_member_spec();
28101        s.placement.estrategia = PlacementStrategy::SingleNode;
28102        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
28103        s.validate().unwrap();
28104    }
28105
28106    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
28107
28108    #[test]
28109    fn mesh_policy_default_is_empty() {
28110        // The Default impl carries None on every axis — the typed
28111        // analog of an unset `:politicas (())` slot. Renderers that
28112        // overlay the policy onto a cluster artifact key off this
28113        // predicate to skip the slot entirely; pinning so a future
28114        // axis added to MeshPolicy can't silently break the contract
28115        // (a new field whose Default is non-None would flip is_empty
28116        // to false on every existing caixa, surfacing here).
28117        assert!(MeshPolicy::default().is_empty());
28118    }
28119
28120    #[test]
28121    fn mesh_policy_with_only_timeout_is_not_empty() {
28122        let p = MeshPolicy {
28123            timeout: Some(Duration::from_secs(30)),
28124            ..Default::default()
28125        };
28126        assert!(!p.is_empty());
28127    }
28128
28129    #[test]
28130    fn mesh_policy_with_only_retries_is_not_empty() {
28131        let p = MeshPolicy {
28132            retries: Some(3),
28133            ..Default::default()
28134        };
28135        assert!(!p.is_empty());
28136    }
28137
28138    #[test]
28139    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
28140        let p = MeshPolicy {
28141            circuit_breaker: Some(CircuitBreaker {
28142                max_failures: 5,
28143                window: Duration::from_secs(60),
28144            }),
28145            ..Default::default()
28146        };
28147        assert!(!p.is_empty());
28148    }
28149
28150    #[test]
28151    fn mesh_policy_with_only_mtls_required_is_not_empty() {
28152        // Even `mtls_required: Some(false)` (an explicit opt-out) is
28153        // not empty — the author *named* the axis, the renderer needs
28154        // to honor that vs. fall back to the cluster default.
28155        let p = MeshPolicy {
28156            mtls_required: Some(false),
28157            ..Default::default()
28158        };
28159        assert!(!p.is_empty());
28160    }
28161
28162    #[test]
28163    fn mesh_policy_with_only_rate_limit_is_not_empty() {
28164        let p = MeshPolicy {
28165            rate_limit: Some(RateLimit {
28166                rate: 100,
28167                window: Duration::from_secs(1),
28168            }),
28169            ..Default::default()
28170        };
28171        assert!(!p.is_empty());
28172    }
28173
28174    #[test]
28175    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
28176        // The three-member happy-path fixture sets timeout + retries +
28177        // mtls_required — every populated axis must read non-empty.
28178        // Pin the round-trip so the M3.x per-:politicas emitter (the
28179        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
28180        // on is_empty() to decide whether to emit at all without
28181        // re-deriving the contract from inline field probes.
28182        assert!(!three_member_spec().politicas.is_empty());
28183    }
28184
28185    #[test]
28186    fn mesh_policy_empty_is_the_all_none_arm_and_is_empty() {
28187        // Fail-before-pass-after round-trip pin on the paired
28188        // ([`MeshPolicy::empty`], [`MeshPolicy::is_empty`]) constructor /
28189        // predicate on the [`MeshPolicy`] typed slot: the lifted
28190        // constructor must materialize a value whose every one of the
28191        // five `Option<_>`-carrying per-axis fields is `None`, so the
28192        // paired [`MeshPolicy::is_empty`] predicate returns `true` on
28193        // the constructor's output by construction. A future silent
28194        // regression that omits a `None` arm from the constructor's
28195        // struct-literal (a sixth axis added to the type whose
28196        // constructor arm is forgotten, an accidental `Some(0)` on the
28197        // `retries` arm that would silently violate the
28198        // [`AplicacaoError::PolicyRetriesZero`] admission floor) trips
28199        // here at caixa-core test time rather than surfacing as a
28200        // downstream consumer's per-`:politicas` overlay-emit path
28201        // reading a `MeshPolicy::empty()` output that fails the
28202        // emptiness predicate and lands an unexpected `spec.policies.
28203        // <axis>` field in the emitted Cilium/Envoy overlay. Peer of
28204        // the sibling
28205        // [`crate::limits::tests::limits_spec_empty_is_the_all_none_arm_and_is_empty`]
28206        // pin on the M2 `:limits` typed slot — extends the same
28207        // "the canonical unset baseline satisfies the paired
28208        // emptiness predicate" round-trip discipline onto the M3
28209        // `:politicas` slot.
28210        let empty = MeshPolicy::empty();
28211        assert!(
28212            empty.is_empty(),
28213            "MeshPolicy::empty() must return a value whose is_empty() \
28214             predicate is true — got {empty:?}",
28215        );
28216        assert_eq!(empty.timeout(), None);
28217        assert_eq!(empty.retries(), None);
28218        assert_eq!(empty.circuit_breaker(), None);
28219        assert_eq!(empty.mtls_required(), None);
28220        assert_eq!(empty.rate_limit(), None);
28221    }
28222
28223    #[test]
28224    fn mesh_policy_empty_byte_equals_default() {
28225        // Fail-before-pass-after byte-parity pin on the two-path
28226        // convergence: the lifted `pub const fn` [`MeshPolicy::empty`]
28227        // constructor must byte-equal the derived (non-`const`)
28228        // [`Default::default`] on every one of the five
28229        // `Option<_>`-carrying per-axis fields under `PartialEq`. The
28230        // two paths are semantically identical (both name the
28231        // "canonical unset [`MeshPolicy`]" shape) but structurally
28232        // distinct (the derived [`Default::default`] threads through
28233        // the derive-generated per-field `<Option<_> as Default>::default`
28234        // cascade, resolving to `None` on each; the lifted
28235        // constructor's struct-literal names each `None` arm
28236        // verbatim). A future regression on either path — an
28237        // accidental `Some(0)` on the constructor's `retries` arm
28238        // that would silently drift the constructor's output from the
28239        // derived default (surfacing here as the pin's first-arm
28240        // inequality), a future substrate-wide field-default rebrand
28241        // that lands on the derived path's per-field
28242        // `<Option<_> as Default>::default` but forgets to extend the
28243        // constructor's struct-literal (surfacing here as the pin's
28244        // per-arm inequality on the newly rebranded axis) — trips
28245        // here at caixa-core test time. The `const` binding on the
28246        // LHS forces the lifted constructor through the `const`-eval
28247        // surface at compile time, so any future accidental downgrade
28248        // to `pub fn` fires E0015 at the binding rather than at a
28249        // downstream `const`-context consumer's dispatch site. Peer
28250        // of the sibling
28251        // [`crate::limits::tests::limits_spec_empty_byte_equals_default`]
28252        // pin on the M2 `:limits` typed slot.
28253        const EMPTY: MeshPolicy = MeshPolicy::empty();
28254        assert_eq!(
28255            EMPTY,
28256            MeshPolicy::default(),
28257            "MeshPolicy::empty() must byte-equal MeshPolicy::default() on \
28258             every per-axis field — the two paths name the same canonical \
28259             unset baseline; a mismatch means one path drifted from the \
28260             other on some per-axis default",
28261        );
28262    }
28263
28264    #[test]
28265    fn mesh_policy_empty_ctor_is_const_fn() {
28266        // Const-eval-surface pin on the lifted [`MeshPolicy::empty`]
28267        // constructor: the constructor must remain `pub const fn` so
28268        // downstream consumers can materialize a canonical unset
28269        // baseline in `const` context (a `const EMPTY: MeshPolicy =
28270        // MeshPolicy::empty();` module-scope binding for a
28271        // fixture-builder table, a `const`-context per-arm predicate
28272        // that folds emptiness over the constructor's output at
28273        // compile time, a compile-time lookup table the LSP hover
28274        // renderer materializes per typed-slot fixture). A future
28275        // accidental downgrade to non-`const` (an added runtime
28276        // helper reachable only from a non-`const` context in the
28277        // body, a manual hand-rolled `impl` that shadows this method)
28278        // trips at caixa-core build time — E0015 at the `const EMPTY`
28279        // binding below — rather than surfacing as a downstream
28280        // `const`-context regression far from the constructor's
28281        // declaration. The paired [`Self::is_empty`] predicate call
28282        // inside the `const { assert!(..) }` block enforces both
28283        // halves of the round-trip (constructor is `const`-callable
28284        // AND its output satisfies the paired emptiness predicate at
28285        // `const`-eval time) at caixa-core compile time. Peer of the
28286        // sibling
28287        // [`crate::limits::tests::limits_spec_empty_ctor_is_const_fn`]
28288        // pin on the M2 `:limits` typed slot.
28289        const EMPTY: MeshPolicy = MeshPolicy::empty();
28290        const {
28291            assert!(EMPTY.is_empty());
28292        }
28293    }
28294
28295    #[test]
28296    fn mesh_policy_default_routes_through_empty_ctor() {
28297        // Fail-before-pass-after byte-parity pin on the two-path
28298        // convergence discipline lifted onto the [`Default`] impl:
28299        // pre-fold the derive-generated [`Default::default`] and the
28300        // `pub const fn` [`MeshPolicy::empty`] constructor were
28301        // byte-equal by *coincidence* (each hand-authored or derive-
28302        // authored `None` per axis, pinned load-bearing by the
28303        // pre-existing [`mesh_policy_empty_byte_equals_default`]
28304        // sibling pin), while the folded impl now routes
28305        // [`Default::default`] through the substrate-canonical
28306        // [`Self::empty`] constructor — the two paths are byte-equal
28307        // by *construction*, one delegates to the other. This pin
28308        // sharpens the pre-existing byte-parity invariant into a
28309        // structural-delegation invariant: any future silent regression
28310        // that re-derives [`Default`] on the type (a `#[derive(Default)]`
28311        // re-addition that shadows the manual impl, a swap of the
28312        // manual impl's body onto a divergent struct-literal that
28313        // diverges from [`Self::empty`]'s output on a new field's
28314        // non-`None` canonical baseline) trips here at caixa-core test
28315        // time under `PartialEq` rather than at a downstream consumer
28316        // of the derived-until-now [`Default::default`] surface (the
28317        // five per-axis-only `..Default::default()` fixtures at
28318        // [`mesh_policy_with_only_timeout_is_not_empty`] /
28319        // [`mesh_policy_with_only_retries_is_not_empty`] /
28320        // [`mesh_policy_with_only_circuit_breaker_is_not_empty`] /
28321        // [`mesh_policy_with_only_mtls_required_is_not_empty`] /
28322        // [`mesh_policy_with_only_rate_limit_is_not_empty`], the
28323        // `MeshPolicy::default().is_empty()` round-trip at
28324        // [`mesh_policy_default_is_empty`], every future consumer of
28325        // a hypothetical `..MeshPolicy::default()` overlay-elision
28326        // arm). Peer of the sibling
28327        // [`crate::limits::tests::limits_spec_default_routes_through_empty_ctor`]
28328        // pin on the M2 `:limits` typed slot (abd52c2).
28329        assert_eq!(
28330            MeshPolicy::default(),
28331            MeshPolicy::empty(),
28332            "MeshPolicy::default() must delegate through MeshPolicy::empty() \
28333             on every per-axis field — a mismatch means the manual Default \
28334             impl drifted off the substrate-canonical empty() constructor \
28335             (or the constructor drifted off the impl's expected shape)",
28336        );
28337    }
28338
28339    #[test]
28340    fn mesh_policy_empty_validates_ok() {
28341        // Fail-before-pass-after invariant pin on the empty-baseline
28342        // validate composition: the canonical unset [`MeshPolicy`]
28343        // (every one of the five `Option<_>`-carrying per-axis fields
28344        // set to `None`) must pass every gate on
28345        // [`MeshPolicy::validate`]. The invariant is structurally
28346        // guaranteed today — every per-axis value-shape gate on the
28347        // validate dispatch is `if let Some(_) = self.<axis>()` guarded
28348        // and every cross-axis arm on
28349        // [`MeshPolicy::first_cross_axis_violation`] is a
28350        // `let (Some(_), Some(_))` pattern, so an all-`None` input
28351        // short-circuits every arm before any zero-floor / canonical-
28352        // form / cap / pairwise-ordering check fires. Pinning the
28353        // composition here makes the invariant load-bearing so a
28354        // future extension of the validate surface that adds a
28355        // non-`Option`-guarded gate (a hypothetical cross-slot
28356        // coherence gate a future per-axis / per-slot fold on the M3
28357        // `:politicas` slot establishes on top of the current
28358        // pairwise-cross-axis composition per
28359        // `theory/MESH-COMPOSITION.md` §III.2, a per-arm
28360        // `mtls_required`-defaults-to-`true` admission overlay a
28361        // future admission webhook lands) that fires on the all-`None`
28362        // input trips here at caixa-core test time rather than at a
28363        // downstream consumer that composed [`MeshPolicy::default`]
28364        // (which now routes through [`MeshPolicy::empty`]) with
28365        // [`MeshPolicy::validate`] as its "no-op axis short-circuit"
28366        // and observed a spurious rejection on the canonical unset
28367        // baseline. Peer of the sibling
28368        // [`crate::limits::tests::limits_spec_empty_validates_ok`] pin
28369        // on the M2 `:limits` typed slot (abd52c2) — that one anchors
28370        // the invariant on the folded [`Default`] impl the
28371        // [`crate::LimitsSpec::empty`] constructor now backs; this one
28372        // extends it onto the M3 `:politicas` slot's folded impl.
28373        MeshPolicy::empty().validate().expect(
28374            "MeshPolicy::empty() must satisfy MeshPolicy::validate — \
28375             every per-axis value-shape gate is `if let Some(_)` guarded \
28376             and every cross-axis arm is a `let (Some(_), Some(_))` pattern, \
28377             so an all-`None` input short-circuits every arm; a spurious \
28378             rejection on the canonical unset baseline means a future \
28379             validate-side extension added a non-`Option`-guarded gate that \
28380             fires on empty input",
28381        );
28382    }
28383
28384    // ── shared duration codec: cross-slot integer-magnitude gate ──
28385    //
28386    // The integer-magnitude discipline applied to
28387    // `supervisor::duration_codec::parse` lifts onto every typed slot
28388    // that routes through the shared codec — `MeshPolicy::timeout`
28389    // (`:politicas :timeout`) and `CircuitBreaker::window`
28390    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
28391    // These cross-slot tests pin that the gate fires at the serde
28392    // layer for both typed slots, not just for the supervisor side.
28393
28394    #[test]
28395    fn policy_timeout_serde_rejects_fractional_seconds() {
28396        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
28397        // so the shared codec's integer-magnitude gate applies on
28398        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
28399        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
28400        // deserialize with the canonical-form diagnostic naming the
28401        // offending `"1.5"` and the remediation `"1500ms"`.
28402        let payload = r#"{"timeout":"1.5s"}"#;
28403        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28404        let msg = err.to_string();
28405        assert!(
28406            msg.contains("not a non-negative integer"),
28407            "expected integer-magnitude diagnostic in {msg:?}"
28408        );
28409        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
28410        assert!(
28411            msg.contains("\"1500ms\""),
28412            "missing canonical-form remediation in {msg:?}"
28413        );
28414    }
28415
28416    #[test]
28417    fn policy_timeout_serde_rejects_leading_plus_sign() {
28418        // Pin the leading-`+` arm cross-slot — the prior f64 parser
28419        // accepted `"+30s"` silently and round-tripped to `"30s"`.
28420        let payload = r#"{"timeout":"+30s"}"#;
28421        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28422        let msg = err.to_string();
28423        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
28424    }
28425
28426    #[test]
28427    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
28428        // `CircuitBreaker::window` uses `with =
28429        // "supervisor::duration_codec_required"` (the required-Duration
28430        // variant that delegates to the same shared parser). `"0.5m"`
28431        // parsed to 30s and round-tripped to `"30s"` on next emit —
28432        // DRIFT closed.
28433        let payload = format!(
28434            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
28435            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
28436            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
28437        );
28438        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
28439        let msg = err.to_string();
28440        assert!(
28441            msg.contains("not a non-negative integer"),
28442            "expected integer-magnitude diagnostic in {msg:?}"
28443        );
28444        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
28445        assert!(
28446            msg.contains("\"30s\""),
28447            "missing canonical-form remediation in {msg:?}"
28448        );
28449    }
28450
28451    #[test]
28452    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
28453        // Pin the happy-path on the cross-slot side: every canonical
28454        // author shape `render` ever emits parses cleanly through the
28455        // shared codec on the `CircuitBreaker` slot. The
28456        // codec's accepted set (post-gate) is exactly its emitted set
28457        // for the integer-magnitude class.
28458        for window_lit in ["30s", "500ms", "2m", "1h"] {
28459            let payload = format!(
28460                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
28461                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
28462                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
28463            );
28464            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
28465                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
28466            });
28467            assert_eq!(cb.max_failures, 5);
28468        }
28469    }
28470
28471    // ── rate_limit_codec: integer-magnitude gate ──
28472    //
28473    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
28474    // / 737a676 / d53c922 trajectory landed on every typed-duration /
28475    // typed-byte-size codec in caixa-core lifts onto the fifth typed
28476    // codec — `rate_limit_codec` — through the digit-only magnitude
28477    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
28478    // These tests pin the gate at the serde layer for `:politicas
28479    // :rate-limit` (the only typed slot the codec backs), and at the
28480    // codec-internal `parse` layer for the canonical positive cases.
28481
28482    #[test]
28483    fn rate_limit_serde_rejects_fractional_rate() {
28484        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
28485        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
28486        // wording, which didn't name the canonical-form remediation or
28487        // the round-trip drift the next emit would produce. Now refused
28488        // at deserialize with the canonical-form diagnostic naming the
28489        // offending `"1.5"` magnitude and the round-trip drift wording.
28490        let payload = r#"{"rateLimit":"1.5/s"}"#;
28491        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28492        let msg = err.to_string();
28493        assert!(
28494            msg.contains("not a non-negative integer"),
28495            "expected integer-magnitude diagnostic in {msg:?}"
28496        );
28497        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
28498        assert!(
28499            msg.contains("THEORY.md"),
28500            "missing render-determinism contract citation in {msg:?}"
28501        );
28502    }
28503
28504    #[test]
28505    fn rate_limit_serde_rejects_leading_plus_sign() {
28506        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
28507        // permissive-`+` parse), so `"+100/s"` silently parsed to
28508        // `RateLimit { 100, 1s }` and round-tripped through `render` to
28509        // `"100/s"` — a *different* canonical string on the next emit,
28510        // breaking the THEORY.md Part V render-determinism contract
28511        // exactly the way the peer duration codecs' `"+30s"` case did.
28512        // This is the load-bearing class the digit-only gate closes
28513        // beyond what `u32::from_str`'s strictness covers on its own.
28514        let payload = r#"{"rateLimit":"+100/s"}"#;
28515        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28516        let msg = err.to_string();
28517        assert!(
28518            msg.contains("not a non-negative integer"),
28519            "expected integer-magnitude diagnostic in {msg:?}"
28520        );
28521        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
28522    }
28523
28524    #[test]
28525    fn rate_limit_serde_rejects_leading_minus_sign() {
28526        // The signed-negative arm: `"-1/s"` lands on the
28527        // non-canonical-but-numeric branch via the `i64` fallback (the
28528        // `f64` parse also succeeds), surfacing the canonical-form
28529        // diagnostic. Replaces the prior value-laundered "not a u32"
28530        // wording with the unified diagnostic across signs.
28531        let payload = r#"{"rateLimit":"-1/s"}"#;
28532        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28533        let msg = err.to_string();
28534        assert!(
28535            msg.contains("not a non-negative integer"),
28536            "expected integer-magnitude diagnostic in {msg:?}"
28537        );
28538        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
28539    }
28540
28541    #[test]
28542    fn rate_limit_serde_rejects_decimal_shaped_integer() {
28543        // `"100.0/s"` is integer-valued numerically but not in the
28544        // codec's accepted set — `render` emits `"100/s"`, so the
28545        // round-trip would drift. Lifted to the canonical-form
28546        // diagnostic peer with the duration codec's `"1.0s"` case
28547        // (1c55a2a).
28548        let payload = r#"{"rateLimit":"100.0/s"}"#;
28549        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28550        let msg = err.to_string();
28551        assert!(
28552            msg.contains("not a non-negative integer"),
28553            "expected integer-magnitude diagnostic in {msg:?}"
28554        );
28555        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
28556    }
28557
28558    #[test]
28559    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
28560        // Non-numeric, non-digit-only input lands on the existing
28561        // narrower `"not a u32"` arm (preserved for diagnostic-shape
28562        // stability on the parser-shape footgun case). Pin this so a
28563        // future relaxation of the numeric-fallback predicate doesn't
28564        // silently collapse garbage onto the canonical-form arm — same
28565        // partition the peer duration codecs draw between
28566        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
28567        let payload = r#"{"rateLimit":"abc/s"}"#;
28568        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28569        let msg = err.to_string();
28570        assert!(
28571            msg.contains("not a u32"),
28572            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
28573        );
28574        assert!(
28575            !msg.contains("not a non-negative integer"),
28576            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
28577        );
28578    }
28579
28580    #[test]
28581    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
28582        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
28583        // u32's range. The digit-only gate passes; `u32::from_str`
28584        // fails on overflow. Surface that with the overflow-shaped
28585        // diagnostic naming the offending magnitude verbatim, peer
28586        // with `supervisor::duration_codec`'s overflow arm. Pinning
28587        // the wording so a future refactor doesn't silently collapse
28588        // overflow onto the canonical-form arm.
28589        let payload = r#"{"rateLimit":"4294967296/s"}"#;
28590        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28591        let msg = err.to_string();
28592        assert!(
28593            msg.contains("overflows u32"),
28594            "expected overflow diagnostic in {msg:?}"
28595        );
28596        assert!(
28597            msg.contains("\"4294967296\""),
28598            "missing offending magnitude in {msg:?}"
28599        );
28600    }
28601
28602    #[test]
28603    fn rate_limit_serde_rejects_leading_zero_magnitude() {
28604        // `"0100/s"` is digit-only, so the existing
28605        // non-digit-only / sign / fractional arm doesn't catch it —
28606        // `u32::from_str("0100")` returns `Ok(100)`, so before this
28607        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
28608        // round-tripped through `render` to `"100/s"` — a *different*
28609        // canonical string on the next emit, breaking the THEORY.md
28610        // Part V render-determinism contract exactly the way the
28611        // peer `"+100/s"` case did before the leading-`+` arm landed.
28612        // This is the load-bearing class the leading-zero gate closes
28613        // beyond what the existing digit-only / sign / fractional
28614        // gates cover, and the peer arm to the leading-`+` test
28615        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
28616        // canonical-form-drift axis.
28617        let payload = r#"{"rateLimit":"0100/s"}"#;
28618        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28619        let msg = err.to_string();
28620        assert!(
28621            msg.contains("non-canonical leading zero"),
28622            "expected leading-zero diagnostic in {msg:?}"
28623        );
28624        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
28625        assert!(
28626            msg.contains("THEORY.md"),
28627            "missing render-determinism contract citation in {msg:?}"
28628        );
28629    }
28630
28631    #[test]
28632    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
28633        // `"00/s"` is the degenerate leading-zero case — every byte
28634        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
28635        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
28636        // a *different* canonical string, same render-determinism
28637        // violation. The single-byte `"0/s"` itself is in the
28638        // accepted set (round-trips losslessly through `render`,
28639        // refused downstream by `PolicyRateLimitZero`); the
28640        // multi-byte `"00/s"` is not. Pins the boundary between the
28641        // accepted single-`0` and the rejected leading-zero class.
28642        let payload = r#"{"rateLimit":"00/s"}"#;
28643        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28644        let msg = err.to_string();
28645        assert!(
28646            msg.contains("non-canonical leading zero"),
28647            "expected leading-zero diagnostic in {msg:?}"
28648        );
28649        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
28650    }
28651
28652    #[test]
28653    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
28654        // Cross-window pin — the gate is window-agnostic; the
28655        // leading-zero class is a property of the magnitude, not the
28656        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
28657        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
28658        // single-window coverage extended across the three canonical
28659        // windows the codec accepts.
28660        let payload = r#"{"rateLimit":"007/h"}"#;
28661        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28662        let msg = err.to_string();
28663        assert!(
28664            msg.contains("non-canonical leading zero"),
28665            "expected leading-zero diagnostic in {msg:?}"
28666        );
28667        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
28668    }
28669
28670    #[test]
28671    fn rate_limit_serde_rejects_leading_whitespace() {
28672        // `" 100/s"` — the canonical paste-from-aligned-doc /
28673        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
28674        // the top-level `s.trim()` silently ate the leading space and
28675        // parsed the value to `RateLimit { 100, 1s }`, which then
28676        // round-tripped through `render` to `"100/s"` (a *different*
28677        // canonical string on the next emit) — the exact
28678        // canonical-form-drift class the leading-`+` / leading-zero
28679        // arms already close, extended to the whitespace byte class.
28680        let payload = r#"{"rateLimit":" 100/s"}"#;
28681        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28682        let msg = err.to_string();
28683        assert!(
28684            msg.contains("contains whitespace byte"),
28685            "expected whitespace diagnostic in {msg:?}"
28686        );
28687        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
28688        assert!(
28689            msg.contains("THEORY.md"),
28690            "missing render-determinism contract citation in {msg:?}"
28691        );
28692    }
28693
28694    #[test]
28695    fn rate_limit_serde_rejects_trailing_whitespace() {
28696        // `"100/s "` — the canonical shell-history / trailing-space
28697        // paste footgun. Before this gate the top-level `s.trim()`
28698        // silently ate the trailing space and parsed to
28699        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
28700        // next emit — same canonical-form drift as the leading-space
28701        // sibling, closed on the same whitespace-byte arm.
28702        let payload = r#"{"rateLimit":"100/s "}"#;
28703        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28704        let msg = err.to_string();
28705        assert!(
28706            msg.contains("contains whitespace byte"),
28707            "expected whitespace diagnostic in {msg:?}"
28708        );
28709        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
28710    }
28711
28712    #[test]
28713    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
28714        // `"100 / s"` — the canonical typographically-spaced author
28715        // shape (the same idiom every prose reference to a rate limit
28716        // renders as, mistakenly retained when the value is pasted
28717        // into a codec-shaped slot). Before this gate the per-part
28718        // `rate_str.trim()` / `unit.trim()` calls silently ate both
28719        // spaces on either side of `/` and parsed to
28720        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
28721        // codec's *internal* whitespace-tolerance vector, orthogonal
28722        // to the leading / trailing surface but the same canonical-
28723        // form-drift class. Pins the arm as strictly stronger than the
28724        // pre-existing top-level `s.trim()` behavior: it fires on
28725        // whitespace anywhere in the value, not just at the string
28726        // boundary.
28727        let payload = r#"{"rateLimit":"100 / s"}"#;
28728        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28729        let msg = err.to_string();
28730        assert!(
28731            msg.contains("contains whitespace byte"),
28732            "expected whitespace diagnostic in {msg:?}"
28733        );
28734        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
28735    }
28736
28737    #[test]
28738    fn rate_limit_serde_rejects_tab_byte() {
28739        // `"\t100/s"` — the canonical paste-from-indented-doc /
28740        // paste-from-YAML-block-scalar footgun where a tab byte leads
28741        // the magnitude. Pins that the gate covers tab (`0x09`) as
28742        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
28743        // members and both would be silently swallowed by `s.trim()`
28744        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
28745        // space alone to the full ASCII-whitespace set (space `0x20`,
28746        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
28747        // the tab arm as a representative of the non-space members.
28748        let payload = r#"{"rateLimit":"\t100/s"}"#;
28749        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28750        let msg = err.to_string();
28751        assert!(
28752            msg.contains("contains whitespace byte"),
28753            "expected whitespace diagnostic in {msg:?}"
28754        );
28755        assert!(
28756            msg.contains("0x09"),
28757            "missing offending tab byte in {msg:?}"
28758        );
28759    }
28760
28761    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
28762    //
28763    // Successor to the ASCII-whitespace arm (1ad7755) on
28764    // `rate_limit_codec` — closes the strictly-complementary class the
28765    // byte-scan cannot see, through the lifted
28766    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
28767
28768    #[test]
28769    fn rate_limit_serde_rejects_leading_nbsp() {
28770        // NBSP prefix — paste-from-typography footgun. Byte-scan
28771        // misses, `str::trim` silently strips it, value drifts to
28772        // `"100/s"` on next serialize.
28773        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
28774        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28775        let msg = err.to_string();
28776        assert!(
28777            msg.contains("non-ASCII Unicode whitespace character"),
28778            "expected non-ASCII whitespace diagnostic in {msg:?}"
28779        );
28780        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
28781    }
28782
28783    #[test]
28784    fn rate_limit_serde_rejects_internal_em_space() {
28785        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
28786        // paste-from-typography footgun on the `<integer>/<unit>`
28787        // shape.
28788        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
28789        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
28790        let msg = err.to_string();
28791        assert!(
28792            msg.contains("non-ASCII Unicode whitespace character"),
28793            "expected non-ASCII whitespace diagnostic in {msg:?}"
28794        );
28795        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
28796    }
28797
28798    #[test]
28799    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
28800        // Positive-control pin: every ASCII-only canonical form the
28801        // renderer emits stays accepted through the new arm.
28802        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
28803            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
28804            let p: MeshPolicy = serde_json::from_str(&payload)
28805                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
28806            assert!(p.rate_limit.is_some());
28807        }
28808    }
28809
28810    #[test]
28811    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
28812        // The boundary case — `"0/s"` is the canonical form
28813        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
28814        // it at the parse layer; the downstream
28815        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
28816        // `rate == 0` at the typed-validate layer above. Pins the
28817        // partition: the leading-zero gate at the codec layer does
28818        // not poach the rate-zero semantic-validation arm at the
28819        // typed-validate layer above (a future stricter codec must
28820        // not reject `"0/s"` here, or it'd collapse the diagnostic
28821        // partitioning that lets `PolicyRateLimitZero` name the
28822        // offending typed slot).
28823        let payload = r#"{"rateLimit":"0/s"}"#;
28824        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
28825            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
28826        });
28827        let rl = policy.rate_limit.expect("rate_limit must be Some");
28828        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
28829        assert_eq!(
28830            rl.window,
28831            Duration::from_secs(1),
28832            "single-`0` magnitude with `s` unit must parse to window=1s"
28833        );
28834    }
28835
28836    #[test]
28837    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
28838        // The complementary boundary pin — every magnitude
28839        // `render` emits starts with `[1-9]` (or is the single byte
28840        // `"0"`), so the canonical-form predicate is `(len == 1) ||
28841        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
28842        // '1'` case explicitly so a future tightening of the gate
28843        // (e.g. an over-eager "no leading digit < 5" rule, or a
28844        // mistakenly anchored start-of-magnitude byte check) lands
28845        // here before the canonical-forms-iterating test would catch
28846        // it.
28847        let payload = r#"{"rateLimit":"100/s"}"#;
28848        let policy: MeshPolicy = serde_json::from_str(payload)
28849            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
28850        let rl = policy.rate_limit.expect("rate_limit must be Some");
28851        assert_eq!(
28852            rl.rate, 100,
28853            "canonical-100 magnitude must parse to rate=100"
28854        );
28855    }
28856
28857    #[test]
28858    fn rate_limit_serde_accepts_integer_canonical_forms() {
28859        // Pin the happy-path: every canonical author shape `render`
28860        // ever emits parses cleanly through the codec post-gate. The
28861        // codec's accepted set (post-gate) is exactly its emitted set
28862        // for the integer-magnitude class — same property
28863        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
28864        // gates guarantee on the peer codecs. Iterating across rate
28865        // magnitudes (including `"0"`, which the codec accepts even
28866        // though `validate_politicas` rejects `rate == 0` at the typed
28867        // layer above) closes the codec contract at the parse layer
28868        // independently of the validate layer.
28869        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
28870            for unit_lit in ["s", "m", "h"] {
28871                let lit = format!("{rate_lit}/{unit_lit}");
28872                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
28873                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
28874                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
28875                });
28876                let rl = policy.rate_limit.expect("rate_limit must be Some");
28877                assert_eq!(
28878                    rl.rate,
28879                    rate_lit.parse::<u32>().unwrap(),
28880                    "rate mismatch for {lit:?}"
28881                );
28882            }
28883        }
28884    }
28885
28886    #[test]
28887    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
28888        // The structural property the gate enforces: serialize ∘
28889        // deserialize is the identity on every canonical author shape.
28890        // Peer of `parse_byte_size`'s and `parse_duration`'s
28891        // `_round_trips_through_render_for_every_canonical_form` tests
28892        // on the rate-limit axis. Before the gate, `"+100/s"` violated
28893        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
28894        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
28895        for rate in [1u32, 100, 5000, 1_000_000] {
28896            for (window, unit) in [
28897                (Duration::from_secs(1), "s"),
28898                (Duration::from_secs(60), "m"),
28899                (Duration::from_secs(3600), "h"),
28900            ] {
28901                let policy = MeshPolicy {
28902                    rate_limit: Some(RateLimit { rate, window }),
28903                    ..Default::default()
28904                };
28905                let json = serde_json::to_string(&policy).unwrap();
28906                let expected = format!("\"{rate}/{unit}\"");
28907                assert!(
28908                    json.contains(&expected),
28909                    "expected {expected:?} in {json:?}"
28910                );
28911                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
28912                assert_eq!(
28913                    back.rate_limit, policy.rate_limit,
28914                    "round-trip for {json:?}"
28915                );
28916            }
28917        }
28918    }
28919
28920    // ── self-membership cross-slot gate ──────────────────────────────
28921
28922    #[test]
28923    fn validate_no_self_membership_rejects_self_named_membro() {
28924        // An Aplicacao whose `:membros` lists its own `:nome` is a
28925        // one-node lacre-closure recursion — rejected, naming the parent.
28926        let membros = vec![
28927            membro("catalog", "^0.1"),
28928            membro("checkout", "^0.1"),
28929            membro("cart", "^0.1"),
28930        ];
28931        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
28932        assert!(
28933            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
28934            "got {err:?}"
28935        );
28936    }
28937
28938    #[test]
28939    fn validate_no_self_membership_accepts_distinct_membros() {
28940        // Positive control: distinct member names (including a member
28941        // that is itself an Aplicacao — recursive composition is valid,
28942        // MESH-COMPOSITION §V) pass the gate.
28943        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
28944        validate_no_self_membership(&membros, "checkout").unwrap();
28945    }
28946
28947    #[test]
28948    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
28949        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
28950        // `NoMembros` arm (the more-fundamental "graph must have nodes"
28951        // gate), not by this cross-slot self-edge gate. Keeping the
28952        // self-membership predicate vacuously-ok on the empty input
28953        // matches its supervisor-axis peer
28954        // (`validate_no_self_supervision_empty_children_is_ok`) and
28955        // makes the gate composable from any future call site (an M4
28956        // CR materializer's per-membros validator) without re-checking
28957        // emptiness.
28958        validate_no_self_membership(&[], "checkout").unwrap();
28959    }
28960
28961    #[test]
28962    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
28963        // Pinning the Display: the self-membership diagnostic must name
28964        // the offending caixa verbatim + the "lists itself" framing the
28965        // author can grep for, so the cluster-far failure surfaces at
28966        // build time with one-line remediation. Same diagnostic shape
28967        // as the supervisor-axis `ChildSupervisesSelf` peer.
28968        let membros = vec![membro("orquestra", "^0.1")];
28969        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
28970        let msg = err.to_string();
28971        assert!(
28972            msg.contains("orquestra"),
28973            "diagnostic must name the offending caixa nome (got: {msg:?})"
28974        );
28975        assert!(
28976            msg.contains("lists itself"),
28977            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
28978        );
28979    }
28980
28981    #[test]
28982    fn default_servico_port_constant_pins_canonical_8080_literal() {
28983        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
28984        // at the verbatim `8080` literal both consumers (the
28985        // `Entrada::port` serde default via [`default_port`] and the
28986        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
28987        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
28988        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
28989        // discipline (a085b26) on the per-renderer canonical-K8s-axis
28990        // string-constant axis: a future refactor that drifts the
28991        // constant out from under either consumer surfaces here ahead
28992        // of every per-renderer's first emission. The literal value
28993        // matches the well-known HTTP-alt port the `pleme-computeunit`
28994        // library chart already emits as its `trigger.service.port`
28995        // default — by construction the same value the substrate
28996        // assumes about every Servico's in-cluster L4 listener.
28997        assert_eq!(
28998            DEFAULT_SERVICO_PORT, 8080,
28999            "canonical Servico port literal must remain `8080` verbatim — \
29000             this is the value both the `Entrada::port` serde default and the \
29001             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
29002        );
29003    }
29004
29005    #[test]
29006    fn default_port_helper_returns_canonical_servico_port_constant() {
29007        // The bridge-arm — pins that the [`default_port`] helper
29008        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
29009        // attribute hooks routes through the lifted
29010        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
29011        // literal. A future refactor that re-introduces the `8080`
29012        // literal at the helper's return site (silently re-opening
29013        // the drift footgun this lift closed) surfaces here ahead of
29014        // every author-side `(:entrada (:host … :para …))` slot
29015        // without an explicit `:port`. Peer with the
29016        // `default_namespace_re_export_points_at_caixa_core_canonical`
29017        // pin on the caixa-mesh-side re-export axis.
29018        assert_eq!(
29019            default_port(),
29020            DEFAULT_SERVICO_PORT,
29021            "the serde-default helper must route through the lifted constant"
29022        );
29023    }
29024
29025    #[test]
29026    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
29027        // The end-to-end pin — an author-surface `(:entrada (:host …
29028        // :para …))` without an explicit `:port` slot deserializes to
29029        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
29030        // verbatim. Routes the canonical lifted constant through both
29031        // the serde-default machinery (the `#[serde(default =
29032        // "default_port")]` attribute) and the typed-value-shape
29033        // contract (the resulting [`Entrada::port`] value). A future
29034        // refactor that drifts either axis — replacing the serde
29035        // hook's helper, changing the typed slot's wire shape — would
29036        // surface here before any per-renderer's CNP / Gateway /
29037        // HTTPRoute emission consumed the drifted default.
29038        let entrada: Entrada =
29039            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
29040        assert_eq!(
29041            entrada.port, DEFAULT_SERVICO_PORT,
29042            "the serde default must materialize as the lifted canonical Servico port"
29043        );
29044    }
29045
29046    #[test]
29047    fn servico_port_min_pins_canonical_accept_set_floor() {
29048        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
29049        // verbatim `1` literal every typed `:entrada :port` acceptance
29050        // gate keys off. Peer with the
29051        // [`default_servico_port_constant_pins_canonical_8080_literal`]
29052        // discipline on the canonical-Servico-port-constant axis: a
29053        // future refactor that drifts the accept-set floor out from
29054        // under the sole consumer at [`AplicacaoSpec::validate`]'s
29055        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
29056        // every per-`:entrada` `EntradaPortZero` diagnostic. The
29057        // literal value matches the IANA-registered TCP/UDP port
29058        // space floor (`1..=65535` — port `0` is the "any ephemeral"
29059        // sentinel, not a well-defined destination the substrate's
29060        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
29061        // axis can honor).
29062        assert_eq!(
29063            SERVICO_PORT_MIN, 1,
29064            "canonical Servico port accept-set floor must remain `1` verbatim — \
29065             this is the value the `AplicacaoSpec::validate` gate at \
29066             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
29067        );
29068    }
29069
29070    #[test]
29071    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
29072        // The cross-const invariant pin — the substrate's canonical
29073        // default port must satisfy its own accept-set floor by
29074        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
29075        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
29076        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
29077        // override the operator pins through a future
29078        // `:placement :default-port` slot that lands out-of-range, a
29079        // per-edition Servico-port migration that lifted the floor
29080        // above the previous default without coordinating the pair —
29081        // would silently invalidate the serde-default emission at
29082        // every author-side `(:entrada (:host … :para …))` slot
29083        // without an explicit `:port`: the default port would fall
29084        // below the accept-set floor, the `AplicacaoSpec::validate`
29085        // gate would reject every default-carrying Aplicacao as
29086        // `EntradaPortZero`, and the substrate's typed
29087        // `(defcaixa … :kind Aplicacao)` surface would fail validate
29088        // on every Aplicacao whose author omitted `:entrada :port`
29089        // for the substrate's chosen default — a class of authoring-
29090        // surface footguns the compile-time pin structurally closes.
29091        // Peer with the
29092        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
29093        // (27f9b34) cross-const invariant pin discipline on the peer
29094        // canonical-Helm-per-values-block child-chart-enablement-toggle
29095        // axis pair.
29096        const {
29097            assert!(
29098                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
29099                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
29100                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
29101                 every default-carrying `(:entrada (:host … :para …))` slot \
29102                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
29103                 through the serde default hook and must pass the \
29104                 `AplicacaoSpec::validate` floor gate by construction",
29105            );
29106        }
29107    }
29108
29109    #[test]
29110    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
29111        // The gate-site pin — asserts the `AplicacaoSpec::validate`
29112        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
29113        // `EntradaPortZero` diagnostic on the below-floor input
29114        // `port: 0` (the only below-floor value the `u16` field can
29115        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
29116        // is the singleton `{0}`). A future refactor that drifts the
29117        // gate off the lifted const (silently re-introducing an
29118        // inline `if e.port == 0` byte-check) surfaces here — the
29119        // pin cannot distinguish `< 1` from `== 0` on the current
29120        // floor, but it *does* pin that the diagnostic fires on `0`
29121        // through whichever gate is wired, so any future accept-set
29122        // floor migration (a hypothetical unprivileged-only
29123        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
29124        // update this test alongside the const declaration —
29125        // structurally guaranteeing the gate + accept-set + pin
29126        // trio move together. Peer with the
29127        // [`rejects_zero_entrada_port`] behavioral pin on the same
29128        // per-`:entrada :port` axis — that pin asserts the pre-lift
29129        // behavioral contract (`port: 0` → `EntradaPortZero`); this
29130        // pin adds the structural link to the lifted floor const.
29131        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
29132        let mut s = three_member_spec();
29133        s.entrada.as_mut().unwrap().port = 0;
29134        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
29135    }
29136
29137    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
29138
29139    #[test]
29140    fn membro_serde_keys_match_lifted_membro_key_consts() {
29141        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
29142        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
29143        // name the exact camelCase JSON keys the
29144        // `#[serde(rename_all = "camelCase")]` attribute on
29145        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
29146        // that each canonical byte-sequence appears verbatim in the
29147        // JSON — a future accidental `rename_all = "snake_case"` /
29148        // `"kebab-case"` / verbatim-field-name flip at the derive
29149        // attribute (any of which would silently break every downstream
29150        // JSON consumer that reaches for one of the two consts via
29151        // `Value::get(...)`) surfaces here as a build-time test failure
29152        // at `aplicacao.rs`, not as an apply-time
29153        // `.get(<stale-canonical-const>)` returning `None` far from the
29154        // derive-attr drift's commit. Peer with the sibling
29155        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
29156        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
29157        // same discipline the SupervisorSpec top-level lift established,
29158        // extended here to the M3 [`Membro`] per-`:membros` axis.
29159        let m = Membro {
29160            caixa: "catalog".into(),
29161            versao: "^0.1".into(),
29162        };
29163        let json = serde_json::to_string(&m).unwrap();
29164        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
29165            let quoted = format!("\"{key}\"");
29166            assert!(
29167                json.contains(&quoted),
29168                "serialized Membro must carry the lifted MEMBRO_KEY_* \
29169                 byte-sequence {quoted} verbatim in the JSON emission \
29170                 (got: {json})",
29171            );
29172        }
29173    }
29174
29175    #[test]
29176    fn membro_key_consts_are_pairwise_distinct() {
29177        // Cross-axis drift-detection pin: a future collapse of the two
29178        // canonical [`Membro`] per-entry byte-strings onto the same
29179        // value (e.g. an accidental copy-paste flip of
29180        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
29181        // silently reroute every downstream probe on one axis onto the
29182        // sibling axis's overlay entry and pass every propagation-probe
29183        // test that expected only the stale axis's value. Peer of the
29184        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
29185        // (40cc4e5).
29186        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
29187        for (i, a) in all.iter().enumerate() {
29188            for b in all.iter().skip(i + 1) {
29189                assert_ne!(
29190                    a, b,
29191                    "MEMBRO_KEY_* consts must be pairwise-distinct \
29192                     canonical byte-sequences — got `{a}` == `{b}`",
29193                );
29194            }
29195        }
29196    }
29197
29198    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
29199    //    URL-path fallback resolver every HTTPRoute-aware renderer
29200    //    reaching for a per-rule path-list resolution routes through.
29201    //    The four pin tests below fix the four-way accept-set the
29202    //    resolver must always honor: (:paths-non-empty-verbatim,
29203    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
29204    //    :paths-preserves-order-across-multiple-entries) — drift on any
29205    //    arm surfaces at caixa-core build time rather than at cluster-
29206    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
29207    //    sibling `:politicas` typed-primitive dispatch axis.
29208
29209    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
29210        Entrada {
29211            host: "example.com".into(),
29212            para: "cart".into(),
29213            paths: paths.into_iter().map(String::from).collect(),
29214            port: DEFAULT_SERVICO_PORT,
29215        }
29216    }
29217
29218    #[test]
29219    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
29220        // The typed `:entrada :paths` slot carries an author-declared
29221        // list — the resolver returns each entry verbatim, no
29222        // catch-all substitution. The canonical "author declared
29223        // paths, honor them verbatim" arm of the path-list dispatch.
29224        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
29225        assert_eq!(
29226            e.resolved_paths(),
29227            vec!["/api/cart", "/api/products"],
29228            "resolved_paths must return each `:entrada :paths` entry \
29229             verbatim when the typed slot is non-empty (got {:?})",
29230            e.resolved_paths(),
29231        );
29232    }
29233
29234    #[test]
29235    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
29236        // Empty `:entrada :paths` slot — the resolver substitutes the
29237        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
29238        // catch-all fallback verbatim. Pins the empty-arm of the
29239        // resolver's four-way accept-set against a future silent
29240        // detour that returned an empty Vec (which would emit an
29241        // HTTPRoute with zero rules — silently dropping every
29242        // external `:entrada` flow at admission time), routed to a
29243        // different fallback shape, or dropped the catch-all
29244        // altogether.
29245        let e = entrada_with_paths(vec![]);
29246        assert_eq!(
29247            e.resolved_paths(),
29248            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
29249            "resolved_paths on empty `:entrada :paths` must fall back \
29250             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
29251             all — got {:?}",
29252            e.resolved_paths(),
29253        );
29254    }
29255
29256    #[test]
29257    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
29258        // Single-entry `:entrada :paths` — the resolver returns the
29259        // single declared path verbatim, NOT the catch-all fallback
29260        // (author declared a path, honor it — the empty-arm and the
29261        // len-1 arm are semantically distinct axes of the resolver's
29262        // accept-set). Pins that the resolver treats "author declared
29263        // one path" as authored input, not as the empty case.
29264        let e = entrada_with_paths(vec!["/api/only"]);
29265        assert_eq!(
29266            e.resolved_paths(),
29267            vec!["/api/only"],
29268            "resolved_paths on single-entry `:entrada :paths` must \
29269             return the declared path verbatim, NOT the catch-all \
29270             fallback (got {:?})",
29271            e.resolved_paths(),
29272        );
29273    }
29274
29275    #[test]
29276    fn resolved_paths_preserves_author_declared_order() {
29277        // The `:entrada :paths` list is author-ordered — the resolver
29278        // preserves the author's declaration order verbatim, since
29279        // per-rule dispatch order at the K8s Gateway API HTTPRoute
29280        // consumer is significant (first-match-wins under the
29281        // path-prefix matcher). Pins against a future silent
29282        // re-sort / dedup / normalize detour that reordered author
29283        // input.
29284        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
29285        assert_eq!(
29286            e.resolved_paths(),
29287            vec!["/z/last", "/a/first", "/m/mid"],
29288            "resolved_paths must preserve author-declared `:entrada \
29289             :paths` order verbatim — got {:?}",
29290            e.resolved_paths(),
29291        );
29292    }
29293
29294    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
29295    //    slot `&[String]` slice accessor every per-`:entrada` consumer
29296    //    that must see the author's declaration verbatim (not the
29297    //    fallback-applied projection the sibling `resolved_paths`
29298    //    returns) routes through. The three pin tests below fix the
29299    //    accept-set the accessor must honor: (:non-empty-byte-equal,
29300    //    :empty-projects-empty-slice, :preserves-author-declared-order)
29301    //    — drift on any arm surfaces at caixa-core build time rather
29302    //    than at cluster-apply time. Peer discipline with the sibling
29303    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
29304    //    peer M3 mesh-slot `Vec<String>`-carry axis.
29305
29306    #[test]
29307    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
29308        // Byte-equal pin: [`Entrada::paths`] must project the raw
29309        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
29310        // slice borrowed from the typed slot's own [`Vec<String>`]
29311        // storage — no re-ordering, no dedup, no per-entry normalization,
29312        // no fallback substitution (the fallback-applying projection is
29313        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
29314        // a future silent detour that re-normalized the list, dropped
29315        // duplicates the [`AplicacaoSpec::validate`]
29316        // `EntradaPathDuplicate` refusal already rejects at build time,
29317        // or (most severe) accidentally routed through the fallback-
29318        // applying sibling and returned the substrate catch-all when
29319        // the author declared an empty list — collapsing the raw-slot
29320        // and fallback-applied axes into one and breaking the
29321        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
29322        //
29323        // Peer of the sibling
29324        // [`Placement::clusters`]-shape byte-equal pin
29325        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
29326        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
29327        let fixtures: Vec<Vec<String>> = vec![
29328            Vec::new(),
29329            vec!["/api/cart".into()],
29330            vec!["/api/cart".into(), "/api/products".into()],
29331            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
29332        ];
29333        for paths in fixtures {
29334            let e = Entrada {
29335                host: "example.com".into(),
29336                para: "cart".into(),
29337                paths: paths.clone(),
29338                port: DEFAULT_SERVICO_PORT,
29339            };
29340            assert_eq!(
29341                e.paths(),
29342                paths.as_slice(),
29343                "Entrada::paths must return :entrada :paths verbatim \
29344                 (got {:?}, expected {:?})",
29345                e.paths(),
29346                paths.as_slice(),
29347            );
29348            assert_eq!(
29349                e.paths(),
29350                e.paths.as_slice(),
29351                "Entrada::paths accessor and .paths.as_slice() field \
29352                 access must byte-equal — the accessor is the substrate-\
29353                 primitive typed dispatch every downstream per-`:entrada` \
29354                 raw-slot path-list consumer must route through",
29355            );
29356            assert_eq!(
29357                e.paths().len(),
29358                e.paths.len(),
29359                "Entrada::paths().len() must byte-equal self.paths.len() \
29360                 — a length drift would silently split the paired \
29361                 pre-flight cascade-head `.is_empty()` probe input in \
29362                 the sibling [`Entrada::resolved_paths`] resolver from \
29363                 the per-entry validate loop's traversal input in \
29364                 [`AplicacaoSpec::validate`]",
29365            );
29366        }
29367    }
29368
29369    #[test]
29370    fn resolved_paths_reads_through_lifted_paths_accessor() {
29371        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
29372        // pre-flight `.paths().is_empty()` cascade-head probe (which
29373        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
29374        // catch-all fallback arm when the accessor projects the empty
29375        // slice) and the per-entry `.paths().iter().map(String::as_str)`
29376        // projection (which must reach every entry in the same order
29377        // the accessor projects, so the sibling
29378        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
29379        // per-entry projection stay in lockstep by construction) must
29380        // both key off the lifted accessor. Pins the two-site coherence
29381        // by exercising each production consumer end-to-end: (1) the
29382        // catch-all-fallback arm under the empty slice, (2) the
29383        // author-declared-verbatim arm under a two-entry cohort whose
29384        // per-entry projection must byte-equal the input's per-entry
29385        // author-declared paths in the author's declared order.
29386        //
29387        // Peer of the sibling M3
29388        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
29389        // `validate_placement_reads_through_lifted_clusters_accessor`
29390        // on the sibling `Placement::clusters` reader-site convergence.
29391        let empty = entrada_with_paths(vec![]);
29392        assert_eq!(
29393            empty.resolved_paths(),
29394            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
29395            "resolved_paths on empty :entrada :paths must trip the \
29396             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
29397             catch-all fallback — routing through the lifted paths() \
29398             accessor must not silently drop the fallback arm",
29399        );
29400
29401        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
29402        assert_eq!(
29403            declared.resolved_paths(),
29404            vec!["/api/cart", "/api/products"],
29405            "resolved_paths on non-empty :entrada :paths must return each \
29406             entry verbatim in the author's declared order — routing \
29407             through the lifted paths() accessor must not silently \
29408             reorder or drop entries",
29409        );
29410        // Byte-equal pin against the raw-slot accessor to keep the
29411        // fallback-applying resolver's per-entry projection input in
29412        // lockstep with the raw-slot accessor's projection.
29413        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
29414        assert_eq!(
29415            declared.resolved_paths(),
29416            raw_projected,
29417            "resolved_paths non-empty projection must byte-equal the \
29418             lifted paths() accessor's per-entry String::as_str projection \
29419             — the two projections share the same input slice by \
29420             construction, so any drift here would surface a silent \
29421             re-ordering / dedup / normalization detour in the resolver",
29422        );
29423    }
29424
29425    #[test]
29426    fn validate_reads_through_lifted_entrada_paths_accessor() {
29427        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
29428        // per-entry value-shape gate's `for p in e.paths()` traversal
29429        // (which must reach every entry in the same order the accessor
29430        // projects, so both the per-entry `EntradaPathEmpty` /
29431        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
29432        // the duplicate-detection HashSet insert that trips
29433        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
29434        // projection) must route through the lifted accessor. Pins the
29435        // coherence by exercising each production consumer end-to-end:
29436        // (1) the `EntradaPathEmpty` refusal fires on the second entry
29437        // of a two-entry cohort whose head is valid but tail is empty
29438        // (which requires the loop to reach the second entry through
29439        // the accessor), and (2) the `EntradaPathDuplicate` refusal
29440        // fires on the second entry of a two-entry cohort that shares
29441        // a path (which requires the loop to reach both entries — a
29442        // first-entry-only projection would silently pass since the
29443        // dedup HashSet has room for the first insert).
29444        //
29445        // Peer of the sibling
29446        // `validate_placement_reads_through_lifted_clusters_accessor`
29447        // on the sibling `Placement::clusters` reader-site convergence.
29448        let base = crate::AplicacaoSpec {
29449            membros: vec![crate::Membro {
29450                caixa: "cart".into(),
29451                versao: "^0.1".into(),
29452            }],
29453            contratos: Vec::new(),
29454            politicas: crate::MeshPolicy::default(),
29455            placement: crate::Placement {
29456                estrategia: crate::PlacementStrategy::SingleNode,
29457                clusters: vec!["rio".into()],
29458                shard_key: None,
29459                affinity: None,
29460            },
29461            entrada: Some(Entrada {
29462                host: "example.com".into(),
29463                para: "cart".into(),
29464                paths: vec!["/api/cart".into(), String::new()],
29465                port: DEFAULT_SERVICO_PORT,
29466            }),
29467        };
29468        assert_eq!(
29469            base.validate(),
29470            Err(crate::AplicacaoError::EntradaPathEmpty),
29471            "validate must trip EntradaPathEmpty on the second entry of \
29472             a two-entry cohort — routing through the lifted paths() \
29473             accessor must not silently short-circuit the loop at the \
29474             valid head entry",
29475        );
29476
29477        let mut dup = base;
29478        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
29479        assert_eq!(
29480            dup.validate(),
29481            Err(crate::AplicacaoError::EntradaPathDuplicate {
29482                path: "/api/cart".into(),
29483            }),
29484            "validate must trip EntradaPathDuplicate on the second entry \
29485             of a two-entry cohort that shares a path — routing through \
29486             the lifted paths() accessor must not silently short-circuit \
29487             the dedup HashSet insert at the first entry",
29488        );
29489    }
29490
29491    // ── Entrada::hostname / Entrada::hostnames — the substrate-
29492    //    canonical per-`:entrada` DNS-hostname resolver pair every
29493    //    Gateway-API-aware renderer reaching for a per-listener
29494    //    singular `hostname:` filter (Gateway) or a per-route plural
29495    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
29496    //    The three pin tests below fix the two-way accept-set the pair
29497    //    must always honor: (:singular-byte-equal-to-host,
29498    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
29499    //    on any arm surfaces at caixa-core build time rather than at
29500    //    cluster-apply time when the API server refuses the HTTPRoute
29501    //    for non-intersecting hostname filters. Peer discipline with
29502    //    the sibling `resolved_paths` accept-set pin block above on the
29503    //    per-`:entrada` path-list resolver axis.
29504
29505    fn entrada_with_host(host: &str) -> Entrada {
29506        Entrada {
29507            host: host.into(),
29508            para: "cart".into(),
29509            paths: Vec::new(),
29510            port: DEFAULT_SERVICO_PORT,
29511        }
29512    }
29513
29514    #[test]
29515    fn hostname_returns_entrada_host_byte_equal() {
29516        // The canonical singular-axis pin: [`Entrada::hostname`] must
29517        // return the `:entrada :host` field byte-for-byte, borrowed
29518        // from the typed slot's own [`String`] storage. Pins against a
29519        // future silent detour that re-normalized the host (an
29520        // accidental `.to_lowercase()` — validate_entrada_host already
29521        // enforces lowercase, so any re-normalization is redundant + a
29522        // drift surface between the validator and the accessor), a
29523        // trailing-`.` fully-qualified DNS shape substitution, or a
29524        // Punycode round-trip that lowered a Unicode host through IDNA.
29525        let e = entrada_with_host("checkout.quero.cloud");
29526        assert_eq!(
29527            e.hostname(),
29528            "checkout.quero.cloud",
29529            "Entrada::hostname must return :entrada :host verbatim \
29530             (got {:?})",
29531            e.hostname(),
29532        );
29533        assert_eq!(
29534            e.hostname(),
29535            e.host.as_str(),
29536            "Entrada::hostname must byte-equal the .host field access",
29537        );
29538    }
29539
29540    #[test]
29541    fn hostnames_returns_singleton_of_hostname_accessor() {
29542        // The pair-invariant pin: [`Entrada::hostnames`] must always
29543        // return exactly `vec![hostname()]` — the singleton list whose
29544        // sole entry is the substrate's canonical per-`:entrada`
29545        // singular hostname. Pins the two-consumer coherence axis: the
29546        // Gateway listener's singular `hostname:` filter and the
29547        // HTTPRoute's plural `spec.hostnames[]` filter list must
29548        // agree, else the Gateway API v1.x conformance layer rejects
29549        // the HTTPRoute at attach time with
29550        // `Accepted:False/NoMatchingParent` (the parent Gateway's
29551        // listener hostname doesn't intersect the route's hostname
29552        // filter list) — a divergence whose apply-time symptom is far
29553        // from any single-site commit and never surfaces in the
29554        // emitted YAML. Pinning the pair-invariant here makes any
29555        // future accidental split (an accidental `.to_string() + "."`
29556        // trailing-`.` on the plural side that didn't land on the
29557        // singular side, an accidental prefix stripping on one axis,
29558        // an accidental wildcard prepend the SNI fan-out overlay
29559        // authors on the plural side without a paired singular
29560        // migration) trip at caixa-core build time.
29561        let e = entrada_with_host("checkout.quero.cloud");
29562        assert_eq!(
29563            e.hostnames(),
29564            vec![e.hostname()],
29565            "Entrada::hostnames must return `vec![hostname()]` under \
29566             the pair-invariant — got {:?} vs. singleton {:?}",
29567            e.hostnames(),
29568            vec![e.hostname()],
29569        );
29570    }
29571
29572    #[test]
29573    fn hostnames_is_singleton_under_single_host_author_surface() {
29574        // The singleton-shape pin: under today's single-hostname-per-
29575        // `:entrada` author surface (the `:host` slot is a single
29576        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
29577        // must always return a list of length exactly one. Pins
29578        // against a future silent detour that returned an empty list
29579        // (which would emit an HTTPRoute with `spec.hostnames: []` —
29580        // matching every incoming Host header regardless of the
29581        // Aplicacao's declared ingress apex, silently over-matching
29582        // every foreign VirtualHost the parent Gateway also fronts) or
29583        // a duplicated entry (which the Gateway API v1.x parser
29584        // accepts as a `[]-length-2 list of equal hostnames]` but
29585        // whose semantics differ from the intended singleton). The
29586        // author-surface extension point ("a future `:entrada
29587        // :alt-hosts` list overlay" the docstring names) is the sole
29588        // future axis that flips this pin — that migration will re-
29589        // author this test to pin the new plural cardinality.
29590        let e = entrada_with_host("checkout.quero.cloud");
29591        assert_eq!(
29592            e.hostnames().len(),
29593            1,
29594            "Entrada::hostnames must be a singleton under today's \
29595             single-hostname-per-`:entrada` author surface — got \
29596             length {}: {:?}",
29597            e.hostnames().len(),
29598            e.hostnames(),
29599        );
29600    }
29601
29602    // ── Entrada::destination — the substrate-canonical per-`:entrada`
29603    //    destination-Servico scalar accessor every Gateway-API
29604    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
29605    //    discriminator arg (HTTPRoute name composer) or a per-rule
29606    //    `backendRefs[0].name` axis routes through. The two pin tests
29607    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
29608    //    either arm surfaces at caixa-core build time rather than at
29609    //    cluster-apply time when an HTTPRoute's `metadata.name` and
29610    //    `backendRefs[]` silently disagree on which destination Servico
29611    //    the ingress fronts. Peer discipline with the sibling
29612    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
29613    //    blocks above on the per-`:entrada` path-list / DNS-hostname
29614    //    resolver axes.
29615
29616    #[test]
29617    fn destination_returns_entrada_para_byte_equal() {
29618        // The canonical destination-scalar pin: [`Entrada::destination`]
29619        // must return the `:entrada :para` field byte-for-byte, borrowed
29620        // from the typed slot's own [`String`] storage. Pins against a
29621        // future silent detour that re-normalized the destination (an
29622        // accidental `.to_lowercase()` — the destination Servico is
29623        // already validated as a DNS-1123 label upstream, so any
29624        // re-normalization is redundant + a drift surface between the
29625        // validator and the accessor), a namespace-prefix rewrite (an
29626        // accidental `format!("{namespace}/{para}")` per-CR fully-
29627        // qualified rewrite that didn't land on the peer axis), or a
29628        // per-cluster suffix stamp the operator authors on one
29629        // consumer without the other.
29630        for para in ["cart", "checkout", "catalog", "orders-v2"] {
29631            let e = Entrada {
29632                host: "checkout.quero.cloud".into(),
29633                para: para.into(),
29634                paths: Vec::new(),
29635                port: DEFAULT_SERVICO_PORT,
29636            };
29637            assert_eq!(
29638                e.destination(),
29639                para,
29640                "Entrada::destination must return :entrada :para verbatim \
29641                 (got {:?}, expected {para:?})",
29642                e.destination(),
29643            );
29644            assert_eq!(
29645                e.destination(),
29646                e.para.as_str(),
29647                "Entrada::destination must byte-equal the .para field access",
29648            );
29649        }
29650    }
29651
29652    #[test]
29653    fn destination_borrows_from_entrada_para_storage() {
29654        // The borrow-not-copy pin: [`Entrada::destination`] must
29655        // return a `&str` slice that borrows from the typed slot's
29656        // own [`String`] storage — same-address invariant with
29657        // `entrada.para.as_str()`. Pins against a future silent detour
29658        // that allocated a fresh `String` (`self.para.clone()` in the
29659        // body would type-check but silently drop the borrow, and
29660        // every downstream consumer that assumed the returned slice
29661        // outlives `&self` would break on a stale-reference use-after-
29662        // free). Peer with the sibling `hostname_returns_entrada_
29663        // host_byte_equal` on the singular-DNS-hostname axis.
29664        let e = entrada_with_host("checkout.quero.cloud");
29665        let dest = e.destination();
29666        let para_slice = e.para.as_str();
29667        assert_eq!(
29668            dest.as_ptr(),
29669            para_slice.as_ptr(),
29670            "Entrada::destination must borrow from the .para String's \
29671             backing storage — a fresh allocation here means the \
29672             accessor no longer names the substrate-primitive typed \
29673             dispatch and every downstream consumer would silently \
29674             carry a detached copy",
29675        );
29676        assert_eq!(
29677            dest.len(),
29678            para_slice.len(),
29679            "Entrada::destination and .para.as_str() must byte-equal in \
29680             length as well as in address",
29681        );
29682    }
29683
29684    #[test]
29685    fn port_returns_entrada_port_verbatim_across_permutations() {
29686        // The canonical L4-port-scalar pin: [`Entrada::port`] must
29687        // return the `:entrada :port` field verbatim as a `u16` across
29688        // every author-declared value in the validated accept-set
29689        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
29690        // silent detour that clamped the port (an accidental
29691        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
29692        // land on the peer [`AplicacaoSpec::port_for_destination`]
29693        // resolver), rewrote it through a per-cluster port-remap table
29694        // the operator authors on one consumer without the other, or
29695        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
29696        // serde-default value (which would silently collapse the
29697        // distinction between "author explicitly declared `:port 8080`"
29698        // and "author omitted the slot and inherited the default" the
29699        // future per-cluster override slot depends on). Peer with the
29700        // sibling `destination_returns_entrada_para_byte_equal` +
29701        // `hostname_returns_entrada_host_byte_equal` pins on the
29702        // per-`:entrada` `&str` scalar axes.
29703        for port in [
29704            SERVICO_PORT_MIN,
29705            DEFAULT_SERVICO_PORT,
29706            8443u16,
29707            9090u16,
29708            u16::MAX,
29709        ] {
29710            let e = Entrada {
29711                host: "checkout.quero.cloud".into(),
29712                para: "cart".into(),
29713                paths: Vec::new(),
29714                port,
29715            };
29716            assert_eq!(
29717                e.port(),
29718                port,
29719                "Entrada::port must return :entrada :port verbatim \
29720                 (got {}, expected {port})",
29721                e.port(),
29722            );
29723            assert_eq!(
29724                e.port(),
29725                e.port,
29726                "Entrada::port accessor and .port field access must \
29727                 byte-equal — the accessor is the substrate-primitive \
29728                 typed dispatch every downstream L4-port consumer must \
29729                 route through",
29730            );
29731        }
29732    }
29733
29734    #[test]
29735    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
29736        // Two-consumer coherence pin: the
29737        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
29738        // (which reads through [`Entrada::port`] to compare against
29739        // [`SERVICO_PORT_MIN`]) and the
29740        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
29741        // through [`Entrada::port`] to emit the per-destination
29742        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
29743        // lifted accessor, so any future rebrand on the typed slot's
29744        // reader shape lands at exactly one place. Pins the two-site
29745        // coherence by exercising a below-floor port through validate
29746        // (which must reject) and a validated in-accept-set port through
29747        // port_for_destination (which must emit the same value the
29748        // accessor returns).
29749        let mut spec = three_member_spec();
29750        if let Some(e) = spec.entrada.as_mut() {
29751            e.port = 0;
29752        }
29753        assert_eq!(
29754            spec.validate().unwrap_err(),
29755            AplicacaoError::EntradaPortZero,
29756            "validate must reject `:entrada :port 0` through the lifted \
29757             Entrada::port accessor — port zero lies below \
29758             SERVICO_PORT_MIN and the validator routes through port() \
29759             to name the floor",
29760        );
29761
29762        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
29763            let mut spec = three_member_spec();
29764            if let Some(e) = spec.entrada.as_mut() {
29765                e.port = port;
29766            }
29767            spec.validate().expect(
29768                "entrada with in-accept-set :port must validate — the \
29769                 structural-floor gate reads through Entrada::port",
29770            );
29771            let entrada_ref = spec.entrada().expect(":entrada present");
29772            assert_eq!(
29773                spec.port_for_destination(entrada_ref.destination()),
29774                entrada_ref.port(),
29775                "port_for_destination(entrada.destination()) must equal \
29776                 entrada.port() — the two consumers of the per-:entrada \
29777                 L4-port axis (validator, per-destination resolver) both \
29778                 route through Entrada::port",
29779            );
29780        }
29781    }
29782
29783    #[test]
29784    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
29785        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
29786        // must return the `:contratos :de` field byte-for-byte, borrowed
29787        // from the typed slot's own [`String`] storage. Peer of the
29788        // sibling `destination_returns_entrada_para_byte_equal` pin on
29789        // the per-`:entrada` axis — same "the substrate-primitive
29790        // accessor must byte-equal the raw field access verbatim across
29791        // every author-declared value" discipline extended to the
29792        // per-`:contratos` caller arm. Pins against a future silent
29793        // detour that re-normalized the caller (an accidental
29794        // `.to_lowercase()` — every `:contratos :de` is validated as a
29795        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
29796        // re-normalization is redundant + a drift surface between the
29797        // validator and the accessor), a namespace-prefix rewrite (an
29798        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
29799        // rewrite that didn't land on the peer axis), or a per-cluster
29800        // suffix stamp the operator authors on one consumer without the
29801        // other.
29802        for de in ["cart", "checkout", "catalog", "orders-v2"] {
29803            let c = WitContract {
29804                de: de.into(),
29805                para: "downstream".into(),
29806                wit: "wasi:http/proxy".into(),
29807                endpoint: Some("/lookup".into()),
29808                subject: None,
29809                slot: None,
29810            };
29811            assert_eq!(
29812                c.source(),
29813                de,
29814                "WitContract::source must return :contratos :de verbatim \
29815                 (got {:?}, expected {de:?})",
29816                c.source(),
29817            );
29818            assert_eq!(
29819                c.source(),
29820                c.de.as_str(),
29821                "WitContract::source must byte-equal the .de field access",
29822            );
29823        }
29824    }
29825
29826    #[test]
29827    fn wit_contract_source_borrows_from_de_storage() {
29828        // The borrow-not-copy pin: [`WitContract::source`] must return a
29829        // `&str` slice that borrows from the typed slot's own [`String`]
29830        // storage — same-address invariant with `c.de.as_str()`. Pins
29831        // against a future silent detour that allocated a fresh `String`
29832        // (`self.de.clone()` in the body would type-check but silently
29833        // drop the borrow, and every downstream consumer that assumed
29834        // the returned slice outlives `&self` would break on a stale-
29835        // reference use-after-free). Peer of the sibling
29836        // `destination_borrows_from_entrada_para_storage` on the
29837        // per-`:entrada` axis.
29838        let c = WitContract {
29839            de: "cart".into(),
29840            para: "catalog".into(),
29841            wit: "wasi:http/proxy".into(),
29842            endpoint: Some("/lookup".into()),
29843            subject: None,
29844            slot: None,
29845        };
29846        let src = c.source();
29847        let de_slice = c.de.as_str();
29848        assert_eq!(
29849            src.as_ptr(),
29850            de_slice.as_ptr(),
29851            "WitContract::source must borrow from the .de String's \
29852             backing storage — a fresh allocation here means the \
29853             accessor no longer names the substrate-primitive typed \
29854             dispatch and every downstream consumer would silently \
29855             carry a detached copy",
29856        );
29857        assert_eq!(
29858            src.len(),
29859            de_slice.len(),
29860            "WitContract::source and .de.as_str() must byte-equal in \
29861             length as well as in address",
29862        );
29863    }
29864
29865    #[test]
29866    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
29867        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
29868        // must return the `:contratos :para` field byte-for-byte,
29869        // borrowed from the typed slot's own [`String`] storage. Peer of
29870        // the sibling `destination_returns_entrada_para_byte_equal` on
29871        // the per-`:entrada` axis — both accessors name "the destination-
29872        // Servico byte-string" concept on their respective mesh-slot
29873        // atoms (per-ingress apex vs. per-typed-edge callee) and both
29874        // must project the underlying `.para` field verbatim so every
29875        // downstream renderer that composes them with peer accessors
29876        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
29877        // per-edge L4 port emit site) reads the same byte-string the
29878        // author declared.
29879        for para in ["catalog", "payment", "orders", "inventory-v3"] {
29880            let c = WitContract {
29881                de: "cart".into(),
29882                para: para.into(),
29883                wit: "wasi:http/proxy".into(),
29884                endpoint: Some("/lookup".into()),
29885                subject: None,
29886                slot: None,
29887            };
29888            assert_eq!(
29889                c.destination(),
29890                para,
29891                "WitContract::destination must return :contratos :para \
29892                 verbatim (got {:?}, expected {para:?})",
29893                c.destination(),
29894            );
29895            assert_eq!(
29896                c.destination(),
29897                c.para.as_str(),
29898                "WitContract::destination must byte-equal the .para \
29899                 field access",
29900            );
29901        }
29902    }
29903
29904    #[test]
29905    fn wit_contract_destination_borrows_from_para_storage() {
29906        // The borrow-not-copy pin: [`WitContract::destination`] must
29907        // return a `&str` slice that borrows from the typed slot's own
29908        // [`String`] storage — same-address invariant with
29909        // `c.para.as_str()`. Peer of the sibling
29910        // `destination_borrows_from_entrada_para_storage` on the
29911        // per-`:entrada` axis.
29912        let c = WitContract {
29913            de: "cart".into(),
29914            para: "catalog".into(),
29915            wit: "wasi:http/proxy".into(),
29916            endpoint: Some("/lookup".into()),
29917            subject: None,
29918            slot: None,
29919        };
29920        let dest = c.destination();
29921        let para_slice = c.para.as_str();
29922        assert_eq!(
29923            dest.as_ptr(),
29924            para_slice.as_ptr(),
29925            "WitContract::destination must borrow from the .para \
29926             String's backing storage — a fresh allocation here means \
29927             the accessor no longer names the substrate-primitive typed \
29928             dispatch and every downstream consumer would silently \
29929             carry a detached copy",
29930        );
29931        assert_eq!(
29932            dest.len(),
29933            para_slice.len(),
29934            "WitContract::destination and .para.as_str() must byte-equal \
29935             in length as well as in address",
29936        );
29937    }
29938
29939    #[test]
29940    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
29941        // The canonical per-`:contratos` WIT-world-reference scalar pin:
29942        // [`WitContract::world_ref`] must return the `:contratos :wit`
29943        // field byte-for-byte, borrowed from the typed slot's own
29944        // [`String`] storage. Sibling of the peer per-`:contratos`
29945        // [`WitContract::source`] / [`WitContract::destination`]
29946        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
29947        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
29948        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
29949        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
29950        // "the substrate-primitive accessor must byte-equal the raw
29951        // field access verbatim across every author-declared value"
29952        // discipline extended to the per-`:contratos` WIT-world arm.
29953        // Pins against a future silent detour that re-canonicalized the
29954        // WIT world reference (an accidental `.to_lowercase()` pass that
29955        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
29956        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
29957        // gate is already lowercase-prefixed so any re-normalization is
29958        // redundant + a drift surface between the validator and the
29959        // accessor), an M4-promotion-shape rewrite that formatted a
29960        // typed WIT-world enum through [`Display`] and silently drifted
29961        // the printer output from the source `caixa.lisp`, or a per-
29962        // cluster WIT-alias rewrite that didn't land on the peer field-
29963        // access sites. Five values sweep the shape-dispatch accept-set
29964        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
29965        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
29966        // `wasi:keyvalue/`).
29967        for (wit, endpoint, subject, slot) in [
29968            ("wasi:http/proxy", Some("/lookup"), None, None),
29969            ("http:proxy", Some("/health"), None, None),
29970            ("nats:pub-sub", None, Some("orders.paid"), None),
29971            ("kafka:events", None, Some("checkout-events"), None),
29972            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
29973        ] {
29974            let c = WitContract {
29975                de: "cart".into(),
29976                para: "downstream".into(),
29977                wit: wit.into(),
29978                endpoint: endpoint.map(str::to_string),
29979                subject: subject.map(str::to_string),
29980                slot: slot.map(str::to_string),
29981            };
29982            assert_eq!(
29983                c.world_ref(),
29984                wit,
29985                "WitContract::world_ref must return :contratos :wit \
29986                 verbatim (got {:?}, expected {wit:?})",
29987                c.world_ref(),
29988            );
29989            assert_eq!(
29990                c.world_ref(),
29991                c.wit.as_str(),
29992                "WitContract::world_ref must byte-equal the .wit field \
29993                 access",
29994            );
29995        }
29996    }
29997
29998    #[test]
29999    fn wit_contract_world_ref_borrows_from_wit_storage() {
30000        // The borrow-not-copy pin: [`WitContract::world_ref`] must
30001        // return a `&str` slice that borrows from the typed slot's own
30002        // [`String`] storage — same-address invariant with
30003        // `c.wit.as_str()`. Pins against a future silent detour that
30004        // allocated a fresh `String` (`self.wit.clone()` in the body
30005        // would type-check but silently drop the borrow, and every
30006        // downstream consumer that assumed the returned slice outlives
30007        // `&self` would break on a stale-reference use-after-free — the
30008        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
30009        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
30010        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
30011        // / [`is_pubsub`][WitContract::is_pubsub] /
30012        // [`is_store`][WitContract::is_store] methods route through —
30013        // each borrow from the WitContract's own storage and each would
30014        // silently misbehave if this accessor produced a detached copy).
30015        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
30016        // [`WitContract::destination`] and per-`:entrada`
30017        // [`Entrada::destination`] / [`Entrada::hostname`] and
30018        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
30019        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
30020        let c = WitContract {
30021            de: "cart".into(),
30022            para: "catalog".into(),
30023            wit: "wasi:http/proxy".into(),
30024            endpoint: Some("/lookup".into()),
30025            subject: None,
30026            slot: None,
30027        };
30028        let world = c.world_ref();
30029        let wit_slice = c.wit.as_str();
30030        assert_eq!(
30031            world.as_ptr(),
30032            wit_slice.as_ptr(),
30033            "WitContract::world_ref must borrow from the .wit String's \
30034             backing storage — a fresh allocation here means the \
30035             accessor no longer names the substrate-primitive typed \
30036             dispatch and every downstream consumer would silently carry \
30037             a detached copy",
30038        );
30039        assert_eq!(
30040            world.len(),
30041            wit_slice.len(),
30042            "WitContract::world_ref and .wit.as_str() must byte-equal in \
30043             length as well as in address",
30044        );
30045    }
30046
30047    #[test]
30048    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
30049        // Sibling-triple invariant pin composing all three per-`:contratos`
30050        // substrate-primitive typed dispatches — [`WitContract::source`]
30051        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
30052        // [`WitContract::world_ref`] — at the joint
30053        // `(source(), destination(), world_ref())` call shape every
30054        // renderer that fans on per-edge caller-callee-shape identity
30055        // keys off. The invariant, evaluated per-contract:
30056        //
30057        //   (c.source(), c.destination(), c.world_ref())
30058        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
30059        //
30060        // Closes the last unlifted per-`:contratos` scalar axis — every
30061        // downstream consumer that reads the triple now routes through
30062        // exactly three typed dispatches on the substrate primitive,
30063        // not two typed + one open-coded field access. A future refactor
30064        // that silently split any one accessor's projection (an
30065        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
30066        // canonicalization that didn't reach the peer `source`/
30067        // `destination` arms, an accidental `source()` per-cluster
30068        // caller-alias rewrite that didn't land on the `world_ref` peer)
30069        // surfaces at caixa-core build time. Peer of the sibling per-
30070        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
30071        // per-`:entrada` `(hostname(), destination())` (6db982c /
30072        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
30073        // axes, extended to the per-`:contratos` triple.
30074        for (de, para, wit, endpoint, subject, slot) in [
30075            (
30076                "cart",
30077                "catalog",
30078                "wasi:http/proxy",
30079                Some("/lookup"),
30080                None,
30081                None,
30082            ),
30083            (
30084                "checkout",
30085                "orders",
30086                "nats:pub-sub",
30087                None,
30088                Some("orders.paid"),
30089                None,
30090            ),
30091            (
30092                "cart",
30093                "kv",
30094                "wasi:keyvalue/store",
30095                None,
30096                None,
30097                Some("carts/{cart_id}"),
30098            ),
30099            (
30100                "orders-v2",
30101                "inventory-v3",
30102                "http:proxy",
30103                Some("/reserve"),
30104                None,
30105                None,
30106            ),
30107        ] {
30108            let c = WitContract {
30109                de: de.into(),
30110                para: para.into(),
30111                wit: wit.into(),
30112                endpoint: endpoint.map(str::to_string),
30113                subject: subject.map(str::to_string),
30114                slot: slot.map(str::to_string),
30115            };
30116            assert_eq!(
30117                (c.source(), c.destination(), c.world_ref()),
30118                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
30119                "(WitContract::source, ::destination, ::world_ref) must \
30120                 project (.de, .para, .wit) verbatim across every author-\
30121                 declared triple (got ({:?}, {:?}, {:?}), expected \
30122                 ({de:?}, {para:?}, {wit:?}))",
30123                c.source(),
30124                c.destination(),
30125                c.world_ref(),
30126            );
30127        }
30128    }
30129
30130    #[test]
30131    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
30132        // The canonical per-`:contratos` owned-form caller-callee-pair
30133        // pin: [`WitContract::edge_pair`] must return the
30134        // `(source(), destination())` tuple in owned form byte-for-byte,
30135        // projected through the lifted [`WitContract::source`] /
30136        // [`WitContract::destination`] scalar accessors. Pins the
30137        // composite-projection invariant on the per-`:contratos`
30138        // mesh-slot atom — every author-declared `(de, para)` pair must
30139        // round-trip verbatim through the substrate primitive's typed
30140        // dispatch, so the nine [`AplicacaoError`] diagnostic-
30141        // construction sites the accessor now feeds
30142        // ([`AplicacaoError::EmptyWit`],
30143        // [`AplicacaoError::ContratoEndpointEmpty`],
30144        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
30145        // [`AplicacaoError::ContratoEndpointInvalid`],
30146        // [`AplicacaoError::ContratoSubjectEmpty`],
30147        // [`AplicacaoError::ContratoSubjectInvalid`],
30148        // [`AplicacaoError::ContratoSlotEmpty`],
30149        // [`AplicacaoError::ContratoSlotInvalid`],
30150        // [`AplicacaoError::ContratoDuplicate`]) all read the same
30151        // `(de, para)` label pair every author sees at the source
30152        // `caixa.lisp`. Pins against a future silent detour that swapped
30153        // the `.0` / `.1` arms (an accidental `(destination(),
30154        // source())` re-order in the body would silently invert every
30155        // downstream diagnostic's `de:` / `para:` label pair, silently
30156        // reversing the direction of every operator-facing typed error
30157        // arrow), a fresh-allocation shape drift (an accidental
30158        // `.to_string()` on one arm but not the other would leave the
30159        // owned/borrowed pair mismatched vs. the sibling `source()` /
30160        // `destination()` returns), or an M4 per-cluster caller/callee-
30161        // alias rewrite that landed on `source()` without reaching
30162        // `destination()` (or vice versa). Peer of the sibling per-
30163        // `:contratos` `(source, destination, world_ref)` triple
30164        // pin above on the mesh-slot-atom scalar-value axes, extended
30165        // to the owned-form pair-projection axis.
30166        for (de, para, wit, endpoint, subject, slot) in [
30167            (
30168                "cart",
30169                "catalog",
30170                "wasi:http/proxy",
30171                Some("/lookup"),
30172                None,
30173                None,
30174            ),
30175            (
30176                "checkout",
30177                "orders",
30178                "nats:pub-sub",
30179                None,
30180                Some("orders.paid"),
30181                None,
30182            ),
30183            (
30184                "cart",
30185                "kv",
30186                "wasi:keyvalue/store",
30187                None,
30188                None,
30189                Some("carts/{cart_id}"),
30190            ),
30191            (
30192                "orders-v2",
30193                "inventory-v3",
30194                "http:proxy",
30195                Some("/reserve"),
30196                None,
30197                None,
30198            ),
30199        ] {
30200            let c = WitContract {
30201                de: de.into(),
30202                para: para.into(),
30203                wit: wit.into(),
30204                endpoint: endpoint.map(str::to_string),
30205                subject: subject.map(str::to_string),
30206                slot: slot.map(str::to_string),
30207            };
30208            assert_eq!(
30209                c.edge_pair(),
30210                (de.to_string(), para.to_string()),
30211                "WitContract::edge_pair must return (:contratos :de, \
30212                 :contratos :para) as an owned tuple verbatim (got {:?}, \
30213                 expected ({de:?}, {para:?}))",
30214                c.edge_pair(),
30215            );
30216        }
30217    }
30218
30219    #[test]
30220    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
30221        // The composition pin: [`WitContract::edge_pair`] must return
30222        // exactly `(source().to_string(), destination().to_string())` —
30223        // the owned form of the sibling accessor pair — so any future
30224        // refactor that silently re-authored the caller-arm / callee-arm
30225        // projection to bypass the lifted scalar accessors (an accidental
30226        // `(self.de.clone(), self.para.clone())` regression back to the
30227        // raw field-access shape, an M4-typed-caller-enum `Display`
30228        // re-canonicalization on `source()` that didn't reach
30229        // `edge_pair()`, a per-cluster alias rewrite the operator lands
30230        // on `destination()` without reaching this composite projection)
30231        // trips at caixa-core build time. Pins the "typed dispatch
30232        // composes with typed dispatch, not with raw field access"
30233        // discipline every downstream diagnostic-construction site now
30234        // routes through — a `de:` / `para:` label pair whose
30235        // projection silently drifted off the substrate primitive's
30236        // scalar accessors would silently split the diagnostic's self-
30237        // locating signal from the source `caixa.lisp` author's view.
30238        // Peer of the sibling per-`:politicas` `is_empty` /
30239        // `validate_politicas` accessor-routing-pin family on the M3
30240        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
30241        let c = WitContract {
30242            de: "cart".into(),
30243            para: "catalog".into(),
30244            wit: "wasi:http/proxy".into(),
30245            endpoint: Some("/lookup".into()),
30246            subject: None,
30247            slot: None,
30248        };
30249        assert_eq!(
30250            c.edge_pair(),
30251            (c.source().to_string(), c.destination().to_string()),
30252            "WitContract::edge_pair must compose exactly \
30253             (source().to_string(), destination().to_string()) — a \
30254             bypass of either sibling accessor here would silently \
30255             decouple the composite-projection axis from the \
30256             substrate-primitive scalar accessors every downstream \
30257             consumer routes through",
30258        );
30259    }
30260
30261    #[test]
30262    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
30263     {
30264        // The canonical per-`:contratos` owned-form
30265        // caller-callee-world-ref-triple pin:
30266        // [`WitContract::edge_triple`] must return the
30267        // `(source(), destination(), world_ref())` tuple in owned form
30268        // byte-for-byte, projected through the lifted
30269        // [`WitContract::source`] / [`WitContract::destination`] /
30270        // [`WitContract::world_ref`] scalar accessors. Pins the
30271        // composite-projection invariant on the per-`:contratos`
30272        // mesh-slot atom — every author-declared `(de, para, wit)`
30273        // triple must round-trip verbatim through the substrate
30274        // primitive's typed dispatch, so the nine
30275        // [`AplicacaoError`] diagnostic-construction sites the
30276        // accessor now feeds (the [`WitTarget`]-dispatch's eight
30277        // wrong-target / missing-target / invalid-wit / capability-
30278        // with-payload arms in [`WitContract::target`], plus the
30279        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
30280        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
30281        // read the same `(de, para, wit)` triple every author sees at
30282        // the source `caixa.lisp`. Pins against a future silent
30283        // detour that swapped any two arms (an accidental `(destination(),
30284        // source(), world_ref())` re-order in the body would silently
30285        // invert every downstream diagnostic's `de:` / `para:` label
30286        // pair, silently reversing the direction of every operator-
30287        // facing typed error arrow), a fresh-allocation shape drift
30288        // (an accidental `.to_string()` skipped on one arm would leave
30289        // the owned/borrowed triple mismatched vs. the sibling
30290        // `source()` / `destination()` / `world_ref()` returns), or an
30291        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
30292        // canonicalization pass that landed on one accessor without
30293        // reaching the peers. Peer of the sibling per-`:contratos`
30294        // caller-callee-pair
30295        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
30296        // pin on the mesh-slot-atom composite-projection axis,
30297        // extended to the triple-projection axis.
30298        for (de, para, wit, endpoint, subject, slot) in [
30299            (
30300                "cart",
30301                "catalog",
30302                "wasi:http/proxy",
30303                Some("/lookup"),
30304                None,
30305                None,
30306            ),
30307            (
30308                "checkout",
30309                "orders",
30310                "nats:pub-sub",
30311                None,
30312                Some("orders.paid"),
30313                None,
30314            ),
30315            (
30316                "cart",
30317                "kv",
30318                "wasi:keyvalue/store",
30319                None,
30320                None,
30321                Some("carts/{cart_id}"),
30322            ),
30323            (
30324                "orders-v2",
30325                "inventory-v3",
30326                "http:proxy",
30327                Some("/reserve"),
30328                None,
30329                None,
30330            ),
30331        ] {
30332            let c = WitContract {
30333                de: de.into(),
30334                para: para.into(),
30335                wit: wit.into(),
30336                endpoint: endpoint.map(str::to_string),
30337                subject: subject.map(str::to_string),
30338                slot: slot.map(str::to_string),
30339            };
30340            assert_eq!(
30341                c.edge_triple(),
30342                (de.to_string(), para.to_string(), wit.to_string()),
30343                "WitContract::edge_triple must return (:contratos :de, \
30344                 :contratos :para, :contratos :wit) as an owned triple \
30345                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
30346                c.edge_triple(),
30347            );
30348        }
30349    }
30350
30351    #[test]
30352    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
30353        // The composition pin: [`WitContract::edge_triple`] must return
30354        // exactly `(source().to_string(), destination().to_string(),
30355        // world_ref().to_string())` — the owned form of the sibling
30356        // scalar-accessor triple — so any future refactor that silently
30357        // re-authored one arm's projection to bypass the lifted scalar
30358        // accessors (an accidental `(self.de.clone(), self.para.clone(),
30359        // self.wit.clone())` regression back to the raw field-access
30360        // shape the internal `edge` closure and the ContratoDuplicate
30361        // diagnostic both carried before this lift landed, an
30362        // M4-typed-caller-enum `Display` re-canonicalization on
30363        // `source()` that didn't reach `edge_triple()`, a per-cluster
30364        // alias rewrite the operator lands on `destination()` /
30365        // `world_ref()` without reaching this composite projection)
30366        // trips at caixa-core build time. Pins the "typed dispatch
30367        // composes with typed dispatch, not with raw field access"
30368        // discipline every downstream diagnostic-construction site now
30369        // routes through — a `de:` / `para:` / `wit:` triple whose
30370        // projection silently drifted off the substrate primitive's
30371        // scalar accessors would silently split the diagnostic's self-
30372        // locating signal from the source `caixa.lisp` author's view.
30373        // Peer of the sibling per-`:contratos` edge_pair composition-
30374        // pin above on the mesh-slot-atom composite-projection axis.
30375        let c = WitContract {
30376            de: "cart".into(),
30377            para: "catalog".into(),
30378            wit: "wasi:http/proxy".into(),
30379            endpoint: Some("/lookup".into()),
30380            subject: None,
30381            slot: None,
30382        };
30383        assert_eq!(
30384            c.edge_triple(),
30385            (
30386                c.source().to_string(),
30387                c.destination().to_string(),
30388                c.world_ref().to_string(),
30389            ),
30390            "WitContract::edge_triple must compose exactly \
30391             (source().to_string(), destination().to_string(), \
30392             world_ref().to_string()) — a bypass of any sibling accessor \
30393             here would silently decouple the composite-projection axis \
30394             from the substrate-primitive scalar accessors every \
30395             downstream consumer routes through",
30396        );
30397    }
30398
30399    #[test]
30400    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
30401        // The canonical semantics-pin: [`WitContract::edge_triple`] must
30402        // project the full `(de, para, wit)` identity of a `:contratos`
30403        // edge — the sub-triple every triple-carrying
30404        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
30405        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
30406        // missing-target, capability-with-payload, invalid-wit, and the
30407        // duplicate-gate). Rejects a drift in shape (an accidental
30408        // silent detour that returned a `(de, para)` pair or added an
30409        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
30410        // would trip here because the return type would no longer
30411        // pattern-match the eight `let (de, para, wit) = edge();`
30412        // destructures the [`WitContract::target`] dispatch feeds off
30413        // + the paired duplicate-gate `let (de, para, wit) =
30414        // c.edge_triple();` destructure in
30415        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
30416        // `:contratos` caller-callee-pair pin above extended to the
30417        // triple projection surface: closes the "one composite
30418        // accessor per typed diagnostic-construction sub-tuple"
30419        // discipline on the per-`:contratos` mesh-slot-atom axis.
30420        let c = WitContract {
30421            de: "checkout".into(),
30422            para: "orders".into(),
30423            wit: "nats:pub-sub".into(),
30424            endpoint: None,
30425            subject: Some("orders.paid".into()),
30426            slot: None,
30427        };
30428        let (de, para, wit) = c.edge_triple();
30429        assert_eq!(de, "checkout");
30430        assert_eq!(para, "orders");
30431        assert_eq!(wit, "nats:pub-sub");
30432    }
30433
30434    #[test]
30435    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
30436     {
30437        // The composition pin: [`WitContract::identity`] must return
30438        // exactly `(source(), destination(), world_ref(), endpoint(),
30439        // subject(), slot())` — the borrowed form of the six-scalar-
30440        // accessor identity axis. Any future refactor that silently
30441        // re-authored one arm's projection to bypass a scalar accessor
30442        // (a `self.de.as_str()` regression back to raw field access on
30443        // any of the three required arms, a `self.endpoint.as_deref()`
30444        // regression on any of the three optional arms, an M4 per-
30445        // cluster caller/callee-alias rewrite the operator lands on
30446        // `source()` / `destination()` without reaching this composite
30447        // projection) trips at caixa-core build time. Sweeps four
30448        // permutations of the WIT-shape × payload lattice — HTTP with
30449        // endpoint, pub-sub with subject, store with slot, payload-less
30450        // capability — so every payload arm is exercised. Peer of the
30451        // sibling per-`:contratos`
30452        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
30453        // composition pin on the mesh-slot-atom composite-projection
30454        // axis; extends the discipline from the (de, para, wit) prefix
30455        // onto the full-identity axis carrying the three payload arms.
30456        for (de, para, wit, endpoint, subject, slot) in [
30457            (
30458                "cart",
30459                "catalog",
30460                "wasi:http/proxy",
30461                Some("/lookup"),
30462                None,
30463                None,
30464            ),
30465            (
30466                "checkout",
30467                "orders",
30468                "nats:pub-sub",
30469                None,
30470                Some("orders.paid"),
30471                None,
30472            ),
30473            (
30474                "cart",
30475                "kv",
30476                "wasi:keyvalue/store",
30477                None,
30478                None,
30479                Some("carts/{cart_id}"),
30480            ),
30481            ("audit", "sink", "wasi:logging", None, None, None),
30482        ] {
30483            let c = WitContract {
30484                de: de.into(),
30485                para: para.into(),
30486                wit: wit.into(),
30487                endpoint: endpoint.map(str::to_owned),
30488                subject: subject.map(str::to_owned),
30489                slot: slot.map(str::to_owned),
30490            };
30491            assert_eq!(
30492                c.identity(),
30493                (
30494                    c.source(),
30495                    c.destination(),
30496                    c.world_ref(),
30497                    c.endpoint(),
30498                    c.subject(),
30499                    c.slot(),
30500                ),
30501                "WitContract::identity must compose exactly \
30502                 (source(), destination(), world_ref(), endpoint(), \
30503                 subject(), slot()) — a bypass of any sibling accessor \
30504                 here would silently decouple the identity-projection \
30505                 axis from the substrate-primitive scalar accessors \
30506                 every dedup-key consumer routes through",
30507            );
30508        }
30509    }
30510
30511    #[test]
30512    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
30513        // The canonical semantics-pin: [`WitContract::identity`] must
30514        // project the six-axis (de, para, wit, endpoint, subject, slot)
30515        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
30516        // gate keys off — two `WitContract`s that agree on all six axes
30517        // are the same typed edge declared twice, the graph-edge
30518        // analogue of duplicate `:membros` / `:placement :clusters` /
30519        // `:entrada :paths` entries. Rejects a shape drift (an
30520        // accidental silent detour that returned a prefix tuple or
30521        // added an extra field) by pattern-matching the six-arm shape.
30522        // Peer of the sibling per-`:contratos`
30523        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
30524        // pin extended from the (de, para, wit) prefix onto the full
30525        // six-axis identity that the dedup key rides.
30526        let c = WitContract {
30527            de: "cart".into(),
30528            para: "catalog".into(),
30529            wit: "wasi:http/proxy".into(),
30530            endpoint: Some("/products/:id".into()),
30531            subject: None,
30532            slot: None,
30533        };
30534        let (de, para, wit, endpoint, subject, slot) = c.identity();
30535        assert_eq!(de, "cart");
30536        assert_eq!(para, "catalog");
30537        assert_eq!(wit, "wasi:http/proxy");
30538        assert_eq!(endpoint, Some("/products/:id"));
30539        assert_eq!(subject, None);
30540        assert_eq!(slot, None);
30541
30542        // Two byte-identical contracts must produce equal identities —
30543        // the dedup key's foundational invariant.
30544        let c2 = c.clone();
30545        assert_eq!(c.identity(), c2.identity());
30546
30547        // Any change on any of the six axes must break the identity —
30548        // sweeps by mutating one axis at a time.
30549        let mut mutated = c.clone();
30550        mutated.de = "search".into();
30551        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
30552        let mut mutated = c.clone();
30553        mutated.para = "warehouse".into();
30554        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
30555        let mut mutated = c.clone();
30556        mutated.wit = "http:legacy".into();
30557        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
30558        let mut mutated = c.clone();
30559        mutated.endpoint = Some("/search".into());
30560        assert_ne!(
30561            c.identity(),
30562            mutated.identity(),
30563            "endpoint axis must partition"
30564        );
30565        let mut mutated = c.clone();
30566        mutated.subject = Some("orders.paid".into());
30567        assert_ne!(
30568            c.identity(),
30569            mutated.identity(),
30570            "subject axis must partition"
30571        );
30572        let mut mutated = c;
30573        mutated.slot = Some("carts/{id}".into());
30574        assert_ne!(mutated.identity().5, None, "slot axis must partition");
30575    }
30576
30577    #[test]
30578    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
30579        // The canonical per-`:contratos` structural-self-edge pin:
30580        // [`WitContract::is_self_loop`] must return `true` when the
30581        // `:de` and `:para` fields agree byte-for-byte, across every
30582        // WIT-shape variant the per-edge shape family carries. Pins
30583        // the shape-agnostic identity-space partition the
30584        // [`AplicacaoSpec::validate`] self-edge gate at
30585        // caixa-core/src/aplicacao.rs:5559 fires against — all four
30586        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
30587        // under the same one predicate. Four permutations sweep the
30588        // accept-set: HTTP with endpoint, pub-sub with subject, KV
30589        // store with slot, and payload-less capability.
30590        for (nome, wit, endpoint, subject, slot) in [
30591            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
30592            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
30593            (
30594                "kv",
30595                "wasi:keyvalue/store",
30596                None,
30597                None,
30598                Some("carts/{cart_id}"),
30599            ),
30600            ("audit", "wasi:logging", None, None, None),
30601        ] {
30602            let c = WitContract {
30603                de: nome.into(),
30604                para: nome.into(),
30605                wit: wit.into(),
30606                endpoint: endpoint.map(str::to_string),
30607                subject: subject.map(str::to_string),
30608                slot: slot.map(str::to_string),
30609            };
30610            assert!(
30611                c.is_self_loop(),
30612                "WitContract::is_self_loop must return true when \
30613                 :contratos :de == :contratos :para (got false on \
30614                 {nome:?} under {wit:?})",
30615            );
30616        }
30617    }
30618
30619    #[test]
30620    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
30621        // The complement pin: [`WitContract::is_self_loop`] must return
30622        // `false` on every well-shaped inter-Servico contract (the
30623        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
30624        // names — "Servico A calls Servico B" between two distinct
30625        // graph nodes). Pins against a future silent detour that
30626        // inverted the predicate (an accidental `!= ` swap for `==`
30627        // would silently reject every legitimate inter-Servico edge
30628        // and admit every self-edge — the exact inversion of the
30629        // author-intended shape). Four permutations sweep the same
30630        // WIT-shape accept-set the sibling positive-arm test carries.
30631        for (de, para, wit, endpoint, subject, slot) in [
30632            (
30633                "cart",
30634                "catalog",
30635                "wasi:http/proxy",
30636                Some("/lookup"),
30637                None,
30638                None,
30639            ),
30640            (
30641                "checkout",
30642                "orders",
30643                "nats:pub-sub",
30644                None,
30645                Some("orders.paid"),
30646                None,
30647            ),
30648            (
30649                "cart",
30650                "kv",
30651                "wasi:keyvalue/store",
30652                None,
30653                None,
30654                Some("carts/{cart_id}"),
30655            ),
30656            ("audit", "sink", "wasi:logging", None, None, None),
30657        ] {
30658            let c = WitContract {
30659                de: de.into(),
30660                para: para.into(),
30661                wit: wit.into(),
30662                endpoint: endpoint.map(str::to_string),
30663                subject: subject.map(str::to_string),
30664                slot: slot.map(str::to_string),
30665            };
30666            assert!(
30667                !c.is_self_loop(),
30668                "WitContract::is_self_loop must return false when \
30669                 :contratos :de differs from :contratos :para (got true \
30670                 on {de:?} → {para:?} under {wit:?})",
30671            );
30672        }
30673    }
30674
30675    #[test]
30676    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
30677        // The composition pin: [`WitContract::is_self_loop`] must
30678        // resolve to exactly `self.source() == self.destination()` —
30679        // the equality probe of the sibling scalar-accessor pair — so
30680        // any future refactor that silently re-authored the predicate
30681        // to bypass the lifted scalar accessors (an accidental
30682        // `self.de == self.para` regression back to the raw field-
30683        // access shape, an M4-typed-caller-enum identity-comparison
30684        // rule that landed on `source()` without reaching
30685        // `destination()`, a per-cluster alias rewrite the operator
30686        // pins on `destination()` without reaching this predicate)
30687        // trips at caixa-core build time. Pins the "typed dispatch
30688        // composes with typed dispatch, not with raw field access"
30689        // discipline the sibling [`WitContract::edge_pair`] /
30690        // [`WitContract::edge_triple`] composite-projection accessors
30691        // already carry, extended onto the per-edge endpoint-equality
30692        // predicate axis. Positive and complement arms both fire.
30693        let self_edge = WitContract {
30694            de: "cart".into(),
30695            para: "cart".into(),
30696            wit: "wasi:http/proxy".into(),
30697            endpoint: Some("/lookup".into()),
30698            subject: None,
30699            slot: None,
30700        };
30701        assert_eq!(
30702            self_edge.is_self_loop(),
30703            self_edge.source() == self_edge.destination(),
30704            "WitContract::is_self_loop must compose exactly \
30705             `source() == destination()` — a bypass of either sibling \
30706             accessor here would silently decouple the endpoint-\
30707             equality predicate from the substrate-primitive scalar \
30708             accessors every downstream consumer routes through",
30709        );
30710        let inter_edge = WitContract {
30711            de: "cart".into(),
30712            para: "catalog".into(),
30713            wit: "wasi:http/proxy".into(),
30714            endpoint: Some("/lookup".into()),
30715            subject: None,
30716            slot: None,
30717        };
30718        assert_eq!(
30719            inter_edge.is_self_loop(),
30720            inter_edge.source() == inter_edge.destination(),
30721            "WitContract::is_self_loop must compose exactly \
30722             `source() == destination()` on the complement arm too",
30723        );
30724    }
30725
30726    #[test]
30727    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
30728        // The composition pin: [`WitContract::target`]'s invalid-wit
30729        // value-shape gate must feed the reason string through the
30730        // lifted [`WitContract::world_ref`] scalar accessor — the same
30731        // typed dispatch on the substrate primitive every peer
30732        // per-`:contratos` payload-carrier extraction in the same
30733        // method body already routes through
30734        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
30735        // [`WitContract::subject`] on the pub-sub-arm target extraction,
30736        // [`WitContract::slot`] on the store-arm target extraction) and
30737        // every peer composite-projection accessor
30738        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
30739        // [`WitContract::identity`]) already composes from. Any future
30740        // refactor that silently re-authored the gate to bypass the
30741        // lifted accessor (an accidental `&self.wit` regression back to
30742        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
30743        // re-canonicalization on `world_ref()` that didn't reach this
30744        // gate, a per-CR lowercasing canonicalization pass the M4
30745        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
30746        // per-tenant that lands on `world_ref()` without reaching this
30747        // gate) would silently split the invalid-wit diagnostic reason
30748        // from the substrate-primitive projection every downstream
30749        // consumer routes through. Same "typed dispatch composes with
30750        // typed dispatch, not with raw field access" discipline the
30751        // sibling
30752        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
30753        // pin already carries on the endpoint-equality predicate axis,
30754        // extended onto the invalid-wit value-shape gate axis inside
30755        // the same [`WitContract::target`] body. Closes the last
30756        // unlifted raw-field-access site inside `impl WitContract`.
30757        //
30758        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
30759        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
30760        // to a capability-only edge; the value-shape gate rejects it
30761        // through [`crate::render::is_wit_world_ref`] on the substrate
30762        // primitive's ASCII-lowercase-only accept-set, with a
30763        // parser-shaped reason string the test asserts round-trips
30764        // byte-for-byte between the direct-dispatch call (through the
30765        // predicate on the accessor's projection) and the
30766        // [`WitContract::target`] gate's produced reason field.
30767        let c = WitContract {
30768            de: "cart".into(),
30769            para: "catalog".into(),
30770            wit: "WASI:HTTP/proxy".into(),
30771            endpoint: Some("/lookup".into()),
30772            subject: None,
30773            slot: None,
30774        };
30775        let err = c.target().unwrap_err();
30776        let AplicacaoError::ContratoWitInvalid {
30777            ref de,
30778            ref para,
30779            ref wit,
30780            ref reason,
30781        } = err
30782        else {
30783            panic!("expected ContratoWitInvalid, got {err:?}");
30784        };
30785        assert_eq!(de, "cart");
30786        assert_eq!(para, "catalog");
30787        assert_eq!(wit, "WASI:HTTP/proxy");
30788        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
30789        assert_eq!(
30790            *reason, expected_reason,
30791            "WitContract::target's invalid-wit value-shape gate reason \
30792             must compose exactly is_wit_world_ref(self.world_ref()) — \
30793             a bypass here (e.g. a raw `&self.wit` field-access \
30794             regression, or a divergent predicate on a different \
30795             projection) would silently decouple the invalid-wit \
30796             diagnostic's reason field from the substrate-primitive \
30797             scalar accessor every peer per-`:contratos` extraction in \
30798             the same method body already routes through",
30799        );
30800    }
30801
30802    #[test]
30803    fn wit_contract_is_self_loop_predicate_is_const_fn() {
30804        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
30805        // caller-callee identity-space predicate's `const`-eval-surface
30806        // posture. The wrapper below dispatches through
30807        // [`WitContract::is_self_loop`] and is well-formed only when the
30808        // callee is itself `pub const fn` — any future accidental
30809        // downgrade to non-`const` fails the wrapper at caixa-core build
30810        // time with E0015 (`cannot call non-const method`), strictly
30811        // stronger than a runtime `assert!` and strictly stronger than a
30812        // module-scope `const _: () = assert!(…)` pin (the type's
30813        // `String` / `Option<String>` carriers rule out `const`-context
30814        // value construction; the `const fn` wrapper is the load-bearing
30815        // shape that side-steps the destructor-in-const restriction on
30816        // the value axis while still pinning the `const`-fn posture on
30817        // the callee — mirror of the sibling
30818        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
30819        // (279823b) and
30820        // [`wit_contract_identity_projection_accessor_is_const_fn`]
30821        // (1ab648c) pins' discipline verbatim on the peer scalar-
30822        // accessor and composite-projection surfaces). Closes the last
30823        // unlifted per-`:contratos` shape/identity predicate on the
30824        // const-eval surface — the peer WIT-shape-partition family
30825        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
30826        // [`WitContract::is_store`] / [`WitContract::is_capability`]
30827        // already carried the `pub const fn` posture on the peer
30828        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
30829        // this pin extends the same posture onto the caller-callee
30830        // identity-space partition. Sweeps every WIT-shape arm on both
30831        // the equal-endpoints (self-edge) and distinct-endpoints
30832        // (inter-edge) arms of the identity-space partition, plus one
30833        // same-length distinct-byte pair to pin the mid-loop `!=` arm
30834        // past the leading length-mismatch shortcut.
30835        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
30836            c.is_self_loop()
30837        }
30838        let mk = |de: &str, para: &str, wit: &str| WitContract {
30839            de: de.into(),
30840            para: para.into(),
30841            wit: wit.into(),
30842            endpoint: None,
30843            subject: None,
30844            slot: None,
30845        };
30846        for (nome, wit) in [
30847            ("cart", "wasi:http/proxy"),
30848            ("checkout", "nats:pub-sub"),
30849            ("kv", "wasi:keyvalue/store"),
30850            ("audit", "wasi:logging"),
30851        ] {
30852            let self_edge = mk(nome, nome, wit);
30853            assert!(
30854                is_self_loop_via_const_fn(&self_edge),
30855                "self-edge {nome:?} under {wit:?}"
30856            );
30857            assert_eq!(
30858                is_self_loop_via_const_fn(&self_edge),
30859                self_edge.is_self_loop()
30860            );
30861        }
30862        for (de, para, wit) in [
30863            ("cart", "catalog", "wasi:http/proxy"),
30864            ("checkout", "orders", "nats:pub-sub"),
30865            ("cart", "kv", "wasi:keyvalue/store"),
30866            ("audit", "sink", "wasi:logging"),
30867        ] {
30868            let inter_edge = mk(de, para, wit);
30869            assert!(
30870                !is_self_loop_via_const_fn(&inter_edge),
30871                "inter-edge {de:?}→{para:?} under {wit:?}",
30872            );
30873            assert_eq!(
30874                is_self_loop_via_const_fn(&inter_edge),
30875                inter_edge.is_self_loop()
30876            );
30877        }
30878        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
30879        // past the leading `a.len() != b.len()` shortcut so the const-fn
30880        // wrapper exercises every arm of the byte-slice equality loop.
30881        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
30882        assert!(
30883            !is_self_loop_via_const_fn(&same_len_pair),
30884            "same-length distinct-byte"
30885        );
30886        assert_eq!(
30887            is_self_loop_via_const_fn(&same_len_pair),
30888            same_len_pair.is_self_loop()
30889        );
30890    }
30891
30892    #[test]
30893    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
30894        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
30895        // pin: [`WitContract::endpoint`] must return the `:contratos
30896        // :endpoint` field byte-for-byte, borrowed from the typed slot's
30897        // own `Option<String>` storage. Peer of the sibling
30898        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
30899        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
30900        // mesh-slot `Option<String>` optional-scalar axes — same "the
30901        // substrate-primitive accessor must byte-equal the raw field
30902        // access verbatim across every author-declared value" discipline
30903        // extended to the per-`:contratos` HTTP-payload-carrier arm.
30904        // Pins against a future silent detour that re-canonicalized the
30905        // endpoint (an accidental percent-encoding pass that didn't
30906        // reach the peer field-access site at the dedup key, a per-CR
30907        // fully-qualified prefix rewrite the operator authors on one
30908        // consumer without the other, or an M4 typed-path-template
30909        // `Display` re-canonicalization that silently drifted the
30910        // printer output from the source `caixa.lisp`). Four values
30911        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
30912        // gate upstream admits (short root-path, dashed, param-shaped,
30913        // deep-hierarchy).
30914        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
30915            let c = WitContract {
30916                de: "cart".into(),
30917                para: "catalog".into(),
30918                wit: "wasi:http/proxy".into(),
30919                endpoint: Some(endpoint.into()),
30920                subject: None,
30921                slot: None,
30922            };
30923            assert_eq!(
30924                c.endpoint(),
30925                Some(endpoint),
30926                "WitContract::endpoint must return :contratos :endpoint \
30927                 verbatim (got {:?}, expected Some({endpoint:?}))",
30928                c.endpoint(),
30929            );
30930            assert_eq!(
30931                c.endpoint(),
30932                c.endpoint.as_deref(),
30933                "WitContract::endpoint must byte-equal the .endpoint \
30934                 field's `.as_deref()` projection",
30935            );
30936        }
30937    }
30938
30939    #[test]
30940    fn wit_contract_endpoint_none_when_field_is_none() {
30941        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
30942        // payload-carrier accessor pin: when the typed slot is absent —
30943        // the canonical shape under a non-HTTP `:wit` world per the
30944        // [`WitContract::target`]-enforced shape ↔ target partition
30945        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
30946        // carries `:slot`, [`WitTarget::Capability`] carries none) —
30947        // [`WitContract::endpoint`] must return `None`. Pins against a
30948        // future silent detour that projected the absent slot to a
30949        // `Some("")` empty-string default (the canonical `Option<String>`
30950        // → `String` collapse footgun the sibling M2
30951        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
30952        // emptiness predicates already guard on the peer M2 typed-slot
30953        // surfaces), a `Some("None")` stringified-None round-trip, or a
30954        // `Some` arm whose contents were derived from a sibling slot (an
30955        // accidental fallback to the `:subject` / `:slot` payload that
30956        // read the pub-sub / store payload into the endpoint axis).
30957        // Three contracts sweep the accept-set every non-HTTP `:wit`
30958        // world lands on — pub-sub NATS, key/value, and payload-less
30959        // capability.
30960        for (wit, subject, slot) in [
30961            ("nats:pub-sub", Some("orders.paid"), None),
30962            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
30963            ("wasi:cli/environment", None, None),
30964        ] {
30965            let c = WitContract {
30966                de: "cart".into(),
30967                para: "downstream".into(),
30968                wit: wit.into(),
30969                endpoint: None,
30970                subject: subject.map(str::to_string),
30971                slot: slot.map(str::to_string),
30972            };
30973            assert!(
30974                c.endpoint().is_none(),
30975                "WitContract::endpoint must return None when the typed \
30976                 slot is absent under :wit {wit:?} (got {:?})",
30977                c.endpoint(),
30978            );
30979            assert_eq!(
30980                c.endpoint(),
30981                c.endpoint.as_deref(),
30982                "WitContract::endpoint must byte-equal the .endpoint \
30983                 field's `.as_deref()` projection in the absent arm",
30984            );
30985        }
30986    }
30987
30988    #[test]
30989    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
30990        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
30991        // an `Option<&str>` whose `Some` arm borrows from the typed
30992        // slot's own [`String`] storage — same-address invariant with
30993        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
30994        // detour that allocated a fresh `String`
30995        // (`self.endpoint.clone().map(...)` in the body would type-check
30996        // but silently drop the borrow, and every downstream consumer
30997        // that assumed the returned slice outlives `&self` would break
30998        // on a stale-reference use-after-free — the [`WitContract::target`]
30999        // Http-arm payload extraction rebinds the returned `Option<&str>`
31000        // through `.ok_or_else(...)` and threads the `&str` payload into
31001        // [`WitTarget::Http { endpoint: &'a str }`], the
31002        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
31003        // [`ContratoIdentity`] dedup key threads the returned
31004        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
31005        // from the WitContract's own storage and each would silently
31006        // misbehave if this accessor produced a detached copy). Peer of
31007        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
31008        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
31009        // shaped optional-scalar axes — first extension of the
31010        // `Option<&str>` borrow-not-copy discipline onto the
31011        // per-`:contratos` HTTP-shaped payload-carrier axis.
31012        let c = WitContract {
31013            de: "cart".into(),
31014            para: "catalog".into(),
31015            wit: "wasi:http/proxy".into(),
31016            endpoint: Some("/lookup".into()),
31017            subject: None,
31018            slot: None,
31019        };
31020        let ep = c.endpoint().expect("Some arm");
31021        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
31022        assert_eq!(
31023            ep.as_ptr(),
31024            storage_slice.as_ptr(),
31025            "WitContract::endpoint must borrow from the .endpoint \
31026             String's backing storage — a fresh allocation here means \
31027             the accessor no longer names the substrate-primitive typed \
31028             dispatch and every downstream consumer would silently \
31029             carry a detached copy",
31030        );
31031        assert_eq!(
31032            ep.len(),
31033            storage_slice.len(),
31034            "WitContract::endpoint and .endpoint.as_deref() must byte-\
31035             equal in length as well as in address",
31036        );
31037    }
31038
31039    #[test]
31040    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
31041        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
31042        // pin: [`WitContract::subject`] must return the `:contratos
31043        // :subject` field byte-for-byte, borrowed from the typed slot's
31044        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
31045        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
31046        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
31047        // optional-scalar axis — same "the substrate-primitive accessor
31048        // must byte-equal the raw field access verbatim across every
31049        // author-declared value" discipline extended to the pub-sub arm.
31050        // Pins against a future silent detour that re-canonicalized the
31051        // subject (an accidental `.to_lowercase()` normalization that
31052        // didn't reach the peer field-access site at the dedup key, a
31053        // per-CR fully-qualified prefix rewrite the operator authors on
31054        // one consumer without the other, or an M4 typed-subject-template
31055        // `Display` re-canonicalization that silently drifted the printer
31056        // output from the source `caixa.lisp`). Four values sweep the
31057        // NATS accept-set every pub-sub author-declared subject lands on
31058        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
31059        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
31060            let c = WitContract {
31061                de: "cart".into(),
31062                para: "notifier".into(),
31063                wit: "nats:pub-sub".into(),
31064                endpoint: None,
31065                subject: Some(subject.into()),
31066                slot: None,
31067            };
31068            assert_eq!(
31069                c.subject(),
31070                Some(subject),
31071                "WitContract::subject must return :contratos :subject \
31072                 verbatim (got {:?}, expected Some({subject:?}))",
31073                c.subject(),
31074            );
31075            assert_eq!(
31076                c.subject(),
31077                c.subject.as_deref(),
31078                "WitContract::subject must byte-equal the .subject \
31079                 field's `.as_deref()` projection",
31080            );
31081        }
31082    }
31083
31084    #[test]
31085    fn wit_contract_subject_none_when_field_is_none() {
31086        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
31087        // shaped payload-carrier accessor pin: when the typed slot is
31088        // absent — the canonical shape under a non-pub-sub `:wit` world
31089        // per the [`WitContract::target`]-enforced shape ↔ target
31090        // partition ([`WitTarget::Http`] carries `:endpoint`,
31091        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
31092        // carries none) — [`WitContract::subject`] must return `None`.
31093        // Pins against a future silent detour that projected the absent
31094        // slot to a `Some("")` empty-string default (the canonical
31095        // `Option<String>` → `String` collapse footgun the sibling M2
31096        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
31097        // emptiness predicates already guard on the peer M2 typed-slot
31098        // surfaces), a `Some("None")` stringified-None round-trip, or a
31099        // `Some` arm whose contents were derived from a sibling slot (an
31100        // accidental fallback to the `:endpoint` / `:slot` payload that
31101        // read the HTTP / store payload into the subject axis). Three
31102        // contracts sweep the accept-set every non-pub-sub `:wit` world
31103        // lands on — HTTP proxy, key/value store, and payload-less
31104        // capability.
31105        for (wit, endpoint, slot) in [
31106            ("wasi:http/proxy", Some("/lookup"), None),
31107            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
31108            ("wasi:cli/environment", None, None),
31109        ] {
31110            let c = WitContract {
31111                de: "cart".into(),
31112                para: "downstream".into(),
31113                wit: wit.into(),
31114                endpoint: endpoint.map(str::to_string),
31115                subject: None,
31116                slot: slot.map(str::to_string),
31117            };
31118            assert!(
31119                c.subject().is_none(),
31120                "WitContract::subject must return None when the typed \
31121                 slot is absent under :wit {wit:?} (got {:?})",
31122                c.subject(),
31123            );
31124            assert_eq!(
31125                c.subject(),
31126                c.subject.as_deref(),
31127                "WitContract::subject must byte-equal the .subject \
31128                 field's `.as_deref()` projection in the absent arm",
31129            );
31130        }
31131    }
31132
31133    #[test]
31134    fn wit_contract_subject_borrows_from_subject_storage() {
31135        // The borrow-not-copy pin: [`WitContract::subject`] must return
31136        // an `Option<&str>` whose `Some` arm borrows from the typed
31137        // slot's own [`String`] storage — same-address invariant with
31138        // `c.subject.as_deref().unwrap()`. Pins against a future silent
31139        // detour that allocated a fresh `String`
31140        // (`self.subject.clone().map(...)` in the body would type-check
31141        // but silently drop the borrow, and every downstream consumer
31142        // that assumed the returned slice outlives `&self` would break
31143        // on a stale-reference use-after-free — the [`WitContract::target`]
31144        // PubSub-arm payload extraction rebinds the returned
31145        // `Option<&str>` through `.ok_or_else(...)` and threads the
31146        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
31147        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
31148        // [`ContratoIdentity`] dedup key threads the returned
31149        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
31150        // from the WitContract's own storage and each would silently
31151        // misbehave if this accessor produced a detached copy). Peer of
31152        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
31153        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
31154        // shaped optional-scalar axis — second extension of the
31155        // `Option<&str>` borrow-not-copy discipline onto the
31156        // per-`:contratos` payload-carrier family, this time on the
31157        // pub-sub arm.
31158        let c = WitContract {
31159            de: "cart".into(),
31160            para: "notifier".into(),
31161            wit: "nats:pub-sub".into(),
31162            endpoint: None,
31163            subject: Some("orders.paid".into()),
31164            slot: None,
31165        };
31166        let sub = c.subject().expect("Some arm");
31167        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
31168        assert_eq!(
31169            sub.as_ptr(),
31170            storage_slice.as_ptr(),
31171            "WitContract::subject must borrow from the .subject \
31172             String's backing storage — a fresh allocation here means \
31173             the accessor no longer names the substrate-primitive typed \
31174             dispatch and every downstream consumer would silently \
31175             carry a detached copy",
31176        );
31177        assert_eq!(
31178            sub.len(),
31179            storage_slice.len(),
31180            "WitContract::subject and .subject.as_deref() must byte-\
31181             equal in length as well as in address",
31182        );
31183    }
31184
31185    #[test]
31186    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
31187        // The canonical per-`:contratos` key/value-store-shaped
31188        // `:slot`-scalar pin: [`WitContract::slot`] must return the
31189        // `:contratos :slot` field byte-for-byte, borrowed from the
31190        // typed slot's own `Option<String>` storage. Peer of the
31191        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
31192        // [`WitContract::subject`] (90de675) accessor pins on the M3
31193        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
31194        // optional-scalar axis — same "the substrate-primitive
31195        // accessor must byte-equal the raw field access verbatim
31196        // across every author-declared value" discipline extended to
31197        // the store arm. Pins against a future silent detour that
31198        // re-canonicalized the slot template (an accidental
31199        // `.to_lowercase()` bucket-prefix normalization that didn't
31200        // reach the peer field-access site at the dedup key, a per-CR
31201        // fully-qualified prefix rewrite the operator authors on one
31202        // consumer without the other, or an M4 typed-key-template
31203        // `Display` re-canonicalization that silently drifted the
31204        // printer output from the source `caixa.lisp`). Four values
31205        // sweep the wasi:keyvalue accept-set every store-shaped
31206        // author-declared slot lands on (flat bucket, single-param
31207        // template, multi-param template, nested-hierarchy template).
31208        for slot in [
31209            "sessions",
31210            "carts/{cart_id}",
31211            "orders/{tenant}/{order_id}",
31212            "cache/tenant-a/orders/{id}",
31213        ] {
31214            let c = WitContract {
31215                de: "cart".into(),
31216                para: "kv".into(),
31217                wit: "wasi:keyvalue/store".into(),
31218                endpoint: None,
31219                subject: None,
31220                slot: Some(slot.into()),
31221            };
31222            assert_eq!(
31223                c.slot(),
31224                Some(slot),
31225                "WitContract::slot must return :contratos :slot \
31226                 verbatim (got {:?}, expected Some({slot:?}))",
31227                c.slot(),
31228            );
31229            assert_eq!(
31230                c.slot(),
31231                c.slot.as_deref(),
31232                "WitContract::slot must byte-equal the .slot field's \
31233                 `.as_deref()` projection",
31234            );
31235        }
31236    }
31237
31238    #[test]
31239    fn wit_contract_slot_none_when_field_is_none() {
31240        // The absent-`:slot` arm of the per-`:contratos` store-shaped
31241        // payload-carrier accessor pin: when the typed slot is absent —
31242        // the canonical shape under a non-store `:wit` world per the
31243        // [`WitContract::target`]-enforced shape ↔ target partition
31244        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
31245        // carries `:subject`, [`WitTarget::Capability`] carries none) —
31246        // [`WitContract::slot`] must return `None`. Pins against a
31247        // future silent detour that projected the absent slot to a
31248        // `Some("")` empty-string default (the canonical
31249        // `Option<String>` → `String` collapse footgun the sibling M2
31250        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
31251        // emptiness predicates already guard on the peer M2 typed-slot
31252        // surfaces), a `Some("None")` stringified-None round-trip, or
31253        // a `Some` arm whose contents were derived from a sibling
31254        // slot (an accidental fallback to the `:endpoint` / `:subject`
31255        // payload that read the HTTP / pub-sub payload into the store
31256        // axis). Three contracts sweep the accept-set every non-store
31257        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
31258        // payload-less capability.
31259        for (wit, endpoint, subject) in [
31260            ("wasi:http/proxy", Some("/lookup"), None),
31261            ("nats:pub-sub", None, Some("orders.paid")),
31262            ("wasi:cli/environment", None, None),
31263        ] {
31264            let c = WitContract {
31265                de: "cart".into(),
31266                para: "downstream".into(),
31267                wit: wit.into(),
31268                endpoint: endpoint.map(str::to_string),
31269                subject: subject.map(str::to_string),
31270                slot: None,
31271            };
31272            assert!(
31273                c.slot().is_none(),
31274                "WitContract::slot must return None when the typed \
31275                 slot is absent under :wit {wit:?} (got {:?})",
31276                c.slot(),
31277            );
31278            assert_eq!(
31279                c.slot(),
31280                c.slot.as_deref(),
31281                "WitContract::slot must byte-equal the .slot field's \
31282                 `.as_deref()` projection in the absent arm",
31283            );
31284        }
31285    }
31286
31287    #[test]
31288    fn wit_contract_slot_borrows_from_slot_storage() {
31289        // The borrow-not-copy pin: [`WitContract::slot`] must return
31290        // an `Option<&str>` whose `Some` arm borrows from the typed
31291        // slot's own [`String`] storage — same-address invariant with
31292        // `c.slot.as_deref().unwrap()`. Pins against a future silent
31293        // detour that allocated a fresh `String`
31294        // (`self.slot.clone().map(...)` in the body would type-check
31295        // but silently drop the borrow, and every downstream consumer
31296        // that assumed the returned slice outlives `&self` would
31297        // break on a stale-reference use-after-free — the
31298        // [`WitContract::target`] Store-arm payload extraction rebinds
31299        // the returned `Option<&str>` through `.ok_or_else(...)` and
31300        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
31301        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
31302        // [`ContratoIdentity`] dedup key threads the returned
31303        // `Option<&str>` into the six-tuple's store arm — each borrow
31304        // from the WitContract's own storage and each would silently
31305        // misbehave if this accessor produced a detached copy). Peer
31306        // of the sibling per-`:contratos` [`WitContract::endpoint`]
31307        // (7020470) / [`WitContract::subject`] (90de675)
31308        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
31309        // shaped optional-scalar axis — third and final extension of
31310        // the `Option<&str>` borrow-not-copy discipline onto the
31311        // per-`:contratos` payload-carrier family, this time on the
31312        // store arm.
31313        let c = WitContract {
31314            de: "cart".into(),
31315            para: "kv".into(),
31316            wit: "wasi:keyvalue/store".into(),
31317            endpoint: None,
31318            subject: None,
31319            slot: Some("carts/{cart_id}".into()),
31320        };
31321        let slot = c.slot().expect("Some arm");
31322        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
31323        assert_eq!(
31324            slot.as_ptr(),
31325            storage_slice.as_ptr(),
31326            "WitContract::slot must borrow from the .slot String's \
31327             backing storage — a fresh allocation here means the \
31328             accessor no longer names the substrate-primitive typed \
31329             dispatch and every downstream consumer would silently \
31330             carry a detached copy",
31331        );
31332        assert_eq!(
31333            slot.len(),
31334            storage_slice.len(),
31335            "WitContract::slot and .slot.as_deref() must byte-equal \
31336             in length as well as in address",
31337        );
31338    }
31339
31340    #[test]
31341    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
31342        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
31343        // [`Membro::nome`] must return the `:membros :caixa` field
31344        // byte-for-byte, borrowed from the typed slot's own [`String`]
31345        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
31346        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
31347        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
31348        // slot-atom scalar-value axes — same "the substrate-primitive
31349        // accessor must byte-equal the raw field access verbatim across
31350        // every author-declared value" discipline extended to the
31351        // per-`:membros` member-identity arm. Pins against a future
31352        // silent detour that re-normalized the member identity (an
31353        // accidental `.to_lowercase()` — every `:membros :caixa` is
31354        // validated as a DNS-1123 label upstream via
31355        // [`validate_membro_caixa`], so any re-normalization is
31356        // redundant + a drift surface between the validator and the
31357        // accessor), a namespace-prefix rewrite (an accidental
31358        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
31359        // rewrite that didn't land on the peer axes), or a per-cluster
31360        // alias stamp the operator authors on one consumer without the
31361        // other. Four values sweep the accept-set the DNS-1123 gate
31362        // upstream admits (short single-word / dashed / v-suffixed
31363        // member names).
31364        for name in ["cart", "checkout", "catalog", "orders-v2"] {
31365            let m = Membro {
31366                caixa: name.into(),
31367                versao: "^0.1".into(),
31368            };
31369            assert_eq!(
31370                m.nome(),
31371                name,
31372                "Membro::nome must return :membros :caixa verbatim \
31373                 (got {:?}, expected {name:?})",
31374                m.nome(),
31375            );
31376            assert_eq!(
31377                m.nome(),
31378                m.caixa.as_str(),
31379                "Membro::nome must byte-equal the .caixa field access",
31380            );
31381        }
31382    }
31383
31384    #[test]
31385    fn membro_nome_borrows_from_caixa_storage() {
31386        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
31387        // slice that borrows from the typed slot's own [`String`]
31388        // storage — same-address invariant with `m.caixa.as_str()`. Pins
31389        // against a future silent detour that allocated a fresh `String`
31390        // (`self.caixa.clone()` in the body would type-check but
31391        // silently drop the borrow, and every downstream consumer that
31392        // assumed the returned slice outlives `&self` would break on a
31393        // stale-reference use-after-free — the `HashSet<&str>` collector
31394        // at [`AplicacaoSpec::validate`]'s `names` seed, the
31395        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
31396        // [`AplicacaoSpec::detect_sync_cycles`], the
31397        // [`crate::render::insert_first_seen`] dedup key at
31398        // [`AplicacaoSpec::validate_membros`] — each borrow from the
31399        // Membro's own storage and each would silently misbehave if
31400        // this accessor produced a detached copy). Peer of the sibling
31401        // per-`:contratos` [`WitContract::source`] /
31402        // [`WitContract::destination`] and per-`:entrada`
31403        // [`Entrada::destination`] borrow-invariant pins on the mesh-
31404        // slot-atom scalar-value axes.
31405        let m = Membro {
31406            caixa: "checkout".into(),
31407            versao: "^0.1".into(),
31408        };
31409        let name = m.nome();
31410        let caixa_slice = m.caixa.as_str();
31411        assert_eq!(
31412            name.as_ptr(),
31413            caixa_slice.as_ptr(),
31414            "Membro::nome must borrow from the .caixa String's backing \
31415             storage — a fresh allocation here means the accessor no \
31416             longer names the substrate-primitive typed dispatch and \
31417             every downstream consumer would silently carry a detached \
31418             copy",
31419        );
31420        assert_eq!(
31421            name.len(),
31422            caixa_slice.len(),
31423            "Membro::nome and .caixa.as_str() must byte-equal in length \
31424             as well as in address",
31425        );
31426    }
31427
31428    #[test]
31429    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
31430        // The canonical per-`:membros` member-`:versao`-scalar pin:
31431        // [`Membro::versao_requirement`] must return the
31432        // `:membros :versao` field byte-for-byte, borrowed from the typed
31433        // slot's own [`String`] storage. Sibling of the peer
31434        // `membro_nome_returns_caixa_byte_equal_across_permutations`
31435        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
31436        // — same "the substrate-primitive accessor must byte-equal the
31437        // raw field access verbatim across every author-declared value"
31438        // discipline extended to the per-`:membros` member-`:versao`
31439        // requirement-string arm. Pins against a future silent detour
31440        // that re-canonicalized the requirement (an accidental
31441        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
31442        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
31443        // drifted the printer output away from the source `caixa.lisp`,
31444        // an accidental whitespace trim on `"^ 0.1"` that no consumer
31445        // ever produced from the field-access side, an accidental
31446        // per-cluster lacre-projected concrete-version rewrite that
31447        // didn't land on the peer field-access sites). Five values sweep
31448        // the accept-set the shared
31449        // [`crate::render::require_valid_versao_requirement`] gate
31450        // admits (caret / tilde / exact / wildcard / bare-major).
31451        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
31452            let m = Membro {
31453                caixa: "cart".into(),
31454                versao: req.into(),
31455            };
31456            assert_eq!(
31457                m.versao_requirement(),
31458                req,
31459                "Membro::versao_requirement must return :membros :versao \
31460                 verbatim (got {:?}, expected {req:?})",
31461                m.versao_requirement(),
31462            );
31463            assert_eq!(
31464                m.versao_requirement(),
31465                m.versao.as_str(),
31466                "Membro::versao_requirement must byte-equal the .versao \
31467                 field access",
31468            );
31469        }
31470    }
31471
31472    #[test]
31473    fn membro_versao_requirement_borrows_from_versao_storage() {
31474        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
31475        // return a `&str` slice that borrows from the typed slot's own
31476        // [`String`] storage — same-address invariant with
31477        // `m.versao.as_str()`. Pins against a future silent detour that
31478        // allocated a fresh `String` (`self.versao.clone()` in the body
31479        // would type-check but silently drop the borrow, and every
31480        // downstream consumer that assumed the returned slice outlives
31481        // `&self` would break on a stale-reference use-after-free). Peer
31482        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
31483        // per-`:contratos` [`WitContract::source`] /
31484        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
31485        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
31486        // the mesh-slot-atom scalar-value axes.
31487        let m = Membro {
31488            caixa: "checkout".into(),
31489            versao: "^0.1".into(),
31490        };
31491        let req = m.versao_requirement();
31492        let versao_slice = m.versao.as_str();
31493        assert_eq!(
31494            req.as_ptr(),
31495            versao_slice.as_ptr(),
31496            "Membro::versao_requirement must borrow from the .versao \
31497             String's backing storage — a fresh allocation here means \
31498             the accessor no longer names the substrate-primitive typed \
31499             dispatch and every downstream consumer would silently carry \
31500             a detached copy",
31501        );
31502        assert_eq!(
31503            req.len(),
31504            versao_slice.len(),
31505            "Membro::versao_requirement and .versao.as_str() must byte-\
31506             equal in length as well as in address",
31507        );
31508    }
31509
31510    #[test]
31511    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
31512        // Sibling-pair invariant pin composing both per-`:membros`
31513        // substrate-primitive typed dispatches — [`Membro::nome`]
31514        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
31515        // `(nome(), versao_requirement())` call shape every renderer
31516        // that fans on per-member identity + version pin keys off. The
31517        // invariant, evaluated per-member:
31518        //
31519        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
31520        //
31521        // Closes the last unlifted per-`:membros` scalar axis — every
31522        // downstream consumer that reads the pair now routes through
31523        // exactly two typed dispatches on the substrate primitive, not
31524        // one typed + one open-coded field access. A future refactor
31525        // that silently split either accessor's projection (an
31526        // accidental `nome()` namespace-prefix rewrite that didn't
31527        // reach the peer, an accidental `versao_requirement()` lacre-
31528        // projected concrete-version rewrite that didn't land on the
31529        // `nome()` peer) surfaces at caixa-core build time. Peer of the
31530        // sibling per-`:entrada` `(hostname(), destination())` and
31531        // per-`:contratos` `(source(), destination())` pair invariants
31532        // on the mesh-slot-atom scalar-value axes.
31533        for (caixa, versao) in [
31534            ("cart", "^0.1"),
31535            ("checkout", "~0.1.2"),
31536            ("catalog", "0.1.0"),
31537            ("orders-v2", "*"),
31538        ] {
31539            let m = Membro {
31540                caixa: caixa.into(),
31541                versao: versao.into(),
31542            };
31543            assert_eq!(
31544                (m.nome(), m.versao_requirement()),
31545                (m.caixa.as_str(), m.versao.as_str()),
31546                "(Membro::nome, Membro::versao_requirement) must project \
31547                 (.caixa, .versao) verbatim across every author-declared \
31548                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
31549                m.nome(),
31550                m.versao_requirement(),
31551            );
31552        }
31553    }
31554
31555    #[test]
31556    fn validate_membros_empty_gate_routes_through_nome_accessor() {
31557        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
31558        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
31559        // not the raw `.caixa` field access. Structurally: setting
31560        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
31561        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
31562        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
31563        // (i.e. the empty string) — so the emptiness predicate the
31564        // refusal arm reaches under is the accessor-projected value,
31565        // not a peer field that would silently drift under a future
31566        // accessor-side rewrite.
31567        //
31568        // Pins against a future silent detour that (a) re-derived the
31569        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
31570        // instead of `self.nome().is_empty()`, silently disagreeing with
31571        // every peer consumer (the `validate_membro_caixa(m.nome())`
31572        // per-slot helper — which now owns the emptiness arm outright —
31573        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
31574        // below, and the emit-side per-`programs[]` entry-`name:` at
31575        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
31576        // per-tenant alias arm the caller was unaware of, silently
31577        // rewriting an author-declared `:caixa "checkout"` to `""` —
31578        // the raw-field-access gate would fail-open while the
31579        // accessor-routed peer consumers would fail-closed, splitting
31580        // the diagnostic from the actual failure surface.
31581        //
31582        // Peer of the sibling
31583        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
31584        // (c0110f1) composition pin — same "the shape-gate predicate
31585        // must route through the substrate-primitive typed dispatch"
31586        // discipline extended onto the per-`:membros` empty-`:caixa`
31587        // refusal-arm axis. Closes the last unlifted `.caixa` production-
31588        // code read site on `Membro` — after this converge every
31589        // caixa-core `.caixa` field access outside the accessor's own
31590        // body is either a test-side field-setter (in-module tests
31591        // constructing invalid-shape inputs) or a doc-comment reference.
31592        let mut s = three_member_spec();
31593        s.membros[1].caixa = String::new();
31594        assert!(
31595            s.membros[1].nome().is_empty(),
31596            "Membro::nome must byte-equal the .caixa field access — an \
31597             accessor-side detour that no longer projects the raw field \
31598             would silently split this drift-detection test from the \
31599             validate() refusal arm",
31600        );
31601        assert_eq!(
31602            s.membros[1].nome(),
31603            s.membros[1].caixa.as_str(),
31604            "Membro::nome and .caixa.as_str() must byte-equal on an \
31605             empty-`:caixa` entry — the emptiness gate keys off the \
31606             accessor by construction",
31607        );
31608        assert_eq!(
31609            s.validate().unwrap_err(),
31610            AplicacaoError::MembroCaixaEmpty,
31611            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
31612             on an entry whose accessor-projected `nome()` is empty",
31613        );
31614    }
31615
31616    #[test]
31617    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
31618        // Convergence pin, paired with the deletion of the redundant
31619        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
31620        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
31621        // after the collapse, the `MembroCaixaEmpty` refusal on every
31622        // empty-`:caixa` per-member input is owned solely by the shared
31623        // [`validate_membro_caixa`] helper — the same per-slot substrate
31624        // primitive routing empty + shape arms uniformly onto
31625        // [`crate::render::require_valid_dns_1123_label`] that every
31626        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
31627        // on `:placement :clusters`, [`validate_entrada_para`] on
31628        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
31629        // :de`/`:para`) already funnels its own empty arm through.
31630        //
31631        // Two arms pin the collapse:
31632        //
31633        //   (1) The per-slot helper called with the empty string returns
31634        //       byte-equal to the previous inline arm's diagnostic — so
31635        //       a future rebrand of [`validate_membro_caixa`] that
31636        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
31637        //       empty input (an inadvertent switch to
31638        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
31639        //       `on_invalid` arm, an accidental re-routing to a shared
31640        //       `MembroError::Empty` under a future error-hierarchy
31641        //       flattening) would silently split the drift from the
31642        //       [`validate_membros`] caller and surface the wrong
31643        //       diagnostic on the author-facing empty-`:caixa` footgun.
31644        //
31645        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
31646        //       anywhere in the `:membros` fan-out still trips
31647        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
31648        //       no outer inline guard needed. Same shape as the
31649        //       whole-spec arm on [`validate_placement_cluster`] /
31650        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
31651        //       one substrate primitive per axis, folding empty + shape.
31652        //
31653        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
31654        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
31655        // MeshPolicy::validate) already extend across the M3 mesh-slot
31656        // family — closes the last per-slot gate on the family carrying
31657        // an inline empty guard duplicating its own helper.
31658        assert_eq!(
31659            validate_membro_caixa(""),
31660            Err(AplicacaoError::MembroCaixaEmpty),
31661            "validate_membro_caixa must own the empty arm outright — a \
31662             regression here would silently split MembroCaixaEmpty from \
31663             validate_membros' end-to-end refusal shape after the outer \
31664             inline `if m.nome().is_empty()` guard collapse",
31665        );
31666        let mut s = three_member_spec();
31667        s.membros[0].caixa = String::new();
31668        assert_eq!(
31669            s.validate().unwrap_err(),
31670            AplicacaoError::MembroCaixaEmpty,
31671            "an empty-`:caixa` :membros head entry must trip \
31672             MembroCaixaEmpty end-to-end via validate() with the outer \
31673             inline guard removed — the per-slot helper alone is now \
31674             load-bearing",
31675        );
31676        let mut s = three_member_spec();
31677        s.membros[2].caixa = String::new();
31678        assert_eq!(
31679            s.validate().unwrap_err(),
31680            AplicacaoError::MembroCaixaEmpty,
31681            "an empty-`:caixa` :membros tail entry must trip \
31682             MembroCaixaEmpty end-to-end via validate() with the outer \
31683             inline guard removed — the per-slot helper alone reaches \
31684             every fan-out position",
31685        );
31686    }
31687
31688    #[test]
31689    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
31690        // The canonical per-`:placement` Akka-cluster-sharding
31691        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
31692        // the `:placement :shard-key` field byte-for-byte, borrowed
31693        // from the typed slot's own `Option<String>` storage. Peer of
31694        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
31695        // per-`:contratos` [`WitContract::source`] /
31696        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
31697        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
31698        // slot-atom scalar-value axes — same "the substrate-primitive
31699        // accessor must byte-equal the raw field access verbatim across
31700        // every author-declared value" discipline extended to the
31701        // per-`:placement` Akka-cluster-sharding key extractor arm.
31702        // Pins against a future silent detour that re-normalized the
31703        // key (an accidental `.to_lowercase()` — every non-empty
31704        // `:shard-key` is validated as a printable-ASCII single-token
31705        // reference upstream via [`validate_placement_shard_key`], so
31706        // any re-normalization is redundant + a drift surface between
31707        // the validator and the accessor), a per-cluster alias rewrite
31708        // the operator authors on one consumer without the other, or an
31709        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
31710        // that didn't land on the peer field-access sites. Four values
31711        // sweep the accept-set the shape gate admits — bare identifier,
31712        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
31713        // the four canonical Akka-style entity-id extractor shapes the
31714        // future M4 cluster-sharding reconciler hashes.
31715        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
31716            let p = Placement {
31717                estrategia: PlacementStrategy::Sharded,
31718                clusters: vec!["rio".into()],
31719                affinity: None,
31720                shard_key: Some(key.into()),
31721            };
31722            assert_eq!(
31723                p.shard_key(),
31724                Some(key),
31725                "Placement::shard_key must return :placement :shard-key \
31726                 verbatim (got {:?}, expected Some({key:?}))",
31727                p.shard_key(),
31728            );
31729            assert_eq!(
31730                p.shard_key(),
31731                p.shard_key.as_deref(),
31732                "Placement::shard_key must byte-equal the .shard_key \
31733                 field's `.as_deref()` projection",
31734            );
31735        }
31736    }
31737
31738    #[test]
31739    fn placement_shard_key_none_when_field_is_none() {
31740        // The absent-`:shard-key` arm of the per-`:placement`
31741        // Akka-cluster-sharding accessor pin: when the typed slot is
31742        // absent — the canonical shape under `:estrategia Replicated` /
31743        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
31744        // enforced `shard_key.is_some() == matches!(estrategia,
31745        // Sharded)` partition — [`Placement::shard_key`] must return
31746        // `None`. Pins against a future silent detour that projected
31747        // the absent slot to a `Some("")` empty-string default (the
31748        // canonical `Option<String>` → `String` collapse footgun the
31749        // sibling M2 [`crate::LimitsSpec::is_empty`] /
31750        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
31751        // already guard on the peer M2 typed-slot surfaces), a
31752        // `Some("None")` stringified-None round-trip, or a `Some` arm
31753        // whose contents were derived from a sibling slot (an
31754        // accidental fallback to `estrategia.as_str()` that read the
31755        // strategy discriminator into the key axis). Two placements
31756        // sweep the accept-set every `validate`-passing non-`Sharded`
31757        // shape lands on — `Replicated` (Erlang/OTP distributed-app
31758        // takeover) and `SingleNode` (single-node hosting).
31759        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
31760            let p = Placement {
31761                estrategia,
31762                clusters: vec!["rio".into()],
31763                affinity: None,
31764                shard_key: None,
31765            };
31766            assert!(
31767                p.shard_key().is_none(),
31768                "Placement::shard_key must return None when the typed \
31769                 slot is absent under :estrategia {estrategia:?} (got {:?})",
31770                p.shard_key(),
31771            );
31772            assert_eq!(
31773                p.shard_key(),
31774                p.shard_key.as_deref(),
31775                "Placement::shard_key must byte-equal the .shard_key \
31776                 field's `.as_deref()` projection in the absent arm",
31777            );
31778        }
31779    }
31780
31781    #[test]
31782    fn placement_shard_key_borrows_from_shard_key_storage() {
31783        // The borrow-not-copy pin: [`Placement::shard_key`] must return
31784        // an `Option<&str>` whose `Some` arm borrows from the typed
31785        // slot's own [`String`] storage — same-address invariant with
31786        // `p.shard_key.as_deref().unwrap()`. Pins against a future
31787        // silent detour that allocated a fresh `String`
31788        // (`self.shard_key.clone().map(...)` in the body would type-
31789        // check but silently drop the borrow, and every downstream
31790        // consumer that assumed the returned slice outlives `&self`
31791        // would break on a stale-reference use-after-free — the
31792        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
31793        // gate's `Some(k)`-bound match arm reads `k: &str` under the
31794        // accessor's return type and would silently misbehave if this
31795        // accessor produced a detached copy). Peer of the sibling
31796        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
31797        // [`WitContract::source`] / [`WitContract::destination`]
31798        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
31799        // (6db982c) borrow-invariant pins on the mesh-slot-atom
31800        // scalar-value axes — first extension of the discipline onto
31801        // an `Option<String>`-shaped optional-scalar axis.
31802        let p = Placement {
31803            estrategia: PlacementStrategy::Sharded,
31804            clusters: vec!["rio".into()],
31805            affinity: None,
31806            shard_key: Some("tenantId".into()),
31807        };
31808        let key = p.shard_key().expect("Some arm");
31809        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
31810        assert_eq!(
31811            key.as_ptr(),
31812            storage_slice.as_ptr(),
31813            "Placement::shard_key must borrow from the .shard_key \
31814             String's backing storage — a fresh allocation here means \
31815             the accessor no longer names the substrate-primitive typed \
31816             dispatch and every downstream consumer would silently \
31817             carry a detached copy",
31818        );
31819        assert_eq!(
31820            key.len(),
31821            storage_slice.len(),
31822            "Placement::shard_key and .shard_key.as_deref() must byte-\
31823             equal in length as well as in address",
31824        );
31825    }
31826
31827    #[test]
31828    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
31829        // The canonical per-`:placement` M3-Adaptive-compression-hint
31830        // scalar pin: [`Placement::affinity`] must return the
31831        // `:placement :affinity` field byte-for-byte, borrowed from the
31832        // typed slot's own `Option<String>` storage. Peer of the sibling
31833        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
31834        // pin on the sibling `Option<&str>` optional-scalar axis — same
31835        // "the substrate-primitive accessor must byte-equal the raw
31836        // field access verbatim across every author-declared value"
31837        // discipline extended to the peer per-`:placement` M3-Adaptive-
31838        // compression-hint arm. Pins against a future silent detour
31839        // that re-normalized the hint (an accidental `.to_lowercase()`
31840        // — every `:affinity` is already validated as a DNS-1123 label
31841        // upstream via [`validate_placement_affinity`], so any re-
31842        // normalization is redundant + a drift surface between the
31843        // validator and the accessor), a per-cluster alias rewrite the
31844        // operator authors on one consumer without the other, or an
31845        // accidental hint-family collapse (`low-latency` → `latency`
31846        // that dropped the qualifier prefix). Four values sweep the
31847        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
31848        // canonical adaptive-compression-weight biases the future M4
31849        // placement engine reads.
31850        for hint in [
31851            "data-locality",
31852            "low-latency",
31853            "high-throughput",
31854            "cost-optimized",
31855        ] {
31856            let p = Placement {
31857                estrategia: PlacementStrategy::Replicated,
31858                clusters: vec!["rio".into()],
31859                affinity: Some(hint.into()),
31860                shard_key: None,
31861            };
31862            assert_eq!(
31863                p.affinity(),
31864                Some(hint),
31865                "Placement::affinity must return :placement :affinity \
31866                 verbatim (got {:?}, expected Some({hint:?}))",
31867                p.affinity(),
31868            );
31869            assert_eq!(
31870                p.affinity(),
31871                p.affinity.as_deref(),
31872                "Placement::affinity must byte-equal the .affinity \
31873                 field's `.as_deref()` projection",
31874            );
31875        }
31876    }
31877
31878    #[test]
31879    fn placement_affinity_none_when_field_is_none() {
31880        // The absent-`:affinity` arm of the per-`:placement`
31881        // M3-Adaptive-compression-hint accessor pin: when the typed
31882        // slot is absent — the canonical shape of an Aplicacao that
31883        // leaves the compression weighting up to the placement engine's
31884        // cluster-default arm — [`Placement::affinity`] must return
31885        // `None`. Pins against a future silent detour that projected
31886        // the absent slot to a `Some("")` empty-string default (the
31887        // canonical `Option<String>` → `String` collapse footgun the
31888        // sibling M2 [`crate::LimitsSpec::is_empty`] /
31889        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
31890        // already guard on the peer M2 typed-slot surfaces), a
31891        // `Some("None")` stringified-None round-trip, a `Some` arm
31892        // whose contents were derived from a sibling slot (an
31893        // accidental fallback to `estrategia.as_str()` that read the
31894        // strategy discriminator into the hint axis), or a
31895        // `Some("default")` implicit-default that would silently biases
31896        // the routing without the author having written one. Three
31897        // placements sweep the accept-set every `validate`-passing
31898        // `:affinity None` shape lands on — one per PlacementStrategy
31899        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
31900        // with a shard-key), since `:affinity` is orthogonal to
31901        // `:estrategia` in the typed grammar.
31902        for (estrategia, shard_key) in [
31903            (PlacementStrategy::SingleNode, None),
31904            (PlacementStrategy::Replicated, None),
31905            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
31906        ] {
31907            let p = Placement {
31908                estrategia,
31909                clusters: vec!["rio".into()],
31910                affinity: None,
31911                shard_key,
31912            };
31913            assert!(
31914                p.affinity().is_none(),
31915                "Placement::affinity must return None when the typed \
31916                 slot is absent under :estrategia {estrategia:?} (got {:?})",
31917                p.affinity(),
31918            );
31919            assert_eq!(
31920                p.affinity(),
31921                p.affinity.as_deref(),
31922                "Placement::affinity must byte-equal the .affinity \
31923                 field's `.as_deref()` projection in the absent arm",
31924            );
31925        }
31926    }
31927
31928    #[test]
31929    fn placement_affinity_borrows_from_affinity_storage() {
31930        // The borrow-not-copy pin: [`Placement::affinity`] must return
31931        // an `Option<&str>` whose `Some` arm borrows from the typed
31932        // slot's own [`String`] storage — same-address invariant with
31933        // `p.affinity.as_deref().unwrap()`. Pins against a future
31934        // silent detour that allocated a fresh `String`
31935        // (`self.affinity.clone().map(...)` in the body would type-
31936        // check but silently drop the borrow, and every downstream
31937        // consumer that assumed the returned slice outlives `&self`
31938        // would break on a stale-reference use-after-free — the
31939        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
31940        // gate reads the accessor's `&str` return through the
31941        // [`validate_placement_affinity`] `&str` parameter and would
31942        // silently misbehave if this accessor produced a detached
31943        // copy). Peer of the sibling per-`:placement`
31944        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
31945        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
31946        // extends the discipline onto the sibling per-`:placement`
31947        // M3-Adaptive-compression-hint arm.
31948        let p = Placement {
31949            estrategia: PlacementStrategy::Replicated,
31950            clusters: vec!["rio".into()],
31951            affinity: Some("data-locality".into()),
31952            shard_key: None,
31953        };
31954        let hint = p.affinity().expect("Some arm");
31955        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
31956        assert_eq!(
31957            hint.as_ptr(),
31958            storage_slice.as_ptr(),
31959            "Placement::affinity must borrow from the .affinity \
31960             String's backing storage — a fresh allocation here means \
31961             the accessor no longer names the substrate-primitive typed \
31962             dispatch and every downstream consumer would silently \
31963             carry a detached copy",
31964        );
31965        assert_eq!(
31966            hint.len(),
31967            storage_slice.len(),
31968            "Placement::affinity and .affinity.as_deref() must byte-\
31969             equal in length as well as in address",
31970        );
31971    }
31972
31973    #[test]
31974    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
31975        // The canonical per-`:placement` distribution-strategy-scalar
31976        // pin: [`Placement::estrategia`] must return the `:placement
31977        // :estrategia` field verbatim as a [`PlacementStrategy`],
31978        // `Copy`-projected from the typed slot's own `PlacementStrategy`
31979        // storage across every variant in the closed accept-set
31980        // (`SingleNode` — Erlang/OTP distributed-app takeover;
31981        // `Replicated` — active-active across every named cluster;
31982        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
31983        // against a future silent detour that re-derived the strategy
31984        // from a peer axis (an accidental fallback to
31985        // `if shard_key.is_some() { Sharded } else { Replicated }`
31986        // collapse that read the shard-key axis into the strategy
31987        // discriminator), a variant remap the operator authors on one
31988        // consumer without the other, or a stale-derive detour that
31989        // substituted [`PlacementStrategy::default`] when the field
31990        // held any explicit variant (which would silently collapse the
31991        // distinction between "author explicitly declared `:estrategia
31992        // Replicated`" and "author omitted the slot and inherited the
31993        // default" the future per-cluster override slot depends on).
31994        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
31995        // pin on the `Copy`-return `u16` scalar axis — same "the
31996        // substrate-primitive accessor must byte-equal the raw field
31997        // access verbatim across every author-declared value" discipline
31998        // extended onto the per-`:placement` distribution-strategy
31999        // `Copy`-composite-enum scalar axis.
32000        for estrategia in [
32001            PlacementStrategy::SingleNode,
32002            PlacementStrategy::Replicated,
32003            PlacementStrategy::Sharded,
32004        ] {
32005            // Route the paired `:shard-key` fixture-builder through the
32006            // typed cross-slot invariant predicate
32007            // [`PlacementStrategy::requires_shard_key`] rather than the
32008            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
32009            // arm-identity predicate — same discipline the sibling
32010            // `placement_strategy_variants_round_trip` fixture builder now
32011            // reads through.
32012            let shard_key = estrategia
32013                .requires_shard_key()
32014                .then(|| "tenantId".to_string());
32015            let p = Placement {
32016                estrategia,
32017                clusters: vec!["rio".into()],
32018                affinity: None,
32019                shard_key,
32020            };
32021            assert_eq!(
32022                p.estrategia(),
32023                estrategia,
32024                "Placement::estrategia must return :placement :estrategia \
32025                 verbatim (got {:?}, expected {estrategia:?})",
32026                p.estrategia(),
32027            );
32028            assert_eq!(
32029                p.estrategia(),
32030                p.estrategia,
32031                "Placement::estrategia accessor and .estrategia field \
32032                 access must byte-equal — the accessor is the substrate-\
32033                 primitive typed dispatch every downstream distribution-\
32034                 strategy consumer must route through",
32035            );
32036        }
32037    }
32038
32039    #[test]
32040    fn validate_placement_reads_through_lifted_estrategia_accessor() {
32041        // Three-consumer coherence pin: the
32042        // [`AplicacaoSpec::validate_placement`]
32043        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
32044        // `estrategia:` field (which reads through
32045        // [`Placement::estrategia`] to name the strategy the empty
32046        // `:clusters` list was declared against), the same method's
32047        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
32048        // reads through [`Placement::estrategia`] to fan across the
32049        // shape-gate cascades), and the non-`Sharded`-arm
32050        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
32051        // `estrategia:` field (which reads through
32052        // [`Placement::estrategia`] to name the strategy the declared-
32053        // but-inert `:shard-key` was authored under) must all key off
32054        // the lifted accessor, so any future rebrand on the typed
32055        // slot's reader shape lands at exactly one place. Pins the
32056        // three-site coherence by exercising each error surface end-
32057        // to-end and asserting the surfaced `estrategia:` field byte-
32058        // equals the accessor's return. Peer of the sibling per-
32059        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
32060        // pin on the M3 mesh-slot `Copy`-return scalar axis.
32061
32062        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
32063        // whose `estrategia:` field must byte-equal the accessor's return
32064        // for every variant in the closed accept-set.
32065        for estrategia in [
32066            PlacementStrategy::SingleNode,
32067            PlacementStrategy::Replicated,
32068            PlacementStrategy::Sharded,
32069        ] {
32070            let mut spec = three_member_spec();
32071            spec.placement.estrategia = estrategia;
32072            spec.placement.clusters = Vec::new();
32073            // Route the paired `:shard-key` spec-mutator through the typed
32074            // cross-slot invariant predicate
32075            // [`PlacementStrategy::requires_shard_key`] rather than the
32076            // [`gen_platform::IsVariant`]-derived
32077            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
32078            // same discipline the sibling
32079            // `placement_strategy_variants_round_trip` and
32080            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
32081            // fixture builders now read through.
32082            spec.placement.shard_key = estrategia
32083                .requires_shard_key()
32084                .then(|| "tenantId".to_string());
32085            let err = spec.validate().unwrap_err();
32086            match err {
32087                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
32088                    assert_eq!(
32089                        e,
32090                        spec.placement.estrategia(),
32091                        "PlacementWithoutClusters.estrategia must byte-equal \
32092                         Placement::estrategia() — the error carrier reads \
32093                         through the lifted accessor",
32094                    );
32095                }
32096                other => panic!(
32097                    "expected PlacementWithoutClusters, got {other:?} for \
32098                     estrategia={estrategia:?}"
32099                ),
32100            }
32101        }
32102
32103        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
32104        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
32105        // must byte-equal the accessor's return for both non-`Sharded`
32106        // strategies.
32107        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
32108            let mut spec = three_member_spec();
32109            spec.placement.estrategia = estrategia;
32110            spec.placement.shard_key = Some("tenantId".into());
32111            let err = spec.validate().unwrap_err();
32112            match err {
32113                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
32114                    assert_eq!(
32115                        e,
32116                        spec.placement.estrategia(),
32117                        "ShardKeyOnNonSharded.estrategia must byte-equal \
32118                         Placement::estrategia() — the non-Sharded-arm \
32119                         refusal reads through the lifted accessor",
32120                    );
32121                }
32122                other => panic!(
32123                    "expected ShardKeyOnNonSharded, got {other:?} for \
32124                     estrategia={estrategia:?}"
32125                ),
32126            }
32127        }
32128    }
32129
32130    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
32131    //
32132    // The [`Placement::clusters`] accessor lift is the second slice-return
32133    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
32134    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
32135    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
32136    // below cover (1) the accessor's byte-equal projection against the raw
32137    // field access across the empty / singleton / cohort fixtures the
32138    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
32139    // and the per-cluster validate loop fan between, and (2) the two-
32140    // consumer coherence of the paired pre-flight refusal probe and the
32141    // per-cluster validate loop routing through the accessor on both arms.
32142
32143    #[test]
32144    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
32145        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
32146        // [`Placement::clusters`] must return the `:placement :clusters`
32147        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
32148        // the same backing buffer the raw `self.clusters.as_slice()`
32149        // field access borrows from, byte-equal across every
32150        // representative fixture in the accept-set — the empty slice
32151        // (the pre-validation sentinel every
32152        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
32153        // the singleton slice (the minimal `SingleNode`-shape cohort),
32154        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
32155        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
32156        //
32157        // Pins against a future silent detour that returned
32158        // `&Vec<String>` (which would type-check but leak the storage-
32159        // side `Vec`'s grow/push/reserve surface no consumer of the
32160        // typed view reaches for), a fresh-allocated `Vec<String>` copy
32161        // (which would type-check via a coercion but silently break
32162        // every downstream caller that relied on the slice sharing the
32163        // backing buffer's identity), or an out-of-order or length-
32164        // drifted projection (which would silently split the paired
32165        // pre-flight `.is_empty()` refusal probe's input from the per-
32166        // cluster validate loop's traversal input).
32167        //
32168        // Peer of the sibling M2
32169        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
32170        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
32171        // `:supervisor` static-child-list axis, extended onto the M3
32172        // per-`:placement` distribution-target-list `Vec`-carry axis.
32173        let fixtures: Vec<Vec<String>> = vec![
32174            Vec::new(),
32175            vec!["rio".into()],
32176            vec!["rio".into(), "mar".into()],
32177            vec!["rio".into(), "mar".into(), "plo".into()],
32178        ];
32179        for clusters in fixtures {
32180            let p = Placement {
32181                clusters: clusters.clone(),
32182                ..Placement::default()
32183            };
32184            assert_eq!(
32185                p.clusters(),
32186                clusters.as_slice(),
32187                "Placement::clusters must return :placement :clusters \
32188                 verbatim (got {:?}, expected {:?})",
32189                p.clusters(),
32190                clusters.as_slice(),
32191            );
32192            assert_eq!(
32193                p.clusters(),
32194                p.clusters.as_slice(),
32195                "Placement::clusters accessor and .clusters.as_slice() \
32196                 field access must byte-equal — the accessor is the \
32197                 substrate-primitive typed dispatch every downstream \
32198                 cluster-pool consumer must route through",
32199            );
32200            assert_eq!(
32201                p.clusters().len(),
32202                p.clusters.len(),
32203                "Placement::clusters().len() must byte-equal \
32204                 self.clusters.len() — a length-drift would silently \
32205                 split the paired pre-flight `.is_empty()` refusal \
32206                 probe input from the per-cluster validate loop's \
32207                 traversal input",
32208            );
32209        }
32210    }
32211
32212    #[test]
32213    fn validate_placement_reads_through_lifted_clusters_accessor() {
32214        // Two-consumer coherence pin: the
32215        // [`AplicacaoSpec::validate_placement`] pre-flight
32216        // `self.placement.clusters().is_empty()` refusal probe (which
32217        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
32218        // the accessor projects the empty slice) and the per-cluster
32219        // validate loop's `for c in self.placement.clusters()`
32220        // traversal (which must reach every entry in the same order
32221        // the accessor projects, so both the per-entry value-shape
32222        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
32223        // and the duplicate-detection HashSet insert that trips
32224        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
32225        // accessor's projection) must both key off the lifted
32226        // accessor, so any future rebrand on the typed slot's reader
32227        // shape lands at exactly one place. Pins the two-site
32228        // coherence by exercising each production consumer end-to-end:
32229        // (1) the `PlacementWithoutClusters` refusal under the empty
32230        // slice, (2) the `PlacementClusterInvalid` refusal fires on
32231        // the second entry of a two-cluster cohort whose head is
32232        // valid but tail is not (which requires the loop to reach the
32233        // second entry through the accessor), and (3) the
32234        // `PlacementClusterDuplicate` refusal fires on the second
32235        // entry of a two-cluster cohort that shares a name (which
32236        // requires the loop to reach both entries — a first-entry-only
32237        // projection would silently pass since the dedup HashSet has
32238        // room for the first insert).
32239        //
32240        // Peer of the sibling M2
32241        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
32242        // (bc92bce) coherence pin on the per-`:supervisor` static-
32243        // child-list axis, extended onto the M3 per-`:placement`
32244        // distribution-target-list `Vec`-carry axis.
32245
32246        // (1) Pre-flight `.is_empty()` probe: the empty slice must
32247        // trip `PlacementWithoutClusters`.
32248        let mut spec = three_member_spec();
32249        spec.placement.clusters = Vec::new();
32250        match spec.validate().unwrap_err() {
32251            AplicacaoError::PlacementWithoutClusters { .. } => {}
32252            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
32253        }
32254        assert!(
32255            spec.placement.clusters().is_empty(),
32256            "the pre-flight refusal input must be the empty slice per \
32257             the accessor's projection",
32258        );
32259
32260        // (2) Per-cluster validate loop: a two-cluster cohort with an
32261        // invalid tail entry must trip `PlacementClusterInvalid` on
32262        // the tail — the loop must reach the second entry through
32263        // the accessor.
32264        let mut spec = three_member_spec();
32265        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
32266        match spec.validate().unwrap_err() {
32267            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
32268                assert_eq!(
32269                    cluster, "BAD_CLUSTER",
32270                    "PlacementClusterInvalid.cluster must carry the \
32271                     tail entry the loop reached through the accessor",
32272                );
32273            }
32274            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
32275        }
32276        assert_eq!(
32277            spec.placement.clusters().len(),
32278            2,
32279            "the per-cluster validate loop's traversal input must be \
32280             a two-element slice per the accessor's projection",
32281        );
32282
32283        // (3) Per-cluster validate loop: a two-cluster cohort that
32284        // shares a name must trip `PlacementClusterDuplicate` on the
32285        // second entry — the loop must reach both entries through the
32286        // accessor for the dedup HashSet's second insert to collide.
32287        let mut spec = three_member_spec();
32288        spec.placement.clusters = vec!["rio".into(), "rio".into()];
32289        match spec.validate().unwrap_err() {
32290            AplicacaoError::PlacementClusterDuplicate { cluster } => {
32291                assert_eq!(
32292                    cluster, "rio",
32293                    "PlacementClusterDuplicate.cluster must carry the \
32294                     shared cluster name verbatim",
32295                );
32296            }
32297            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
32298        }
32299        assert_eq!(
32300            spec.placement.clusters().len(),
32301            2,
32302            "the per-cluster validate loop's traversal input must be \
32303             a two-element slice per the accessor's projection",
32304        );
32305    }
32306
32307    #[test]
32308    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
32309        // The canonical per-`:membros` member-list-slice-shape pin:
32310        // [`AplicacaoSpec::membros`] must return the `:membros` typed
32311        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
32312        // same backing buffer the raw `self.membros.as_slice()` field
32313        // access borrows from, byte-equal across every representative
32314        // fixture in the accept-set — the empty slice (the pre-
32315        // validation sentinel every [`AplicacaoError::NoMembros`]
32316        // refusal keys off), the singleton slice (the minimal one-
32317        // Servico Aplicacao shape), and multi-entry cohorts (the peer
32318        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
32319        // load-bearing identity of the application graph).
32320        //
32321        // Pins against a future silent detour that returned
32322        // `&Vec<Membro>` (which would type-check but leak the storage-
32323        // side `Vec`'s grow/push/reserve surface no consumer of the
32324        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
32325        // (which would type-check via a coercion but silently break
32326        // every downstream caller that relied on the slice sharing the
32327        // backing buffer's identity), or an out-of-order or length-
32328        // drifted projection (which would silently split the paired
32329        // `HashSet<&str>` name-set seed's collect input from the
32330        // pre-flight `.is_empty()` refusal probe's input from the per-
32331        // member validate loop's traversal input from the
32332        // programs.yaml emitter's per-entry fan-out loop's input from
32333        // the `feira app graph` per-member print traversal's input).
32334        //
32335        // Peer of the sibling M2
32336        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
32337        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
32338        // `:supervisor` static-child-list axis and the sibling M3
32339        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
32340        // (a6e18d7) `&[String]` byte-equal pin on the per-
32341        // `:placement` distribution-target-list axis — extends the
32342        // slice-return-accessor byte-equal-projection discipline onto
32343        // the outermost M3 mesh-slot type's per-Aplicacao member-list
32344        // `Vec`-carry axis.
32345        let fixtures: Vec<Vec<Membro>> = vec![
32346            Vec::new(),
32347            vec![membro("catalog", "^0.1")],
32348            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
32349            vec![
32350                membro("catalog", "^0.1"),
32351                membro("cart", "^0.1"),
32352                membro("payment", "^0.2"),
32353            ],
32354        ];
32355        for membros in fixtures {
32356            let s = AplicacaoSpec {
32357                membros: membros.clone(),
32358                contratos: Vec::new(),
32359                politicas: MeshPolicy::default(),
32360                placement: Placement::default(),
32361                entrada: None,
32362            };
32363            assert_eq!(
32364                s.membros(),
32365                membros.as_slice(),
32366                "AplicacaoSpec::membros must return :membros verbatim \
32367                 (got {:?}, expected {:?})",
32368                s.membros(),
32369                membros.as_slice(),
32370            );
32371            assert_eq!(
32372                s.membros(),
32373                s.membros.as_slice(),
32374                "AplicacaoSpec::membros accessor and .membros.as_slice() \
32375                 field access must byte-equal — the accessor is the \
32376                 substrate-primitive typed dispatch every downstream \
32377                 member-list consumer must route through",
32378            );
32379            assert_eq!(
32380                s.membros().len(),
32381                s.membros.len(),
32382                "AplicacaoSpec::membros().len() must byte-equal \
32383                 self.membros.len() — a length-drift would silently \
32384                 split the paired `HashSet<&str>` name-set seed's \
32385                 collect input from the pre-flight `.is_empty()` \
32386                 refusal probe input from the per-member validate \
32387                 loop's traversal input",
32388            );
32389        }
32390    }
32391
32392    #[test]
32393    fn validate_reads_through_lifted_membros_accessor() {
32394        // Three-consumer coherence pin: the
32395        // [`AplicacaoSpec::validate_membros`] pre-flight
32396        // `self.membros().is_empty()` refusal probe (which must trip
32397        // [`AplicacaoError::NoMembros`] when the accessor projects the
32398        // empty slice), the same method's per-member validate loop's
32399        // `for m in self.membros()` traversal (which must reach every
32400        // entry in the same order the accessor projects, so both the
32401        // per-entry empty-`:caixa` gate that trips
32402        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
32403        // detection `insert_first_seen` that trips
32404        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
32405        // projection), and the peer [`AplicacaoSpec::validate`]'s
32406        // `HashSet<&str>` name-set seed's
32407        // `self.membros().iter().map(Membro::nome).collect()` collect
32408        // input (which every `:contratos` `:de` / `:para` membership
32409        // lookup rejects an unknown name against) must all three key
32410        // off the lifted accessor, so any future rebrand on the typed
32411        // slot's reader shape lands at exactly one place. Pins the
32412        // three-site coherence by exercising each production consumer
32413        // end-to-end: (1) the `NoMembros` refusal under the empty
32414        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
32415        // second entry of a two-member cohort whose head is valid but
32416        // tail has an empty `:caixa` (which requires the loop to
32417        // reach the second entry through the accessor), and (3) the
32418        // `MembroDuplicate` refusal fires on the second entry of a
32419        // two-member cohort that shares a `:caixa` name (which
32420        // requires the loop to reach both entries through the
32421        // accessor for the dedup HashSet's second insert to collide).
32422        //
32423        // Peer of the sibling M2
32424        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
32425        // (bc92bce) coherence pin on the per-`:supervisor` static-
32426        // child-list axis and the sibling M3
32427        // `validate_placement_reads_through_lifted_clusters_accessor`
32428        // (a6e18d7) coherence pin on the per-`:placement` distribution-
32429        // target-list axis — extends the slice-return-accessor
32430        // multi-consumer coherence discipline onto the outermost M3
32431        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
32432
32433        // (1) Pre-flight `.is_empty()` probe: the empty slice must
32434        // trip `NoMembros`.
32435        let mut spec = three_member_spec();
32436        spec.membros = Vec::new();
32437        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
32438        assert!(
32439            spec.membros().is_empty(),
32440            "the pre-flight refusal input must be the empty slice per \
32441             the accessor's projection",
32442        );
32443
32444        // (2) Per-member validate loop: a two-member cohort with an
32445        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
32446        // the tail — the loop must reach the second entry through
32447        // the accessor.
32448        let mut spec = three_member_spec();
32449        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
32450        assert_eq!(
32451            spec.validate().unwrap_err(),
32452            AplicacaoError::MembroCaixaEmpty,
32453        );
32454        assert_eq!(
32455            spec.membros().len(),
32456            2,
32457            "the per-member validate loop's traversal input must be \
32458             a two-element slice per the accessor's projection",
32459        );
32460
32461        // (3) Per-member validate loop: a two-member cohort that
32462        // shares a `:caixa` name must trip `MembroDuplicate` on the
32463        // second entry — the loop must reach both entries through the
32464        // accessor for the dedup HashSet's second insert to collide.
32465        let mut spec = three_member_spec();
32466        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
32467        match spec.validate().unwrap_err() {
32468            AplicacaoError::MembroDuplicate { caixa } => {
32469                assert_eq!(
32470                    caixa, "catalog",
32471                    "MembroDuplicate.caixa must carry the shared \
32472                     member name verbatim",
32473                );
32474            }
32475            other => panic!("expected MembroDuplicate, got {other:?}"),
32476        }
32477        assert_eq!(
32478            spec.membros().len(),
32479            2,
32480            "the per-member validate loop's traversal input must be \
32481             a two-element slice per the accessor's projection",
32482        );
32483    }
32484
32485    #[test]
32486    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
32487        // The canonical per-`:contratos` contract-list-slice-shape pin:
32488        // [`AplicacaoSpec::contratos`] must return the `:contratos`
32489        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
32490        // slice-view over the same backing buffer the raw
32491        // `self.contratos.as_slice()` field access borrows from, byte-
32492        // equal across every representative fixture in the accept-set —
32493        // the empty slice (the pre-validation "internal-only mesh" shape
32494        // an Aplicacao whose members exchange no typed edges renders
32495        // through), the singleton slice (the minimal one-edge Aplicacao
32496        // shape), and multi-entry cohorts (the peer multi-edge shapes
32497        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
32498        // of the application graph).
32499        //
32500        // Pins against a future silent detour that returned
32501        // `&Vec<WitContract>` (which would type-check but leak the
32502        // storage-side `Vec`'s grow/push/reserve surface no consumer of
32503        // the typed view reaches for), a fresh-allocated
32504        // `Vec<WitContract>` copy (which would type-check via a coercion
32505        // but silently break every downstream caller that relied on the
32506        // slice sharing the backing buffer's identity), or an out-of-
32507        // order or length-drifted projection (which would silently split
32508        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
32509        // seed's traversal input from the `detect_sync_cycles` per-edge
32510        // adjacency-list seed's traversal input from the
32511        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
32512        // BTreeMap grouping loop's traversal input from the
32513        // `feira app graph` per-contract print traversal's input).
32514        //
32515        // Peer of the immediately-adjacent sibling M3
32516        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
32517        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
32518        // node-list axis, the sibling M3
32519        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
32520        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
32521        // distribution-target-list axis, and the sibling M2
32522        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
32523        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
32524        // `:supervisor` static-child-list axis — extends the slice-
32525        // return-accessor byte-equal-projection discipline onto the
32526        // outermost M3 mesh-slot type's per-Aplicacao contract-list
32527        // `Vec`-carry axis, closing the last unlifted per-
32528        // `AplicacaoSpec` `Vec`-carry axis.
32529        let fixtures: Vec<Vec<WitContract>> = vec![
32530            Vec::new(),
32531            vec![contract_http("cart", "catalog", "/products/:id")],
32532            vec![
32533                contract_http("cart", "catalog", "/products/:id"),
32534                contract_http("cart", "payment", "/charge"),
32535            ],
32536            vec![
32537                contract_http("cart", "catalog", "/products/:id"),
32538                contract_http("cart", "payment", "/charge"),
32539                contract_http("payment", "catalog", "/audit"),
32540            ],
32541        ];
32542        for contratos in fixtures {
32543            let s = AplicacaoSpec {
32544                membros: vec![
32545                    membro("catalog", "^0.1"),
32546                    membro("cart", "^0.1"),
32547                    membro("payment", "^0.2"),
32548                ],
32549                contratos: contratos.clone(),
32550                politicas: MeshPolicy::default(),
32551                placement: Placement::default(),
32552                entrada: None,
32553            };
32554            assert_eq!(
32555                s.contratos(),
32556                contratos.as_slice(),
32557                "AplicacaoSpec::contratos must return :contratos verbatim \
32558                 (got {:?}, expected {:?})",
32559                s.contratos(),
32560                contratos.as_slice(),
32561            );
32562            assert_eq!(
32563                s.contratos(),
32564                s.contratos.as_slice(),
32565                "AplicacaoSpec::contratos accessor and \
32566                 .contratos.as_slice() field access must byte-equal — \
32567                 the accessor is the substrate-primitive typed dispatch \
32568                 every downstream contract-list consumer must route \
32569                 through",
32570            );
32571            assert_eq!(
32572                s.contratos().len(),
32573                s.contratos.len(),
32574                "AplicacaoSpec::contratos().len() must byte-equal \
32575                 self.contratos.len() — a length-drift would silently \
32576                 split the paired per-edge validate-loop's traversal \
32577                 input from the sync-cycle adjacency-list seed's \
32578                 traversal input from the cilium_network_policies \
32579                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
32580                 input from the `feira app graph` per-contract print \
32581                 traversal's input",
32582            );
32583        }
32584    }
32585
32586    #[test]
32587    fn validate_reads_through_lifted_contratos_accessor() {
32588        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
32589        // per-`:contratos` validate-loop's `for c in self.contratos()`
32590        // traversal (which must reach every entry in the same order the
32591        // accessor projects, so both the per-entry
32592        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
32593        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
32594        // dedup `HashSet` insert key off the accessor's projection),
32595        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
32596        // `for c in self.contratos()` adjacency-list seed (which drives
32597        // the sync-subgraph deadlock-detection gate via
32598        // [`AplicacaoError::SyncCycle`]), and the peer
32599        // [`caixa_mesh::cilium_network_policies`]'s
32600        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
32601        // grouping loop (which drives the per-CNP fan-out) must all
32602        // three key off the lifted accessor, so any future rebrand on
32603        // the typed slot's reader shape lands at exactly one place. Pins
32604        // the three-site coherence by exercising the two caixa-core
32605        // production consumers end-to-end: (1) the empty-`:contratos`
32606        // slice must validate without a per-edge diagnostic (the
32607        // per-edge loop is a no-op under the empty projection), (2) the
32608        // `ContratoMemberMissing` refusal fires on the second entry of a
32609        // two-edge cohort whose head references a valid member but tail
32610        // references a phantom name (which requires the loop to reach
32611        // the second entry through the accessor), and (3) the
32612        // `SyncCycle` refusal fires on a self-referential two-edge
32613        // cohort through the sync-cycle detector's peer projection
32614        // (which requires the detector to iterate the accessor's
32615        // projection to add the back-edge to its adjacency list).
32616        //
32617        // Peer of the sibling M3
32618        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
32619        // three-consumer coherence pin on the per-`:membros` node-list
32620        // axis and the sibling M3
32621        // `validate_placement_reads_through_lifted_clusters_accessor`
32622        // (a6e18d7) coherence pin on the per-`:placement` distribution-
32623        // target-list axis — extends the slice-return-accessor multi-
32624        // consumer coherence discipline onto the outermost M3 mesh-slot
32625        // type's per-Aplicacao contract-list `Vec`-carry axis.
32626
32627        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
32628        // and no per-edge diagnostic surfaces. Validate succeeds on
32629        // the well-formed `:membros` head.
32630        let mut spec = three_member_spec();
32631        spec.contratos = Vec::new();
32632        assert!(
32633            spec.validate().is_ok(),
32634            "empty :contratos must validate — the per-edge loop is a \
32635             no-op under the accessor's empty projection",
32636        );
32637        assert!(
32638            spec.contratos().is_empty(),
32639            "the per-edge validate loop's traversal input must be the \
32640             empty slice per the accessor's projection",
32641        );
32642
32643        // (2) Per-edge validate loop: a two-edge cohort whose tail
32644        // references a phantom `:para` member must trip
32645        // `ContratoMemberMissing` on the tail — the loop must reach
32646        // the second entry through the accessor for the membership
32647        // lookup to fail on the phantom name.
32648        let mut spec = three_member_spec();
32649        spec.contratos = vec![
32650            contract_http("cart", "catalog", "/products/:id"),
32651            contract_http("cart", "phantom", "/x"),
32652        ];
32653        let err = spec.validate().unwrap_err();
32654        assert!(
32655            matches!(
32656                err,
32657                AplicacaoError::ContratoMemberMissing { ref caixa }
32658                    if caixa == "phantom"
32659            ),
32660            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
32661        );
32662        assert_eq!(
32663            spec.contratos().len(),
32664            2,
32665            "the per-edge validate loop's traversal input must be \
32666             a two-element slice per the accessor's projection",
32667        );
32668
32669        // (3) Sync-cycle detector: a two-edge synchronous cohort
32670        // whose second edge closes the sync-subgraph back onto the
32671        // first must trip [`AplicacaoError::ContratoCycle`] — the
32672        // detector must iterate the accessor's projection to add
32673        // both edges to its adjacency list, so a length-drift on
32674        // the accessor's projection would silently disagree with
32675        // the sync-cycle detector on which edge closes the loop.
32676        // Peer projection to the `validate` per-edge loop above:
32677        // the sync-cycle detector routes through the same lifted
32678        // accessor, so a rebrand of the reader shape lands at one
32679        // place. Uses a two-edge cohort (cart → catalog → cart)
32680        // because the per-edge `ContratoSelfLoop` gate fires before
32681        // the sync-cycle detector on a single self-referential edge
32682        // (`cart → cart`) — the cycle-detector's input must be a
32683        // multi-edge cohort for its per-edge traversal input to be
32684        // observably wider than the per-edge validate loop's input.
32685        let mut spec = three_member_spec();
32686        spec.contratos = vec![
32687            contract_http("cart", "catalog", "/products/:id"),
32688            contract_http("catalog", "cart", "/callback"),
32689        ];
32690        let err = spec.validate().unwrap_err();
32691        assert!(
32692            matches!(err, AplicacaoError::ContratoCycle { .. }),
32693            "expected ContratoCycle from the sync-cycle detector on a \
32694             two-edge back-edge cohort, got {err:?}",
32695        );
32696        assert_eq!(
32697            spec.contratos().len(),
32698            2,
32699            "the sync-cycle detector's traversal input must be a \
32700             two-element slice per the accessor's projection",
32701        );
32702    }
32703
32704    #[test]
32705    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
32706        // The canonical per-`:politicas` outer-composite-reference-shape
32707        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
32708        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
32709        // the same backing storage the raw `&self.politicas` field
32710        // access borrows from, byte-equal across every representative
32711        // fixture in the accept-set — the default `MeshPolicy` (the
32712        // author-empty "no policy on any axis" shape whose
32713        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
32714        // shapes carrying one axis at a time
32715        // (`{mtls_required, timeout, retries, circuit_breaker,
32716        // rate_limit}` — the minimal five-axis fan-out over the
32717        // per-axis lifted accessor family every downstream mesh-artifact
32718        // emitter dispatches on), and the multi-axis composite (the
32719        // canonical `three_member_spec` fixture's `{timeout, retries,
32720        // mtls_required}` triple — the load-bearing shape every
32721        // Aplicacao-scoped fixture in this suite constructs).
32722        //
32723        // Pins against a future silent detour that returned a fresh-
32724        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
32725        // impl but silently break every downstream caller that relied
32726        // on the reference sharing the composite's backing identity), a
32727        // reference to an operator-resolved overlay (the future
32728        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
32729        // acknowledges — its resolution must land at exactly this
32730        // accessor body, not silently divert the raw slot away from a
32731        // second consumer), or an axis-shuffled projection (a future
32732        // detour that swapped `timeout` and `retries` through the
32733        // accessor would silently split the paired `validate_politicas`
32734        // per-axis bracket-dispatch's traversal input from the peer
32735        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
32736        // emitter's fan-out input from the peer
32737        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
32738        // overlay emitter's fan-out input).
32739        //
32740        // Peer of the sibling M3
32741        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
32742        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
32743        // node-list `Vec`-carry axis and the sibling M3
32744        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
32745        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
32746        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
32747        // accessor byte-equal-projection discipline onto the outermost
32748        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
32749        // reference axis, the first `&Composite`-return accessor on the
32750        // outer [`AplicacaoSpec`] type.
32751        let fixtures: Vec<MeshPolicy> = vec![
32752            MeshPolicy::default(),
32753            MeshPolicy {
32754                mtls_required: Some(true),
32755                ..MeshPolicy::default()
32756            },
32757            MeshPolicy {
32758                mtls_required: Some(false),
32759                ..MeshPolicy::default()
32760            },
32761            MeshPolicy {
32762                timeout: Some(Duration::from_secs(30)),
32763                ..MeshPolicy::default()
32764            },
32765            MeshPolicy {
32766                retries: Some(3),
32767                ..MeshPolicy::default()
32768            },
32769            MeshPolicy {
32770                circuit_breaker: Some(CircuitBreaker {
32771                    max_failures: 5,
32772                    window: Duration::from_secs(30),
32773                }),
32774                ..MeshPolicy::default()
32775            },
32776            MeshPolicy {
32777                rate_limit: Some(RateLimit {
32778                    rate: 100,
32779                    window: Duration::from_secs(1),
32780                }),
32781                ..MeshPolicy::default()
32782            },
32783            MeshPolicy {
32784                timeout: Some(Duration::from_secs(30)),
32785                retries: Some(3),
32786                mtls_required: Some(true),
32787                ..MeshPolicy::default()
32788            },
32789        ];
32790        for politicas in fixtures {
32791            let s = AplicacaoSpec {
32792                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
32793                contratos: Vec::new(),
32794                politicas: politicas.clone(),
32795                placement: Placement::default(),
32796                entrada: None,
32797            };
32798            assert_eq!(
32799                *s.politicas(),
32800                politicas,
32801                "AplicacaoSpec::politicas must return :politicas verbatim \
32802                 (got {:?}, expected {:?})",
32803                s.politicas(),
32804                politicas,
32805            );
32806            assert!(
32807                std::ptr::eq(s.politicas(), &s.politicas),
32808                "AplicacaoSpec::politicas accessor and &self.politicas \
32809                 field access must borrow the same backing storage — \
32810                 the accessor is the substrate-primitive typed dispatch \
32811                 every downstream mesh-policy composite consumer must \
32812                 route through, and a reference-identity split would \
32813                 silently break every consumer that relied on the \
32814                 borrow sharing the composite's storage",
32815            );
32816            assert_eq!(
32817                s.politicas().is_empty(),
32818                s.politicas.is_empty(),
32819                "AplicacaoSpec::politicas().is_empty() must byte-equal \
32820                 self.politicas.is_empty() — an emptiness-drift would \
32821                 silently split the paired `validate_politicas` \
32822                 per-axis bracket-dispatch's seed from the peer \
32823                 caixa-mesh CNP mTLS-overlay emitter's key from the \
32824                 peer caixa-mesh HTTPRoute timeout+retry overlay \
32825                 emitter's key",
32826            );
32827        }
32828    }
32829
32830    #[test]
32831    fn validate_politicas_reads_through_lifted_politicas_accessor() {
32832        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
32833        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
32834        // followed by the per-axis fan-out `p.timeout()` /
32835        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
32836        // the lifted axis-level accessor family) must key off the
32837        // lifted outer accessor, so any future rebrand on the typed
32838        // slot's outer-composite reader shape lands at exactly one
32839        // place. Pins the multi-axis coherence by exercising each
32840        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
32841        // a `Some(Duration::ZERO)` timeout under the outer accessor's
32842        // reference projection, (2) `PolicyRetriesZero` fires on a
32843        // `Some(0)` retries under the same projection, and (3) an
32844        // empty [`MeshPolicy::default`] passes `validate_politicas` —
32845        // the outer accessor's reference-projection reaches every
32846        // per-axis branch without silently short-circuiting any.
32847        //
32848        // Peer of the sibling M3
32849        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
32850        // three-consumer coherence pin on the per-`:membros` node-list
32851        // axis and the sibling M3
32852        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
32853        // three-consumer coherence pin on the per-`:contratos`
32854        // edge-list axis — extends the multi-consumer coherence
32855        // discipline onto the outermost M3 mesh-slot type's per-
32856        // Aplicacao mesh-policy composite-reference axis, the first
32857        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
32858        // type.
32859
32860        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
32861        // reference projection: a `Some(Duration::ZERO)` timeout must
32862        // trip the zero-floor gate. The bracket-dispatch's first arm
32863        // reads `p.timeout()` on the reference returned by the outer
32864        // accessor.
32865        let mut spec = three_member_spec();
32866        spec.politicas.timeout = Some(Duration::ZERO);
32867        spec.politicas.retries = None;
32868        spec.politicas.circuit_breaker = None;
32869        spec.politicas.rate_limit = None;
32870        assert_eq!(
32871            spec.validate().unwrap_err(),
32872            AplicacaoError::PolicyTimeoutZero,
32873        );
32874        assert!(
32875            std::ptr::eq(spec.politicas(), &spec.politicas),
32876            "the `validate_politicas` per-axis bracket-dispatch's \
32877             traversal input must be the same backing composite the \
32878             accessor's reference projection borrows from",
32879        );
32880
32881        // (2) `PolicyRetriesZero` refusal under the outer accessor's
32882        // reference projection: a `Some(0)` retries must trip the
32883        // zero-floor gate. The bracket-dispatch's second arm reads
32884        // `p.retries()` on the reference returned by the outer accessor.
32885        let mut spec = three_member_spec();
32886        spec.politicas.timeout = None;
32887        spec.politicas.retries = Some(0);
32888        spec.politicas.circuit_breaker = None;
32889        spec.politicas.rate_limit = None;
32890        assert_eq!(
32891            spec.validate().unwrap_err(),
32892            AplicacaoError::PolicyRetriesZero,
32893        );
32894
32895        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
32896        // — every per-axis arm short-circuits on `None`, so the outer
32897        // accessor's reference projection reaches the fall-through
32898        // `Ok(())` without any per-axis refusal firing.
32899        let mut spec = three_member_spec();
32900        spec.politicas = MeshPolicy::default();
32901        assert!(
32902            spec.validate().is_ok(),
32903            "an empty `MeshPolicy` must pass `validate_politicas` — \
32904             every per-axis arm short-circuits on `None` under the \
32905             outer accessor's reference projection",
32906        );
32907        assert!(
32908            spec.politicas().is_empty(),
32909            "the outer accessor's reference projection must be the \
32910             empty composite per the `MeshPolicy::default()` fixture",
32911        );
32912    }
32913
32914    #[test]
32915    #[allow(clippy::too_many_lines)]
32916    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
32917        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
32918        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
32919        // must both key off the lifted axis-level accessors
32920        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
32921        // the peer `:circuit-breaker` / `:rate-limit` arms already
32922        // routing through [`MeshPolicy::circuit_breaker`] /
32923        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
32924        // per axis on the substrate primitive" shape at the fan-out
32925        // (four axes, four accessors, no raw-field-access site
32926        // anywhere on the bracket-dispatch). Pins the per-axis
32927        // coherence at the accept-set boundaries the bracket carves:
32928        //   1. accessor byte-equal to raw field on every representative
32929        //      accept-set value (`None`, sub-cap, at-cap, past-cap
32930        //      sentinel) — a future accessor drift that no longer
32931        //      shipped the raw slot verbatim would surface here,
32932        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
32933        //      routed through the accessor's projection, proving the
32934        //      first arm reads through the accessor rather than a
32935        //      silent-detour peer-axis field access,
32936        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
32937        //      through the accessor's projection, proving the second
32938        //      arm reads through the accessor,
32939        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
32940        //      passes validate under the accessor projection (paired
32941        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
32942        //      sibling axis), pinning the upper-boundary accept-arm
32943        //      also routes through the accessor.
32944        //
32945        // Peer of the sibling M3
32946        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
32947        // outer-composite-reference coherence pin (which asserts the
32948        // `let p = self.politicas()` seed); extends the discipline onto
32949        // the per-axis fan-out layer that consumes the seed's
32950        // reference. Same shape as
32951        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
32952        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
32953        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
32954        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
32955
32956        // (1) Accessor byte-equal to raw field on the `:timeout` axis
32957        // across the accept-set boundaries the bracket dispatch's
32958        // three-arm gate carves out
32959        // ([`crate::render::require_positive_canonical_bounded_duration`]
32960        // — zero-floor + canonical-form + upper-cap).
32961        for timeout in [
32962            None,
32963            Some(Duration::ZERO),
32964            Some(Duration::from_millis(1)),
32965            Some(POLICY_TIMEOUT_MAX),
32966        ] {
32967            let p = MeshPolicy {
32968                timeout,
32969                ..MeshPolicy::default()
32970            };
32971            assert_eq!(
32972                p.timeout(),
32973                p.timeout,
32974                "MeshPolicy::timeout accessor must byte-equal the raw \
32975                 .timeout field across every accept-set boundary the \
32976                 validate_politicas :timeout arm carves out — a drift \
32977                 here would silently split the validate bracket's arm \
32978                 from the peer caixa-mesh HTTPRoute timeout-overlay \
32979                 emitter's read",
32980            );
32981        }
32982
32983        // (2) Accessor byte-equal to raw field on the `:retries` axis
32984        // across the accept-set boundaries the bracket dispatch's
32985        // two-arm gate carves out
32986        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
32987        // + upper-cap).
32988        for retries in [
32989            None,
32990            Some(0u32),
32991            Some(1u32),
32992            Some(POLICY_RETRIES_MAX),
32993            Some(POLICY_RETRIES_MAX + 1),
32994            Some(u32::MAX),
32995        ] {
32996            let p = MeshPolicy {
32997                retries,
32998                ..MeshPolicy::default()
32999            };
33000            assert_eq!(
33001                p.retries(),
33002                p.retries,
33003                "MeshPolicy::retries accessor must byte-equal the raw \
33004                 .retries field across every accept-set boundary the \
33005                 validate_politicas :retries arm carves out — a drift \
33006                 here would silently split the validate bracket's arm \
33007                 from the peer caixa-mesh HTTPRoute retry-overlay \
33008                 emitter's read",
33009            );
33010        }
33011
33012        // (3) `PolicyTimeoutZero` fires on the accessor-projected
33013        // zero-floor boundary. A silent detour that no longer read
33014        // through `p.timeout()` (a peer-axis field read, an accidental
33015        // Option::and-then chain that collapsed the None arm to Some,
33016        // an accessor rebrand that clamped the return through the
33017        // upper cap) would fail to refuse here.
33018        let mut spec = three_member_spec();
33019        spec.politicas.timeout = Some(Duration::ZERO);
33020        spec.politicas.retries = None;
33021        spec.politicas.circuit_breaker = None;
33022        spec.politicas.rate_limit = None;
33023        assert_eq!(
33024            spec.politicas().timeout(),
33025            Some(Duration::ZERO),
33026            "the accessor projection must reflect the fixture's \
33027             `Some(Duration::ZERO)` :timeout verbatim",
33028        );
33029        assert_eq!(
33030            spec.validate().unwrap_err(),
33031            AplicacaoError::PolicyTimeoutZero,
33032            "the validate_politicas :timeout zero-floor arm must fire \
33033             through the lifted accessor's projection — a silent \
33034             detour to a peer-axis field would fail to refuse",
33035        );
33036
33037        // (4) `PolicyRetriesZero` fires on the accessor-projected
33038        // zero-floor boundary on the sibling `:retries` axis.
33039        let mut spec = three_member_spec();
33040        spec.politicas.timeout = None;
33041        spec.politicas.retries = Some(0);
33042        spec.politicas.circuit_breaker = None;
33043        spec.politicas.rate_limit = None;
33044        assert_eq!(
33045            spec.politicas().retries(),
33046            Some(0),
33047            "the accessor projection must reflect the fixture's \
33048             `Some(0)` :retries verbatim",
33049        );
33050        assert_eq!(
33051            spec.validate().unwrap_err(),
33052            AplicacaoError::PolicyRetriesZero,
33053            "the validate_politicas :retries zero-floor arm must fire \
33054             through the lifted accessor's projection — a silent \
33055             detour to a peer-axis field would fail to refuse",
33056        );
33057
33058        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
33059        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
33060        // must pass validate under the accessor projection — pins the
33061        // upper-boundary accept-arm also routes through the lifted
33062        // accessor (a drift that clamped or short-circuited at the
33063        // upper boundary would fail the whole-spec validate here).
33064        let mut spec = three_member_spec();
33065        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
33066        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
33067        spec.politicas.circuit_breaker = None;
33068        spec.politicas.rate_limit = None;
33069        assert_eq!(
33070            spec.politicas().timeout(),
33071            Some(POLICY_TIMEOUT_MAX),
33072            "the accessor projection must reflect the fixture's \
33073             at-cap :timeout verbatim",
33074        );
33075        assert_eq!(
33076            spec.politicas().retries(),
33077            Some(POLICY_RETRIES_MAX),
33078            "the accessor projection must reflect the fixture's \
33079             at-cap :retries verbatim",
33080        );
33081        assert!(
33082            spec.validate().is_ok(),
33083            "at-cap :timeout + :retries must pass validate under the \
33084             accessor projection — the upper-boundary accept-arm on \
33085             both axes routes through the lifted accessor",
33086        );
33087    }
33088
33089    #[test]
33090    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
33091        // The canonical per-`:placement` outer-composite-reference-shape
33092        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
33093        // typed `Placement` verbatim as a `&Placement` reference over the
33094        // same backing storage the raw `&self.placement` field access
33095        // borrows from, byte-equal across every representative fixture in
33096        // the accept-set — the default `Placement` (the substrate seed
33097        // shape whose [`PlacementStrategy::default`] evaluates to
33098        // `SingleNode` with an empty `:clusters` pool and both
33099        // optional-scalar axes `None`), and every canonical strategy /
33100        // cluster-pool / optional-scalar combination the
33101        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
33102        // three [`PlacementStrategy`] variants — `SingleNode`,
33103        // `Replicated`, `Sharded` — cross-projected with a non-empty
33104        // `:clusters` pool and, on the `Sharded` arm, a non-empty
33105        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
33106        // canonical `three_member_spec` `Replicated` fixture's
33107        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
33108        //
33109        // Pins against a future silent detour that returned a fresh-
33110        // cloned `Placement` copy (which would type-check via a `Clone`
33111        // impl but silently break every downstream caller that relied on
33112        // the reference sharing the composite's backing identity), a
33113        // reference to an operator-resolved overlay (the future per-
33114        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
33115        // acknowledges — its resolution must land at exactly this
33116        // accessor body, not silently divert the raw slot away from a
33117        // second consumer), or an axis-shuffled projection (a future
33118        // detour that swapped `clusters` and `affinity` through the
33119        // accessor would silently split the paired `validate_placement`
33120        // per-axis bracket-dispatch's traversal input from the peer
33121        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
33122        // programs.yaml distribution-annotation emitter's fan-out input
33123        // from the peer `feira app graph` per-Aplicacao print line's
33124        // input).
33125        //
33126        // Peer of the sibling M3
33127        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
33128        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
33129        // outer mesh-policy composite-reference axis, and of the sibling
33130        // slice-return `aplicacao_spec_membros_returns_membros_slice_
33131        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
33132        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
33133        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
33134        // the outer-accessor byte-equal-projection discipline onto the
33135        // outermost M3 mesh-slot type's per-Aplicacao distribution
33136        // composite-reference axis, the second `&Composite`-return
33137        // accessor on the outer [`AplicacaoSpec`] type.
33138        let fixtures: Vec<Placement> = vec![
33139            Placement::default(),
33140            Placement {
33141                estrategia: PlacementStrategy::SingleNode,
33142                clusters: vec!["rio".into()],
33143                affinity: None,
33144                shard_key: None,
33145            },
33146            Placement {
33147                estrategia: PlacementStrategy::Replicated,
33148                clusters: vec!["rio".into(), "mar".into()],
33149                affinity: None,
33150                shard_key: None,
33151            },
33152            Placement {
33153                estrategia: PlacementStrategy::Replicated,
33154                clusters: vec!["rio".into(), "mar".into()],
33155                affinity: Some("data-locality".into()),
33156                shard_key: None,
33157            },
33158            Placement {
33159                estrategia: PlacementStrategy::Sharded,
33160                clusters: vec!["rio".into(), "mar".into()],
33161                affinity: None,
33162                shard_key: Some("tenantId".into()),
33163            },
33164            Placement {
33165                estrategia: PlacementStrategy::Sharded,
33166                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
33167                affinity: Some("low-latency".into()),
33168                shard_key: Some("metadata.tenantId".into()),
33169            },
33170        ];
33171        for placement in fixtures {
33172            let s = AplicacaoSpec {
33173                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
33174                contratos: Vec::new(),
33175                politicas: MeshPolicy::default(),
33176                placement: placement.clone(),
33177                entrada: None,
33178            };
33179            assert_eq!(
33180                *s.placement(),
33181                placement,
33182                "AplicacaoSpec::placement must return :placement verbatim \
33183                 (got {:?}, expected {:?})",
33184                s.placement(),
33185                placement,
33186            );
33187            assert!(
33188                std::ptr::eq(s.placement(), &s.placement),
33189                "AplicacaoSpec::placement accessor and &self.placement \
33190                 field access must borrow the same backing storage — the \
33191                 accessor is the substrate-primitive typed dispatch every \
33192                 downstream distribution-composite consumer must route \
33193                 through, and a reference-identity split would silently \
33194                 break every consumer that relied on the borrow sharing \
33195                 the composite's storage",
33196            );
33197            assert_eq!(
33198                s.placement().estrategia(),
33199                s.placement.estrategia,
33200                "AplicacaoSpec::placement().estrategia() must byte-equal \
33201                 self.placement.estrategia — a strategy-drift would \
33202                 silently split the paired `validate_placement` \
33203                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
33204                 peer caixa-mesh programs.yaml `placement.estrategia` \
33205                 emitter's key from the peer `feira app graph` printer's \
33206                 strategy label",
33207            );
33208            assert_eq!(
33209                s.placement().clusters(),
33210                s.placement.clusters.as_slice(),
33211                "AplicacaoSpec::placement().clusters() must byte-equal \
33212                 self.placement.clusters — a cluster-pool drift would \
33213                 silently split the paired `validate_placement` \
33214                 pre-flight `.is_empty()` refusal probe's traversal from \
33215                 the peer caixa-mesh programs.yaml `placement.clusters` \
33216                 emitter's fan-out from the peer `feira app graph` \
33217                 printer's cluster list",
33218            );
33219        }
33220    }
33221
33222    #[test]
33223    fn validate_placement_reads_through_lifted_placement_accessor() {
33224        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
33225        // per-axis bracket-dispatch seed (`let p = self.placement();`,
33226        // followed by the per-axis fan-out `p.clusters()` /
33227        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
33228        // lifted axis-level accessor family) must key off the lifted
33229        // outer accessor, so any future rebrand on the typed slot's
33230        // outer-composite reader shape lands at exactly one place. Pins
33231        // the multi-axis coherence by exercising each per-axis refusal
33232        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
33233        // `:clusters` pool under the outer accessor's reference
33234        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
33235        // strategy with a `None` `:shard-key` under the same projection,
33236        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
33237        // with a `Some` `:shard-key` under the same projection, and
33238        // (4) the canonical `three_member_spec` `Replicated` fixture
33239        // passes `validate_placement` under the outer accessor's
33240        // reference projection — the accessor's reference-projection
33241        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
33242        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
33243        // without silently short-circuiting any.
33244        //
33245        // Peer of the sibling M3
33246        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
33247        // (534dc21) multi-axis coherence pin on the per-`:politicas`
33248        // outer mesh-policy composite-reference axis — extends the
33249        // multi-consumer coherence discipline onto the outermost M3
33250        // mesh-slot type's per-Aplicacao distribution composite-
33251        // reference axis, the second `&Composite`-return accessor on
33252        // the outer [`AplicacaoSpec`] type.
33253
33254        // (1) `PlacementWithoutClusters` refusal under the outer
33255        // accessor's reference projection: an empty `:clusters` pool
33256        // must trip the pre-flight refusal probe. The bracket-dispatch's
33257        // first arm reads `p.clusters()` on the reference returned by
33258        // the outer accessor.
33259        let mut spec = three_member_spec();
33260        spec.placement.clusters = Vec::new();
33261        assert_eq!(
33262            spec.validate().unwrap_err(),
33263            AplicacaoError::PlacementWithoutClusters {
33264                estrategia: PlacementStrategy::Replicated,
33265            },
33266        );
33267        assert!(
33268            std::ptr::eq(spec.placement(), &spec.placement),
33269            "the `validate_placement` per-axis bracket-dispatch's \
33270             traversal input must be the same backing composite the \
33271             accessor's reference projection borrows from",
33272        );
33273
33274        // (2) `ShardedWithoutKey` refusal under the outer accessor's
33275        // reference projection: a `Sharded` strategy with a `None`
33276        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
33277        // The bracket-dispatch's third arm reads `p.estrategia()` for
33278        // the match scrutinee then `p.shard_key()` for the cascade
33279        // scrutinee, both on the reference returned by the outer
33280        // accessor.
33281        let mut spec = three_member_spec();
33282        spec.placement.estrategia = PlacementStrategy::Sharded;
33283        spec.placement.shard_key = None;
33284        assert_eq!(
33285            spec.validate().unwrap_err(),
33286            AplicacaoError::ShardedWithoutKey,
33287        );
33288
33289        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
33290        // reference projection: a non-`Sharded` strategy with a `Some`
33291        // `:shard-key` must trip the declared-but-inert refusal. The
33292        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
33293        // + `p.estrategia()` for the diagnostic on the reference
33294        // returned by the outer accessor.
33295        let mut spec = three_member_spec();
33296        spec.placement.estrategia = PlacementStrategy::Replicated;
33297        spec.placement.shard_key = Some("tenantId".into());
33298        assert_eq!(
33299            spec.validate().unwrap_err(),
33300            AplicacaoError::ShardKeyOnNonSharded {
33301                estrategia: PlacementStrategy::Replicated,
33302                shard_key: "tenantId".into(),
33303            },
33304        );
33305
33306        // (4) Canonical `three_member_spec` `Replicated` fixture passes
33307        // `validate_placement` — every per-axis arm reaches the fall-
33308        // through `Ok(())` without any per-axis refusal firing under the
33309        // outer accessor's reference projection.
33310        let spec = three_member_spec();
33311        assert!(
33312            spec.validate().is_ok(),
33313            "the canonical Replicated placement fixture must pass \
33314             `validate_placement` — every per-axis arm short-circuits on \
33315             valid input under the outer accessor's reference projection",
33316        );
33317        assert_eq!(
33318            spec.placement().estrategia(),
33319            PlacementStrategy::Replicated,
33320            "the outer accessor's reference projection must be the \
33321             canonical Replicated fixture's strategy",
33322        );
33323        assert_eq!(
33324            spec.placement().clusters(),
33325            &["rio", "mar"],
33326            "the outer accessor's reference projection must be the \
33327             canonical Replicated fixture's cluster pool",
33328        );
33329    }
33330
33331    #[test]
33332    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
33333        // The canonical per-`:entrada` outer-composite-optional-
33334        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
33335        // the `:entrada` typed `Option<Entrada>` verbatim as an
33336        // `Option<&Entrada>` reference over the same backing storage
33337        // the raw `self.entrada.as_ref()` field access borrows from,
33338        // byte-equal across every representative fixture in the
33339        // accept-set — the author-omitted `None` shape (the
33340        // "internal-only mesh" partition every downstream external-
33341        // gateway emitter treats as "emit nothing"), the minimal
33342        // singleton `:entrada` composite (host + destination + empty
33343        // paths + default port), the paths-carrying composite (the
33344        // canonical `three_member_spec` fixture's ["/api" "/health"]
33345        // path-list shape every HTTPRoute per-rule fan-out emitter
33346        // reads), and the non-default port composite (the canonical
33347        // custom-port shape the port-fallback resolver reads).
33348        //
33349        // Pins against a future silent detour that returned a fresh-
33350        // cloned `Entrada` copy (which would type-check via a `Clone`
33351        // impl but silently break every downstream caller that
33352        // relied on the reference sharing the composite's backing
33353        // identity), a reference to an operator-resolved overlay
33354        // (the future per-cluster `:entrada-overrides` slot the
33355        // MESH-COMPOSITION §V federation roadmap acknowledges — its
33356        // resolution must land at exactly this accessor body, not
33357        // silently divert the raw slot away from a second consumer),
33358        // a `None` → `Some(Entrada::default)` cluster-default
33359        // projection (which would collapse the load-bearing
33360        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
33361        // the peer `gateway_routes` early-return + `feira app graph`
33362        // internal-only-mesh partition both read), or an axis-
33363        // shuffled projection (a future detour that swapped
33364        // `host` and `para` through the accessor would silently
33365        // split the paired `validate` per-`:entrada` shape-and-
33366        // membership gate's traversal input from the peer
33367        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
33368        // fan-out input from the peer `feira app graph` external-
33369        // gateway summary line).
33370        //
33371        // Peer of the sibling M3
33372        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
33373        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
33374        // `:politicas` outer mesh-policy composite-reference axis
33375        // and of the sibling M3
33376        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
33377        // (9abb8f0) `&Placement` byte-equal pin on the per-
33378        // `:placement` outer distribution-composite composite-
33379        // reference axis — extends the outer-accessor byte-equal-
33380        // projection discipline onto the last unlifted outermost M3
33381        // mesh-slot type's per-Aplicacao external-gateway composite-
33382        // reference axis, the third and final `&Composite`-return
33383        // accessor on the outer [`AplicacaoSpec`] type.
33384        let fixtures: Vec<Option<Entrada>> = vec![
33385            None,
33386            Some(Entrada {
33387                host: "checkout.quero.cloud".into(),
33388                para: "cart".into(),
33389                paths: Vec::new(),
33390                port: DEFAULT_SERVICO_PORT,
33391            }),
33392            Some(Entrada {
33393                host: "checkout.quero.cloud".into(),
33394                para: "cart".into(),
33395                paths: vec!["/api".into(), "/health".into()],
33396                port: DEFAULT_SERVICO_PORT,
33397            }),
33398            Some(Entrada {
33399                host: "checkout.quero.cloud".into(),
33400                para: "cart".into(),
33401                paths: vec!["/api".into()],
33402                port: 9443,
33403            }),
33404        ];
33405        for entrada in fixtures {
33406            let s = AplicacaoSpec {
33407                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
33408                contratos: Vec::new(),
33409                politicas: MeshPolicy::default(),
33410                placement: Placement::default(),
33411                entrada: entrada.clone(),
33412            };
33413            assert_eq!(
33414                s.entrada(),
33415                entrada.as_ref(),
33416                "AplicacaoSpec::entrada must return :entrada verbatim \
33417                 (got {:?}, expected {:?})",
33418                s.entrada(),
33419                entrada.as_ref(),
33420            );
33421            match (s.entrada(), s.entrada.as_ref()) {
33422                (Some(a), Some(b)) => assert!(
33423                    std::ptr::eq(a, b),
33424                    "AplicacaoSpec::entrada accessor and \
33425                     self.entrada.as_ref() field access must borrow \
33426                     the same backing storage — the accessor is the \
33427                     substrate-primitive typed dispatch every \
33428                     downstream external-gateway composite consumer \
33429                     must route through, and a reference-identity \
33430                     split would silently break every consumer that \
33431                     relied on the borrow sharing the composite's \
33432                     storage",
33433                ),
33434                (None, None) => {}
33435                _ => panic!(
33436                    "AplicacaoSpec::entrada presence bit must byte-\
33437                     equal self.entrada.is_some() — a presence-bit \
33438                     drift would silently split the paired `validate` \
33439                     per-`:entrada` shape-and-membership gate's \
33440                     traversal head from the peer \
33441                     caixa-mesh gateway_routes early-return partition \
33442                     from the peer `feira app graph` internal-only-\
33443                     mesh partition",
33444                ),
33445            }
33446            assert_eq!(
33447                s.entrada().is_some(),
33448                s.entrada.is_some(),
33449                "AplicacaoSpec::entrada().is_some() must byte-equal \
33450                 self.entrada.is_some() — a presence-bit drift would \
33451                 silently split every downstream `Option<&Entrada>` \
33452                 consumer's partition on the internal-only-mesh arm",
33453            );
33454        }
33455    }
33456
33457    #[test]
33458    fn validate_reads_through_lifted_entrada_accessor() {
33459        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
33460        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
33461        // self.entrada() { … }`, followed by the per-axis fan-out
33462        // `validate_entrada_para(&e.para)` /
33463        // `EntradaMemberMissing` membership lookup /
33464        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
33465        // per-`e.paths` `validate_entrada_path` traversal) must key
33466        // off the lifted outer accessor, so any future rebrand on
33467        // the typed slot's outer-composite reader shape lands at
33468        // exactly one place. Pins the multi-axis coherence by
33469        // exercising each per-axis refusal end-to-end: (1) the
33470        // author-omitted `None` shape short-circuits past every
33471        // per-`:entrada` refusal (the internal-only mesh partition
33472        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
33473        // fires on a well-shaped but phantom `:para` under the outer
33474        // accessor's reference projection, and (3) the canonical
33475        // `three_member_spec` `:entrada` fixture passes `validate`
33476        // under the outer accessor's reference projection.
33477        //
33478        // Peer of the sibling M3
33479        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
33480        // (534dc21) multi-axis coherence pin on the per-`:politicas`
33481        // outer mesh-policy composite-reference axis and the sibling
33482        // M3
33483        // [`validate_placement_reads_through_lifted_placement_accessor`]
33484        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
33485        // outer distribution-composite composite-reference axis —
33486        // extends the multi-consumer coherence discipline onto the
33487        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
33488        // external-gateway composite-reference axis, the third and
33489        // final `&Composite`-return accessor on the outer
33490        // [`AplicacaoSpec`] type.
33491
33492        // (1) `None` :entrada — the internal-only-mesh partition
33493        // short-circuits past every per-`:entrada` refusal. The outer
33494        // accessor's reference projection reaches the fall-through
33495        // `Ok(())` on the `None` arm without any per-axis refusal
33496        // firing.
33497        let mut spec = three_member_spec();
33498        spec.entrada = None;
33499        assert!(
33500            spec.validate().is_ok(),
33501            "an author-omitted `:entrada` must pass `validate` — the \
33502             internal-only-mesh partition short-circuits past every \
33503             per-`:entrada` refusal under the outer accessor's \
33504             reference projection",
33505        );
33506        assert!(
33507            spec.entrada().is_none(),
33508            "the outer accessor's reference projection must name the \
33509             internal-only-mesh partition per the `None` fixture",
33510        );
33511
33512        // (2) `EntradaMemberMissing` refusal under the outer accessor's
33513        // reference projection: a well-shaped but phantom `:para` must
33514        // trip the membership-lookup refusal. The gate's second arm
33515        // reads `e.para` on the reference returned by the outer
33516        // accessor.
33517        let mut spec = three_member_spec();
33518        if let Some(e) = spec.entrada.as_mut() {
33519            e.para = "phantom".into();
33520        }
33521        assert_eq!(
33522            spec.validate().unwrap_err(),
33523            AplicacaoError::EntradaMemberMissing {
33524                para: "phantom".into(),
33525            },
33526        );
33527        match (spec.entrada(), spec.entrada.as_ref()) {
33528            (Some(a), Some(b)) => assert!(
33529                std::ptr::eq(a, b),
33530                "the `validate` per-`:entrada` gate's traversal head \
33531                 must be the same backing composite the accessor's \
33532                 reference projection borrows from",
33533            ),
33534            _ => panic!("fixture must carry Some(:entrada)"),
33535        }
33536
33537        // (3) Canonical `three_member_spec` `:entrada` fixture passes
33538        // `validate` — every per-axis arm reaches the fall-through
33539        // `Ok(())` without any per-axis refusal firing under the
33540        // outer accessor's reference projection.
33541        let spec = three_member_spec();
33542        assert!(
33543            spec.validate().is_ok(),
33544            "the canonical `:entrada` fixture must pass `validate` — \
33545             every per-axis arm short-circuits on valid input under \
33546             the outer accessor's reference projection",
33547        );
33548        assert!(
33549            spec.entrada().is_some(),
33550            "the outer accessor's reference projection must be the \
33551             canonical `:entrada` fixture's composite",
33552        );
33553    }
33554
33555    #[test]
33556    fn membro_names_matches_inline_membros_projection() {
33557        // Substrate-primitive ≡ inline-projection pin on
33558        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
33559        // must be byte-for-byte the set the pre-lift inline
33560        // `self.membros().iter().map(Membro::nome).collect()` builder
33561        // produced, on every membership shape the three
33562        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
33563        // :para`, `:entrada :para`) resolve against. Pins the
33564        // projection so a future rebrand of the node-identity axis
33565        // lands at the primitive rather than diverging between the
33566        // per-`:contratos` membership arms still inline at `validate`
33567        // and the lifted `validate_entrada` gate.
33568        for membros in [
33569            vec![],
33570            vec![membro("cart", "^0.1")],
33571            vec![
33572                membro("catalog", "^0.1"),
33573                membro("cart", "^0.1"),
33574                membro("payment", "^0.2"),
33575            ],
33576        ] {
33577            let mut spec = three_member_spec();
33578            spec.membros = membros;
33579            let inline: std::collections::HashSet<&str> =
33580                spec.membros().iter().map(Membro::nome).collect();
33581            assert_eq!(
33582                spec.membro_names(),
33583                inline,
33584                "the lifted membership oracle must discriminate the \
33585                 same node set as the pre-lift inline projection",
33586            );
33587        }
33588    }
33589
33590    #[test]
33591    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
33592        // Per-slot-gate ≡ validate equivalence pin on the lifted
33593        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
33594        // must discriminate the same set as [`AplicacaoSpec::validate`]
33595        // on every `:entrada`-covered input, so a future consumer that
33596        // re-validates the one slot (the M4 admission webhook
33597        // re-checking `:entrada` after a gateway-host patch) accepts
33598        // exactly what `feira build` accepts and surfaces the same
33599        // diagnostic on the same input. Covers each of the five gated
33600        // axes plus the two clean-pass shapes (`None` — the
33601        // internal-only-mesh partition — and the canonical fixture).
33602        //
33603        // Peer of the sibling per-slot equivalence pins
33604        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
33605        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
33606        // `:politicas` slot's compound entry gate, extended here onto
33607        // the `:entrada` slot's newly-named per-slot gate.
33608        /// One `:entrada` equivalence case: a label, the per-axis
33609        /// mutation applied to the canonical fixture's composite, and
33610        /// the diagnostic both the per-slot gate and `validate` must
33611        /// surface on it (`None` = clean pass).
33612        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
33613
33614        let cases: &[EntradaCase] = &[
33615            (
33616                ":para shape — empty",
33617                |e| e.para = String::new(),
33618                Some(AplicacaoError::EntradaParaEmpty),
33619            ),
33620            (
33621                ":para membership — well-shaped phantom",
33622                |e| e.para = "phantom".into(),
33623                Some(AplicacaoError::EntradaMemberMissing {
33624                    para: "phantom".into(),
33625                }),
33626            ),
33627            (
33628                ":host emptiness",
33629                |e| e.host = String::new(),
33630                Some(AplicacaoError::EmptyEntradaHost),
33631            ),
33632            (
33633                ":port structural floor",
33634                |e| e.port = 0,
33635                Some(AplicacaoError::EntradaPortZero),
33636            ),
33637            (
33638                ":paths per-entry emptiness",
33639                |e| e.paths = vec![String::new()],
33640                Some(AplicacaoError::EntradaPathEmpty),
33641            ),
33642            (
33643                ":paths leading-slash grammar",
33644                |e| e.paths = vec!["api/cart".into()],
33645                Some(AplicacaoError::EntradaPathNotAbsolute {
33646                    path: "api/cart".into(),
33647                }),
33648            ),
33649            (
33650                ":paths set-not-multiset",
33651                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
33652                Some(AplicacaoError::EntradaPathDuplicate {
33653                    path: "/api/cart".into(),
33654                }),
33655            ),
33656            ("clean pass — canonical fixture", |_| {}, None),
33657        ];
33658        for (label, mutate, expected) in cases {
33659            let mut spec = three_member_spec();
33660            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
33661            assert_eq!(
33662                spec.validate_entrada().err(),
33663                *expected,
33664                "per-slot gate disagreed with the expected diagnostic on {label}",
33665            );
33666            assert_eq!(
33667                spec.validate().err(),
33668                *expected,
33669                "`validate` disagreed with the per-slot gate on {label}",
33670            );
33671        }
33672
33673        // The `None` arm is the internal-only-mesh partition: a clean
33674        // pass through both the per-slot gate and `validate`, not a
33675        // refusal.
33676        let mut spec = three_member_spec();
33677        spec.entrada = None;
33678        assert_eq!(spec.validate_entrada().err(), None);
33679        assert_eq!(spec.validate().err(), None);
33680    }
33681
33682    #[test]
33683    fn validate_entrada_resolves_membership_through_own_oracle() {
33684        // Self-containment pin on the lifted per-slot gate:
33685        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
33686        // against the oracle *it* builds through
33687        // [`AplicacaoSpec::membro_names`], not one threaded down from
33688        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
33689        // longer contains the `:entrada :para` target must trip
33690        // `EntradaMemberMissing` when the per-slot gate is called
33691        // directly — the shape a future single-slot re-validator
33692        // (the M4 admission webhook) reaches the axis through, without
33693        // re-walking `:membros` / `:contratos` / the sync-cycle
33694        // detector first. Same self-contained posture
33695        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
33696        // the M4 per-edge policy resolver.
33697        let mut spec = three_member_spec();
33698        spec.membros.retain(|m| m.nome() != "cart");
33699        assert_eq!(
33700            spec.validate_entrada().unwrap_err(),
33701            AplicacaoError::EntradaMemberMissing {
33702                para: "cart".into(),
33703            },
33704            "the per-slot gate must resolve `:para` against the oracle \
33705             it builds itself, with no membership set threaded in",
33706        );
33707        assert!(
33708            !spec.membro_names().contains("cart"),
33709            "fixture must have dropped the `:entrada :para` target \
33710             from the graph's node set",
33711        );
33712    }
33713
33714    #[test]
33715    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
33716        // Per-slot-gate ≡ validate equivalence pin on the lifted
33717        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
33718        // gate must discriminate the same set as
33719        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
33720        // input, so a future consumer that re-validates the one slot
33721        // (the M4 admission webhook re-checking `:contratos` after a
33722        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
33723        // `:politicas` override MESH-COMPOSITION §III.2 #3
33724        // acknowledges — which resolves an effective per-edge
33725        // [`MeshPolicy`] and must re-check the edge's identity closure
33726        // before it can key a per-edge override off the endpoint
33727        // tuple) accepts exactly what `feira build` accepts and
33728        // surfaces the same diagnostic on the same input. Covers each
33729        // of the six gated axes (`:de`/`:para` per-arm shape,
33730        // per-arm graph-membership, structural self-loop, `:wit`
33731        // emptiness) plus the clean-pass canonical fixture; the
33732        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
33733        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
33734        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
33735        // `target:` carriers depend on library implementation
33736        // details are pinned separately below with a `matches!`
33737        // predicate on the arm identity plus the mirror equivalence
33738        // between the two entry points.
33739        //
33740        // Peer of the sibling per-slot equivalence pins
33741        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
33742        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
33743        // `:politicas` slot's compound entry gate, and
33744        // `validate_entrada_matches_gate_on_every_per_axis_shape`
33745        // (20cd523) on the `:entrada` slot's per-slot gate — extended
33746        // here onto the `:contratos` slot's newly-named per-slot gate,
33747        // closing the last unlifted per-slot gate on the M3 mesh-slot
33748        // family.
33749        /// One `:contratos` equivalence case: a label, the per-axis
33750        /// mutation applied to the canonical fixture's spec, and the
33751        /// diagnostic both the per-slot gate and `validate` must
33752        /// surface on it (`None` = clean pass).
33753        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
33754
33755        let cases: &[ContratoCase] = &[
33756            (
33757                ":de shape — empty",
33758                |s| s.contratos[0].de = String::new(),
33759                Some(AplicacaoError::ContratoCaixaEmpty {
33760                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
33761                }),
33762            ),
33763            (
33764                ":para shape — empty",
33765                |s| s.contratos[0].para = String::new(),
33766                Some(AplicacaoError::ContratoCaixaEmpty {
33767                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
33768                }),
33769            ),
33770            (
33771                ":de membership — well-shaped phantom",
33772                |s| s.contratos[0].de = "phantom".into(),
33773                Some(AplicacaoError::ContratoMemberMissing {
33774                    caixa: "phantom".into(),
33775                }),
33776            ),
33777            (
33778                ":para membership — well-shaped phantom",
33779                |s| s.contratos[0].para = "phantom".into(),
33780                Some(AplicacaoError::ContratoMemberMissing {
33781                    caixa: "phantom".into(),
33782                }),
33783            ),
33784            (
33785                "structural self-loop",
33786                |s| s.contratos[0].para = "cart".into(),
33787                Some(AplicacaoError::ContratoSelfLoop {
33788                    caixa: "cart".into(),
33789                    wit: "wasi:http/proxy".into(),
33790                }),
33791            ),
33792            (
33793                ":wit emptiness",
33794                |s| s.contratos[0].wit = String::new(),
33795                Some(AplicacaoError::EmptyWit {
33796                    de: "cart".into(),
33797                    para: "catalog".into(),
33798                }),
33799            ),
33800            ("clean pass — canonical fixture", |_| {}, None),
33801        ];
33802        for (label, mutate, expected) in cases {
33803            let mut spec = three_member_spec();
33804            mutate(&mut spec);
33805            assert_eq!(
33806                spec.validate_contratos().err(),
33807                *expected,
33808                "per-slot gate disagreed with the expected diagnostic on {label}",
33809            );
33810            assert_eq!(
33811                spec.validate().err(),
33812                *expected,
33813                "`validate` disagreed with the per-slot gate on {label}",
33814            );
33815        }
33816    }
33817
33818    #[test]
33819    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
33820        // Companion pin to
33821        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
33822        // the per-slot gate ≡ `validate` equivalence on the three
33823        // `:contratos` refusal arms whose diagnostic carries a
33824        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
33825        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
33826        // `is_dns_1123_label` / `WitContract::target` shape helpers,
33827        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
33828        // library-formatted `target:` scalar). Value equality between
33829        // the per-slot gate and `validate` outputs pins the full
33830        // `Option<AplicacaoError>` (including reason-strings), and the
33831        // per-arm `matches!` predicate pins the arm-discriminator
33832        // identity on the specific `Contrato*` variant. Split from
33833        // the primary equivalence pin so each pin body stays under
33834        // [`clippy::too_many_lines`], the same shape the peer
33835        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
33836        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
33837        // carries on the `:politicas` slot's compound entry gate.
33838        type ContratoReasonCase = (
33839            &'static str,
33840            fn(&mut AplicacaoSpec),
33841            fn(&AplicacaoError) -> bool,
33842        );
33843        let cases: &[ContratoReasonCase] = &[
33844            (
33845                ":de shape — DNS-1123 invalid",
33846                |s| s.contratos[0].de = "Cart".into(),
33847                |err| {
33848                    matches!(
33849                        err,
33850                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
33851                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
33852                    )
33853                },
33854            ),
33855            (
33856                ":wit target-shape mismatch — payload on capability arm",
33857                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
33858                |err| {
33859                    matches!(
33860                        err,
33861                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
33862                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
33863                    )
33864                },
33865            ),
33866            (
33867                "whole-edge dedup — six-axis identity collision",
33868                |s| {
33869                    let dup = s.contratos[0].clone();
33870                    s.contratos.push(dup);
33871                },
33872                |err| {
33873                    matches!(
33874                        err,
33875                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
33876                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
33877                    )
33878                },
33879            ),
33880        ];
33881        for (label, mutate, arm_matches) in cases {
33882            let mut spec = three_member_spec();
33883            mutate(&mut spec);
33884            let per_slot = spec.validate_contratos().err();
33885            let gate = spec.validate().err();
33886            assert_eq!(
33887                per_slot, gate,
33888                "per-slot gate and `validate` must return byte-equal \
33889                 `Option<AplicacaoError>` on {label} (including \
33890                 library-owned reason strings)",
33891            );
33892            let err = per_slot
33893                .as_ref()
33894                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
33895            assert!(
33896                arm_matches(err),
33897                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
33898            );
33899        }
33900    }
33901
33902    #[test]
33903    fn validate_contratos_resolves_membership_through_own_oracle() {
33904        // Self-containment pin on the lifted per-slot gate:
33905        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
33906        // `:de` / `:para` against the oracle *it* builds through
33907        // [`AplicacaoSpec::membro_names`], not one threaded down from
33908        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
33909        // longer contains a `:contratos` edge's endpoint must trip
33910        // `ContratoMemberMissing` when the per-slot gate is called
33911        // directly — the shape a future single-slot re-validator
33912        // (the M4 admission webhook re-checking `:contratos` after a
33913        // per-`(:de, :para)` edge patch, the M4 per-edge policy
33914        // resolver on the `:politicas` override axis) reaches the
33915        // axis through, without re-walking `:membros` / `:entrada` /
33916        // `:placement` / `:politicas` first. Same self-contained
33917        // posture the peer per-slot gates
33918        // [`AplicacaoSpec::detect_sync_cycles`] and
33919        // [`AplicacaoSpec::validate_entrada`] already carry for the
33920        // same M4 consumers.
33921        let mut spec = three_member_spec();
33922        spec.membros.retain(|m| m.nome() != "catalog");
33923        assert_eq!(
33924            spec.validate_contratos().unwrap_err(),
33925            AplicacaoError::ContratoMemberMissing {
33926                caixa: "catalog".into(),
33927            },
33928            "the per-slot gate must resolve `:de` / `:para` against \
33929             the oracle it builds itself, with no membership set \
33930             threaded in",
33931        );
33932        assert!(
33933            !spec.membro_names().contains("catalog"),
33934            "fixture must have dropped the `:contratos` edge's \
33935             `:para` target from the graph's node set",
33936        );
33937    }
33938
33939    #[test]
33940    fn validate_contratos_folds_cycle_axis_matches_gate() {
33941        // Fold-into-per-slot-gate equivalence pin on the
33942        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
33943        // surfaces byte-equal through both
33944        // [`AplicacaoSpec::validate_contratos`] and
33945        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
33946        // a synchronous-edge cycle in `:contratos`. Pins the fold that
33947        // moved the cross-edge cycle axis onto the per-slot gate — a
33948        // future silent regression that de-folded the axis back to the
33949        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
33950        // a peer per-slot gate lift that skipped the cross-axis half of
33951        // the [`MeshPolicy::validate`]-analogous discipline) would
33952        // surface here as `Some(ContratoCycle)` from `validate` and
33953        // `None` from `validate_contratos`.
33954        //
33955        // Cycle fixture is the same shape as the peer
33956        // [`rejects_three_node_synchronous_cycle`] test carries: a
33957        // clean 3-cycle over the HTTP subgraph (catalog → cart →
33958        // payment → catalog), so the per-entry cascade (shape +
33959        // membership + self-loop + `:wit` emptiness + WIT-target +
33960        // whole-edge dedup) passes cleanly and the sole surviving
33961        // refusal shape is the cross-edge cycle axis. The `cycle`
33962        // vector is normalized to a sorted body set for the equality
33963        // compare (the traversal path's starting node depends on
33964        // BTreeMap iteration order, which is deterministic but is not
33965        // the load-bearing property this pin covers).
33966        //
33967        // Peer of the sibling per-slot ≡ `validate` equivalence pins
33968        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
33969        // (per-entry axes) and
33970        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
33971        // (parser-owned reason arms) already carry on the six
33972        // per-entry axes — this extends the discipline onto the
33973        // cross-edge cycle axis newly folded into the per-slot gate,
33974        // matching the peer per-slot compound gate
33975        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
33976        // both per-axis and cross-axis surfaces on `:politicas`.
33977        let mut spec = three_member_spec();
33978        spec.contratos = vec![
33979            contract_http("catalog", "cart", "/x"),
33980            contract_http("cart", "payment", "/y"),
33981            contract_http("payment", "catalog", "/z"),
33982        ];
33983        let per_slot_err = spec.validate_contratos().unwrap_err();
33984        let gate_err = spec.validate().unwrap_err();
33985        assert_eq!(
33986            per_slot_err, gate_err,
33987            "the per-slot gate and `validate` must return byte-equal \
33988             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
33989             — the fold pins the cross-edge axis onto the per-slot \
33990             gate the same way the peer `validate_politicas` fold \
33991             pinned the `:politicas` cross-axis surface",
33992        );
33993        match per_slot_err {
33994            AplicacaoError::ContratoCycle { ref cycle } => {
33995                assert_eq!(
33996                    cycle.first(),
33997                    cycle.last(),
33998                    "cycle traversal must close on the back-edge \
33999                     target — the diagnostic shape the peer \
34000                     `rejects_three_node_synchronous_cycle` pins",
34001                );
34002                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
34003                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
34004                assert!(body.contains("cart"));
34005                assert!(body.contains("catalog"));
34006                assert!(body.contains("payment"));
34007            }
34008            other => panic!("expected ContratoCycle, got {other:?}"),
34009        }
34010    }
34011
34012    #[test]
34013    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
34014        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
34015        // carrying *both* a per-entry defect (a self-loop, the
34016        // structural-self-edge arm on the per-entry cascade — chosen
34017        // because it never masks or is masked by the cycle diagnostic
34018        // on the peer arms) *and* a would-be synchronous-edge cycle in
34019        // the remaining edges must surface the per-entry diagnostic
34020        // first through both [`AplicacaoSpec::validate_contratos`] and
34021        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
34022        // per-entry-before-cross-edge dispatch ordering, byte-equal to
34023        // the pre-fold `validate`-side sequence
34024        // (`validate_contratos()? → detect_sync_cycles()?`) the
34025        // dispatch encoded verbatim. A silent regression that reversed
34026        // the ordering inside the fold would surface here as a cycle
34027        // diagnostic on a fixture carrying an earlier per-entry defect
34028        // — masking the narrower "this edge is degenerate" arm behind
34029        // the coarser "this graph deadlocks" arm.
34030        //
34031        // Peer of the diagnostic-ordering property the pre-fold
34032        // dispatch encoded at the [`AplicacaoSpec::validate`]
34033        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
34034        // now enforced inside the per-slot gate's own body, so a future
34035        // consumer that reaches only the per-slot gate (the M4
34036        // admission webhook re-checking `:contratos` after a per-edge
34037        // patch) inherits the ordering property by construction.
34038        let mut spec = three_member_spec();
34039        // The three-member fixture already has cart → catalog and
34040        // cart → payment; adding catalog → cart closes a 2-cycle on
34041        // the HTTP subgraph.
34042        spec.contratos
34043            .push(contract_http("catalog", "cart", "/refresh"));
34044        // Add a self-loop on `payment` — the per-entry structural-
34045        // self-edge arm — which must surface first.
34046        spec.contratos
34047            .push(contract_http("payment", "payment", "/loop"));
34048        let per_slot_err = spec.validate_contratos().unwrap_err();
34049        let gate_err = spec.validate().unwrap_err();
34050        assert_eq!(
34051            per_slot_err, gate_err,
34052            "per-slot gate and `validate` must agree on the ordering \
34053             fixture's surfaced diagnostic — a divergence here means \
34054             the fold reshaped one dispatch's ordering without the \
34055             other",
34056        );
34057        assert!(
34058            matches!(
34059                per_slot_err,
34060                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
34061                    if caixa == "payment"
34062            ),
34063            "the per-entry structural-self-edge arm must fire before \
34064             the cross-edge cycle arm — pinning the fold's per-entry-\
34065             before-cross-edge dispatch ordering byte-equal to the \
34066             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
34067             sequence; got {per_slot_err:?}",
34068        );
34069    }
34070
34071    #[test]
34072    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
34073        // Self-containment pin on the folded cross-edge cycle axis:
34074        // [`AplicacaoSpec::validate_contratos`] surfaces
34075        // [`AplicacaoError::ContratoCycle`] directly against `&self`
34076        // without depending on the peer per-slot gates
34077        // ([`AplicacaoSpec::validate_membros`],
34078        // [`AplicacaoSpec::validate_entrada`],
34079        // [`AplicacaoSpec::validate_placement`],
34080        // [`AplicacaoSpec::validate_politicas`]) running first — the
34081        // shape a future single-slot re-validator (the M4 admission
34082        // webhook re-checking `:contratos` after a per-`(:de, :para)`
34083        // edge patch, the per-edge policy resolver MESH-COMPOSITION
34084        // §III.2 #3 acknowledges) reaches *both* structural axes on
34085        // the slot through one call. A spec with a per-`:politicas`
34086        // refusal shape (zero `:timeout`, the first per-axis arm the
34087        // peer [`MeshPolicy::validate`] gate covers) AND a
34088        // synchronous-edge cycle in `:contratos` must:
34089        //
34090        //   - surface [`AplicacaoError::ContratoCycle`] through the
34091        //     per-slot gate `validate_contratos` directly (proves the
34092        //     cycle axis reaches the per-slot altitude without the
34093        //     peer `:politicas` gate running first);
34094        //   - surface [`AplicacaoError::ContratoCycle`] through
34095        //     `validate` (which reaches `validate_contratos` before
34096        //     `validate_politicas` per the fixed dispatch order), so
34097        //     the fold's cross-slot ordering (`:membros` →
34098        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
34099        //     is byte-equal to the pre-fold dispatch's ordering.
34100        //
34101        // Same self-contained-on-`&self` posture the peer per-slot
34102        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
34103        // [`AplicacaoSpec::validate_contratos`] per-entry axis
34104        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
34105        // (f03a154) already carry — extended here onto the newly-
34106        // folded cross-edge cycle axis. Peer of the sibling per-slot
34107        // self-containment pins
34108        // `validate_entrada_resolves_membership_through_own_oracle`
34109        // and `validate_contratos_resolves_membership_through_own_oracle`
34110        // on the per-entry membership axis — extends the discipline
34111        // onto the cross-edge cycle axis of the same per-slot gate.
34112        let mut spec = three_member_spec();
34113        // Poison `:politicas` — zero-`:timeout` trips the first per-
34114        // axis arm the [`MeshPolicy::validate`] gate covers, so any
34115        // dispatch that reached `:politicas` would surface a
34116        // `:politicas` diagnostic instead of `ContratoCycle`.
34117        spec.politicas.timeout = Some(Duration::from_secs(0));
34118        // Close a synchronous-edge cycle on the HTTP subgraph.
34119        spec.contratos
34120            .push(contract_http("catalog", "cart", "/refresh"));
34121        let per_slot_err = spec.validate_contratos().unwrap_err();
34122        assert!(
34123            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
34124            "the per-slot gate must surface `ContratoCycle` directly \
34125             against `&self` — a peer per-slot gate's regression \
34126             would surface a non-`ContratoCycle` diagnostic here; \
34127             got {per_slot_err:?}",
34128        );
34129        let gate_err = spec.validate().unwrap_err();
34130        assert!(
34131            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
34132            "`validate`'s five-slot dispatch must reach the fold's \
34133             cross-edge cycle axis on `:contratos` before the peer \
34134             `:politicas` gate — a dispatch-order regression would \
34135             surface a `:politicas` diagnostic here; got {gate_err:?}",
34136        );
34137        // Sanity: the poisoned `:politicas` alone would trip
34138        // [`MeshPolicy::validate`] under the peer per-slot gate, so
34139        // the cycle-first surfacing above is a real ordering property,
34140        // not a case where the `:politicas` axis silently accepts the
34141        // fixture.
34142        let mut politicas_only = three_member_spec();
34143        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
34144        assert!(
34145            politicas_only.validate_politicas().is_err(),
34146            "the poisoned `:politicas` fixture must trip the peer \
34147             per-slot gate on its own — otherwise the self-contained \
34148             cycle-first surfacing above would not be an ordering \
34149             property",
34150        );
34151    }
34152
34153    #[test]
34154    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
34155        // Fail-before-pass-after equivalence pin on the lifted
34156        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
34157        // both arms (`:de` phantom and `:para` phantom) must fire the
34158        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
34159        // `caixa` carrier byte-equal to the offending accessor's
34160        // projection, and `:de` must fire before `:para` when both
34161        // arms would trip on the same call — preserving the canonical
34162        // edge-direction order the peer per-arm shape gate
34163        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
34164        // diagnostic, and every peer per-arm ordering in
34165        // [`AplicacaoSpec::validate_contratos`] already carry.
34166        //
34167        // Two-endpoint oracle covers exactly enough graph nodes to
34168        // exercise each arm in isolation: the `:de` arm fires when
34169        // the source is off-oracle and the destination is on-oracle,
34170        // the `:para` arm fires when the source is on-oracle and the
34171        // destination is off-oracle, and the `:de`-before-`:para`
34172        // ordering falls out from a probe where *both* endpoints are
34173        // off-oracle — the diagnostic's `caixa` field must byte-equal
34174        // the source, not the destination, pinning the primitive's
34175        // arm ordering as `:de` first.
34176        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
34177        names.insert("cart");
34178        names.insert("catalog");
34179
34180        // `:de` phantom, `:para` on-oracle
34181        let de_phantom = contract_http("phantom-de", "catalog", "/x");
34182        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
34183        assert_eq!(
34184            err,
34185            AplicacaoError::ContratoMemberMissing {
34186                caixa: de_phantom.source().to_string(),
34187            },
34188            "the `:de` phantom arm must fire ContratoMemberMissing \
34189             with `caixa` byte-equal to `WitContract::source` — a \
34190             bypass here (a raw `.de.clone()` regression, a divergent \
34191             accessor on a per-CR alias table) would silently split \
34192             the primitive's diagnostic from the substrate-primitive \
34193             scalar accessor every downstream consumer routes through",
34194        );
34195
34196        // `:de` on-oracle, `:para` phantom
34197        let para_phantom = contract_http("cart", "phantom-para", "/x");
34198        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
34199        assert_eq!(
34200            err,
34201            AplicacaoError::ContratoMemberMissing {
34202                caixa: para_phantom.destination().to_string(),
34203            },
34204            "the `:para` phantom arm must fire ContratoMemberMissing \
34205             with `caixa` byte-equal to `WitContract::destination` — \
34206             symmetric callee-side pin to the `:de` arm above",
34207        );
34208
34209        // Both endpoints off-oracle: the `:de` arm must fire first,
34210        // pinning the primitive's canonical edge-direction order.
34211        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
34212        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
34213        assert_eq!(
34214            err,
34215            AplicacaoError::ContratoMemberMissing {
34216                caixa: both_phantom.source().to_string(),
34217            },
34218            "when both endpoints are off-oracle, the `:de` arm must \
34219             fire before the `:para` arm — preserving byte-equal \
34220             ordering with the pre-lift inline cascade in \
34221             `validate_contratos` and with every peer per-arm \
34222             ordering the sibling per-edge substrate primitives \
34223             already carry",
34224        );
34225
34226        // Both endpoints on-oracle: clean pass.
34227        let clean = contract_http("cart", "catalog", "/x");
34228        clean.require_endpoints_in(&names).unwrap();
34229    }
34230
34231    #[test]
34232    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
34233        // Convergence pin: the whole-spec end-to-end route through
34234        // [`AplicacaoSpec::validate_contratos`] must reach the
34235        // per-edge substrate primitive
34236        // [`WitContract::require_endpoints_in`] on every membership
34237        // arm — the diagnostic fired at the per-slot altitude must
34238        // byte-equal the diagnostic the primitive fires when called
34239        // directly on the same edge and the same oracle. Pins the
34240        // primitive as the sole load-bearing gate on the membership
34241        // axis, so any future silent detour that re-inlined the twin
34242        // `if !names.contains(...)` cascade back into the per-slot
34243        // gate (a rebase-artifact regression, an M4 admission-webhook
34244        // consumer that bypassed the primitive) would surface here as
34245        // a byte-equal miss between the two dispatches.
34246        //
34247        // Same equivalence-pin discipline the peer
34248        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
34249        // pin already carries on the per-slot gate ≡ `validate` axis,
34250        // extended here onto the per-slot gate ≡ per-edge primitive
34251        // axis at one altitude deeper.
34252        for phantom_edge in [
34253            contract_http("phantom-de", "catalog", "/x"),
34254            contract_http("cart", "phantom-para", "/x"),
34255        ] {
34256            let mut spec = three_member_spec();
34257            spec.contratos.push(phantom_edge.clone());
34258            let per_slot_err = spec.validate_contratos().unwrap_err();
34259            let primitive_err = phantom_edge
34260                .require_endpoints_in(&spec.membro_names())
34261                .unwrap_err();
34262            assert_eq!(
34263                per_slot_err, primitive_err,
34264                "the per-slot gate must reach the per-edge substrate \
34265                 primitive on every membership arm — a bypass here \
34266                 would silently split the two dispatches on the \
34267                 same edge + same oracle input",
34268            );
34269            // And the diagnostic's `caixa` carrier must byte-equal
34270            // the offending accessor's projection at both altitudes,
34271            // pinning the accessor routing across the whole-spec
34272            // path.
34273            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
34274                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
34275            };
34276            let expected = if spec.membro_names().contains(phantom_edge.source()) {
34277                phantom_edge.destination()
34278            } else {
34279                phantom_edge.source()
34280            };
34281            assert_eq!(
34282                caixa, expected,
34283                "the whole-spec ContratoMemberMissing.caixa carrier \
34284                 must byte-equal the offending edge's accessor \
34285                 projection — a bypass here would silently split \
34286                 the wrap envelope's `caixa` field from the \
34287                 substrate-primitive scalar accessor every \
34288                 downstream consumer routes through",
34289            );
34290        }
34291    }
34292
34293    #[test]
34294    fn port_for_destination_reads_through_lifted_entrada_accessor() {
34295        // Peer coherence pin: the
34296        // [`AplicacaoSpec::port_for_destination`] per-destination
34297        // L4-port fallback resolver's composite-projection seed
34298        // (`self.entrada().filter(…).map_or(…)`) must key off the
34299        // lifted outer accessor. Pins the coherence by exercising
34300        // the resolver end-to-end: (1) the `None` `:entrada` shape
34301        // falls through to `DEFAULT_SERVICO_PORT` under the outer
34302        // accessor's reference projection, (2) a non-matching
34303        // destination falls through to `DEFAULT_SERVICO_PORT` under
34304        // the outer accessor's reference projection, and (3) the
34305        // matching destination resolves to the `:entrada :port`
34306        // value under the outer accessor's reference projection.
34307        //
34308        // Peer of the sibling
34309        // [`validate_reads_through_lifted_entrada_accessor`] multi-
34310        // consumer coherence pin on the same per-`:entrada` outer-
34311        // composite axis — extends the multi-consumer coherence
34312        // discipline onto the second per-`:entrada` production
34313        // consumer, the L4-port fallback resolver.
34314
34315        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
34316        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
34317        // arm under the outer accessor's reference projection.
34318        let mut spec = three_member_spec();
34319        spec.entrada = None;
34320        assert_eq!(
34321            spec.port_for_destination("cart"),
34322            DEFAULT_SERVICO_PORT,
34323            "the port-fallback resolver must fall through to \
34324             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
34325             under the outer accessor's reference projection",
34326        );
34327
34328        // (2) Non-matching destination — the resolver's `filter(…)`
34329        // arm rejects a mismatched destination and falls through
34330        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
34331        // reference projection.
34332        let mut spec = three_member_spec();
34333        if let Some(e) = spec.entrada.as_mut() {
34334            e.para = "cart".into();
34335            e.port = 9443;
34336        }
34337        assert_eq!(
34338            spec.port_for_destination("catalog"),
34339            DEFAULT_SERVICO_PORT,
34340            "the port-fallback resolver must fall through to \
34341             DEFAULT_SERVICO_PORT on a non-matching destination \
34342             under the outer accessor's reference projection",
34343        );
34344
34345        // (3) Matching destination — the resolver's `map_or(…)` arm
34346        // returns the `:entrada :port` value under the outer
34347        // accessor's reference projection.
34348        let mut spec = three_member_spec();
34349        if let Some(e) = spec.entrada.as_mut() {
34350            e.para = "cart".into();
34351            e.port = 9443;
34352        }
34353        assert_eq!(
34354            spec.port_for_destination("cart"),
34355            9443,
34356            "the port-fallback resolver must return the \
34357             `:entrada :port` value on a matching destination \
34358             under the outer accessor's reference projection",
34359        );
34360    }
34361
34362    #[test]
34363    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
34364        // The canonical per-`:politicas` `:mtls-required` mTLS-
34365        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
34366        // must return the `:politicas :mtls-required` typed bool
34367        // verbatim as an `Option<bool>`, byte-equal to the raw field
34368        // access across every value in the three-way accept-set —
34369        // `None` (cluster default applies), `Some(true)` (mTLS
34370        // handshake enforced — the sandboxing-by-default arm the
34371        // MeshPolicy's docstring names), `Some(false)` (handshake
34372        // skipped — the explicit debug-edge opt-out).
34373        //
34374        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
34375        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
34376        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
34377        // shape — first `Option<Copy-T>`-return accessor on the M3
34378        // mesh-slot family. Pins against a future silent detour that
34379        // re-derived the toggle from a peer axis (an accidental
34380        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
34381        // whenever a breaker is set), a `None` → `Some(false)` cluster-
34382        // default projection (the canonical `Option<bool>` → `bool`
34383        // collapse footgun the surrounding `is_empty()` predicate
34384        // guards on the peer emptiness axis), or a `Some(true)` /
34385        // `Some(false)` variant swap that landed on one consumer
34386        // without the other.
34387        for required in [None, Some(true), Some(false)] {
34388            let p = MeshPolicy {
34389                mtls_required: required,
34390                ..MeshPolicy::default()
34391            };
34392            assert_eq!(
34393                p.mtls_required(),
34394                required,
34395                "MeshPolicy::mtls_required must return :politicas \
34396                 :mtls-required verbatim (got {:?}, expected {required:?})",
34397                p.mtls_required(),
34398            );
34399            assert_eq!(
34400                p.mtls_required(),
34401                p.mtls_required,
34402                "MeshPolicy::mtls_required must byte-equal the raw \
34403                 .mtls_required field access across every value in the \
34404                 three-way accept-set",
34405            );
34406        }
34407    }
34408
34409    #[test]
34410    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
34411        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
34412        // arm must key off [`MeshPolicy::mtls_required`], not the raw
34413        // `.mtls_required` field access. Structurally: toggling ONLY
34414        // the `mtls_required` slot on an otherwise-default MeshPolicy
34415        // must flip `is_empty()` from `true` (all-`None`) to `false`
34416        // (one axis carries a value); the flip must be observed for
34417        // both `Some(true)` and `Some(false)` since the emptiness
34418        // semantic reads "any axis carries a value" — not "any axis
34419        // carries a truthy value" — the same non-collapsing shape the
34420        // sibling M2 [`crate::LimitsSpec::is_empty`] /
34421        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
34422        // peer `Option<T>`-typed slot surfaces.
34423        //
34424        // Pins against a future silent detour that re-derived the
34425        // emptiness predicate off a peer axis (an accidental
34426        // `.rate_limit.is_none()`-only chain that dropped the
34427        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
34428        // collapse to a truthy-only check (which would silently
34429        // classify `Some(false)` as empty), or an accessor-side
34430        // detour that no longer names the substrate-primitive typed
34431        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
34432        // == false` fallback in the accessor that would silently
34433        // classify both `None` and `Some(false)` as the same value).
34434        //
34435        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
34436        // (7cd2a28) accessor-composition pin on the sibling optional-
34437        // scalar axis — same "the emptiness / shape-gate predicate
34438        // must route through the substrate-primitive typed dispatch"
34439        // discipline extended onto the peer per-`:politicas` emptiness
34440        // predicate.
34441        let empty = MeshPolicy::default();
34442        assert!(
34443            empty.is_empty(),
34444            "MeshPolicy::default() must be is_empty() — every axis \
34445             defaults to None",
34446        );
34447        for required in [Some(true), Some(false)] {
34448            let p = MeshPolicy {
34449                mtls_required: required,
34450                ..MeshPolicy::default()
34451            };
34452            assert!(
34453                !p.is_empty(),
34454                "MeshPolicy::is_empty must return false when \
34455                 :mtls-required is {required:?} — the emptiness \
34456                 predicate reads \"any axis carries a value\", not \
34457                 \"any axis carries a truthy value\"",
34458            );
34459            assert_eq!(
34460                p.mtls_required().is_none(),
34461                p.is_empty(),
34462                "when :mtls-required is the only set axis, \
34463                 is_empty() must equal mtls_required().is_none() — \
34464                 the accessor and the emptiness predicate must \
34465                 route through the same substrate-primitive typed \
34466                 dispatch on the :mtls-required arm",
34467            );
34468        }
34469    }
34470
34471    #[test]
34472    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
34473        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
34474        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
34475        // accessor must return by value, not by reference. Peer of the
34476        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
34477        // borrow-invariant pin on the sibling `Option<String>` slot,
34478        // but extended onto the peer `Option<bool>` copy-invariant
34479        // shape — the accessor's returned `Option<bool>` must outlive
34480        // `&self` (multiple calls must return equal values from a
34481        // dropped-`&self` copy, since the returned Option carries no
34482        // borrow), and calling the accessor twice on the same
34483        // MeshPolicy must yield the same `Option<bool>` verbatim
34484        // (idempotent, no side effects on `&self`).
34485        //
34486        // Pins against a future silent detour that returned
34487        // `Option<&bool>` (which would type-check but silently break
34488        // every downstream caller — [`single_field_overlay`]'s first
34489        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
34490        // detached copy at the call site), an accidental
34491        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
34492        // would also type-check but return `Option<&bool>`), or a
34493        // one-arm-only accessor that reads `Some(*b)` in the Some arm
34494        // but reads a fresh Default::default() in the None arm.
34495        for required in [None, Some(true), Some(false)] {
34496            let p = MeshPolicy {
34497                mtls_required: required,
34498                ..MeshPolicy::default()
34499            };
34500            let first = p.mtls_required();
34501            let second = p.mtls_required();
34502            assert_eq!(
34503                first, second,
34504                "MeshPolicy::mtls_required must be idempotent — two \
34505                 successive calls on the same &self must return the \
34506                 same Option<bool>",
34507            );
34508            assert_eq!(
34509                first, required,
34510                "MeshPolicy::mtls_required must return :politicas \
34511                 :mtls-required verbatim by copy — got {first:?}, \
34512                 expected {required:?}",
34513            );
34514        }
34515    }
34516
34517    #[test]
34518    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
34519        // The canonical per-`:politicas` `:retries` transient-failure-
34520        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
34521        // the `:politicas :retries` typed `u32` verbatim as an
34522        // `Option<u32>`, byte-equal to the raw field access across every
34523        // representative value in the accept-set — `None` (cluster
34524        // default applies — typically "no retries beyond a single
34525        // dispatch attempt" the caixa-mesh `retry_overlay` builder
34526        // documents), `Some(1)` (the lower boundary of the
34527        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
34528        // `AplicacaoSpec::validate_politicas` gate carves out on the
34529        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
34530        // (the upper boundary the same gate carves out on the sibling
34531        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
34532        // past-the-guard sentinel that pins the accessor doesn't perform
34533        // a silent bounds-collapse at the return path).
34534        //
34535        // Sibling of the peer per-`:politicas`
34536        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
34537        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
34538        // peer per-`:politicas` `Option<u32>` shape — second
34539        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
34540        // Pins against a future silent detour that re-derived the retry
34541        // cap from a peer axis (an accidental `.circuit_breaker
34542        // .as_ref().map(|b| b.max_failures)` collapse that read the
34543        // breaker's max-failure count as a retry budget), a
34544        // `None → Some(0)` cluster-default projection (which would
34545        // silently re-introduce the `PolicyRetriesZero` refusal case at
34546        // the emit boundary), or a bounds-collapsing accessor that
34547        // clamped the return through `POLICY_RETRIES_MAX` (the
34548        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
34549        // must ship the raw slot verbatim so a validate-time gate
34550        // regression surfaces at the emit boundary rather than being
34551        // silently absorbed).
34552        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
34553            let p = MeshPolicy {
34554                retries,
34555                ..MeshPolicy::default()
34556            };
34557            assert_eq!(
34558                p.retries(),
34559                retries,
34560                "MeshPolicy::retries must return :politicas :retries \
34561                 verbatim (got {:?}, expected {retries:?})",
34562                p.retries(),
34563            );
34564            assert_eq!(
34565                p.retries(),
34566                p.retries,
34567                "MeshPolicy::retries must byte-equal the raw .retries \
34568                 field access across every value in the accept-set",
34569            );
34570        }
34571    }
34572
34573    #[test]
34574    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
34575        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
34576        // must key off [`MeshPolicy::retries`], not the raw `.retries`
34577        // field access. Structurally: toggling ONLY the `retries` slot
34578        // on an otherwise-default MeshPolicy must flip `is_empty()`
34579        // from `true` (all-`None`) to `false` (one axis carries a
34580        // value); the flip must be observed for every value in the
34581        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
34582        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
34583        // the emptiness semantic reads "any axis carries a value" —
34584        // not "any axis carries a value the validate gate accepts" —
34585        // the same non-collapsing shape the peer M2
34586        // [`crate::LimitsSpec::is_empty`] /
34587        // [`crate::BehaviorSpec::is_empty`] predicates carry.
34588        //
34589        // Pins against a future silent detour that re-derived the
34590        // emptiness predicate off a peer axis (an accidental
34591        // `.rate_limit.is_none()`-only chain that dropped the
34592        // `retries` arm entirely), a `retries == Some(_)` collapse
34593        // that key-off a validate-gate-clamped bounds check (which
34594        // would silently classify a past-the-guard `Some(u32::MAX)`
34595        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
34596        // check), or an accessor-side detour that no longer names the
34597        // substrate-primitive typed dispatch.
34598        //
34599        // Sibling of the peer per-`:politicas`
34600        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
34601        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
34602        // same "the emptiness predicate must route through the
34603        // substrate-primitive typed dispatch" discipline extended onto
34604        // the peer per-`:politicas` `Option<u32>` axis.
34605        let empty = MeshPolicy::default();
34606        assert!(
34607            empty.is_empty(),
34608            "MeshPolicy::default() must be is_empty() — every axis \
34609             defaults to None",
34610        );
34611        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
34612            let p = MeshPolicy {
34613                retries,
34614                ..MeshPolicy::default()
34615            };
34616            assert!(
34617                !p.is_empty(),
34618                "MeshPolicy::is_empty must return false when \
34619                 :retries is {retries:?} — the emptiness \
34620                 predicate reads \"any axis carries a value\", not \
34621                 \"any axis carries a value the validate gate \
34622                 accepts\"",
34623            );
34624            assert_eq!(
34625                p.retries().is_none(),
34626                p.is_empty(),
34627                "when :retries is the only set axis, is_empty() \
34628                 must equal retries().is_none() — the accessor and \
34629                 the emptiness predicate must route through the same \
34630                 substrate-primitive typed dispatch on the :retries \
34631                 arm",
34632            );
34633        }
34634    }
34635
34636    #[test]
34637    fn mesh_policy_retries_projects_option_u32_by_copy() {
34638        // The by-copy pin: [`MeshPolicy::retries`] returns
34639        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
34640        // accessor must return by value, not by reference. Sibling of
34641        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
34642        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
34643        // extended onto the sibling `Option<u32>` copy-invariant
34644        // shape — the accessor's returned `Option<u32>` must outlive
34645        // `&self` (multiple calls must return equal values from a
34646        // dropped-`&self` copy, since the returned Option carries no
34647        // borrow), and calling the accessor twice on the same
34648        // MeshPolicy must yield the same `Option<u32>` verbatim
34649        // (idempotent, no side effects on `&self`).
34650        //
34651        // Pins against a future silent detour that returned
34652        // `Option<&u32>` (which would type-check but silently break
34653        // every downstream caller — [`crate::render::single_field_overlay`]'s
34654        // first parameter is `Option<T: Clone>`, and `&u32` would
34655        // fold to a detached copy at the call site), an accidental
34656        // `Option::as_ref()` projection (`self.retries.as_ref()` would
34657        // also type-check but return `Option<&u32>`), or a one-arm-
34658        // only accessor that reads `Some(*n)` in the Some arm but
34659        // reads a fresh `Default::default()` (`0_u32`) in the None
34660        // arm.
34661        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
34662            let p = MeshPolicy {
34663                retries,
34664                ..MeshPolicy::default()
34665            };
34666            let first = p.retries();
34667            let second = p.retries();
34668            assert_eq!(
34669                first, second,
34670                "MeshPolicy::retries must be idempotent — two \
34671                 successive calls on the same &self must return the \
34672                 same Option<u32>",
34673            );
34674            assert_eq!(
34675                first, retries,
34676                "MeshPolicy::retries must return :politicas :retries \
34677                 verbatim by copy — got {first:?}, expected {retries:?}",
34678            );
34679        }
34680    }
34681
34682    #[test]
34683    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
34684        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
34685        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
34686        // return the `:politicas :timeout` typed [`Duration`] verbatim
34687        // as an `Option<Duration>`, byte-equal to the raw field access
34688        // across every representative value in the accept-set — `None`
34689        // (cluster default applies — typically the gateway class's
34690        // implementation-side per-request wall-clock cap the caixa-mesh
34691        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
34692        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
34693        // set the surrounding `AplicacaoSpec::validate_politicas` gate
34694        // carves out on the sibling `PolicyTimeoutZero` /
34695        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
34696        // (the upper boundary the same gate carves out on the sibling
34697        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
34698        // (a past-the-guard sentinel that pins the accessor doesn't
34699        // perform a silent bounds-collapse into `None` on the zero-
34700        // Duration arm — validate rejects zero but the accessor must
34701        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
34702        // past-the-guard sentinel that pins the accessor doesn't
34703        // perform a silent bounds-collapse at the return path).
34704        //
34705        // Sibling of the peer per-`:politicas`
34706        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
34707        // `Option<u32>` optional-scalar axis and the peer per-
34708        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
34709        // pin on the sibling `Option<bool>` optional-scalar axis,
34710        // extended onto the peer per-`:politicas` `Option<Duration>`
34711        // shape — third `Option<Copy-T>`-return accessor on the M3
34712        // mesh-slot family. Pins against a future silent detour that
34713        // re-derived the per-call cap from a peer axis (an accidental
34714        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
34715        // read the breaker's rolling-window duration as a per-call
34716        // deadline), a `None → Some(Duration::MAX)` cluster-default
34717        // projection (which would silently re-introduce the
34718        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
34719        // blocking" arm at the emit boundary), or a bounds-collapsing
34720        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
34721        // (the `AplicacaoSpec::validate` gate owns the bounds; the
34722        // accessor must ship the raw slot verbatim so a validate-time
34723        // gate regression surfaces at the emit boundary rather than
34724        // being silently absorbed).
34725        for timeout in [
34726            None,
34727            Some(Duration::from_millis(1)),
34728            Some(POLICY_TIMEOUT_MAX),
34729            Some(Duration::ZERO),
34730            Some(Duration::MAX),
34731        ] {
34732            let p = MeshPolicy {
34733                timeout,
34734                ..MeshPolicy::default()
34735            };
34736            assert_eq!(
34737                p.timeout(),
34738                timeout,
34739                "MeshPolicy::timeout must return :politicas :timeout \
34740                 verbatim (got {:?}, expected {timeout:?})",
34741                p.timeout(),
34742            );
34743            assert_eq!(
34744                p.timeout(),
34745                p.timeout,
34746                "MeshPolicy::timeout must byte-equal the raw .timeout \
34747                 field access across every value in the accept-set",
34748            );
34749        }
34750    }
34751
34752    #[test]
34753    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
34754        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
34755        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
34756        // field access. Structurally: toggling ONLY the `timeout` slot
34757        // on an otherwise-default MeshPolicy must flip `is_empty()`
34758        // from `true` (all-`None`) to `false` (one axis carries a
34759        // value); the flip must be observed for every value in the
34760        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
34761        // gate accepts (`Some(Duration::from_millis(1))`,
34762        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
34763        // reads "any axis carries a value" — not "any axis carries a
34764        // value the validate gate accepts" — the same non-collapsing
34765        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
34766        // [`crate::BehaviorSpec::is_empty`] predicates carry.
34767        //
34768        // Pins against a future silent detour that re-derived the
34769        // emptiness predicate off a peer axis (an accidental
34770        // `.rate_limit.is_none()`-only chain that dropped the
34771        // `timeout` arm entirely), a `timeout == Some(_)` collapse
34772        // that key-off a validate-gate-clamped bounds check (which
34773        // would silently classify a past-the-guard `Some(Duration::MAX)`
34774        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
34775        // check), or an accessor-side detour that no longer names the
34776        // substrate-primitive typed dispatch.
34777        //
34778        // Sibling of the peer per-`:politicas`
34779        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
34780        // the sibling `Option<u32>` optional-scalar axis and the peer
34781        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
34782        // accessor-composition pin on the sibling `Option<bool>`
34783        // optional-scalar axis — same "the emptiness predicate must
34784        // route through the substrate-primitive typed dispatch"
34785        // discipline extended onto the peer per-`:politicas`
34786        // `Option<Duration>` axis.
34787        let empty = MeshPolicy::default();
34788        assert!(
34789            empty.is_empty(),
34790            "MeshPolicy::default() must be is_empty() — every axis \
34791             defaults to None",
34792        );
34793        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
34794            let p = MeshPolicy {
34795                timeout,
34796                ..MeshPolicy::default()
34797            };
34798            assert!(
34799                !p.is_empty(),
34800                "MeshPolicy::is_empty must return false when \
34801                 :timeout is {timeout:?} — the emptiness \
34802                 predicate reads \"any axis carries a value\", not \
34803                 \"any axis carries a value the validate gate \
34804                 accepts\"",
34805            );
34806            assert_eq!(
34807                p.timeout().is_none(),
34808                p.is_empty(),
34809                "when :timeout is the only set axis, is_empty() \
34810                 must equal timeout().is_none() — the accessor and \
34811                 the emptiness predicate must route through the same \
34812                 substrate-primitive typed dispatch on the :timeout \
34813                 arm",
34814            );
34815        }
34816    }
34817
34818    #[test]
34819    fn mesh_policy_timeout_projects_option_duration_by_copy() {
34820        // The by-copy pin: [`MeshPolicy::timeout`] returns
34821        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
34822        // and the accessor must return by value, not by reference.
34823        // Sibling of the peer per-`:politicas`
34824        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
34825        // sibling `Option<u32>` optional-scalar axis and the peer
34826        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
34827        // by-copy pin on the sibling `Option<bool>` optional-scalar
34828        // axis, extended onto the peer per-`:politicas`
34829        // `Option<Duration>` copy-invariant shape — the accessor's
34830        // returned `Option<Duration>` must outlive `&self` (multiple
34831        // calls must return equal values from a dropped-`&self`
34832        // copy, since the returned Option carries no borrow), and
34833        // calling the accessor twice on the same MeshPolicy must
34834        // yield the same `Option<Duration>` verbatim (idempotent, no
34835        // side effects on `&self`).
34836        //
34837        // Pins against a future silent detour that returned
34838        // `Option<&Duration>` (which would type-check but silently
34839        // break every downstream caller — [`crate::render::single_field_overlay`]'s
34840        // first parameter is `Option<T: Clone>`, and `&Duration`
34841        // would fold to a detached copy at the call site), an
34842        // accidental `Option::as_ref()` projection
34843        // (`self.timeout.as_ref()` would also type-check but return
34844        // `Option<&Duration>`), or a one-arm-only accessor that
34845        // reads `Some(*d)` in the Some arm but reads a fresh
34846        // `Default::default()` (`Duration::ZERO`) in the None arm
34847        // (which would silently re-classify every unset `:timeout`
34848        // as the `PolicyTimeoutZero`-refused zero-Duration value at
34849        // the accessor boundary).
34850        for timeout in [
34851            None,
34852            Some(Duration::from_millis(1)),
34853            Some(POLICY_TIMEOUT_MAX),
34854            Some(Duration::ZERO),
34855            Some(Duration::MAX),
34856        ] {
34857            let p = MeshPolicy {
34858                timeout,
34859                ..MeshPolicy::default()
34860            };
34861            let first = p.timeout();
34862            let second = p.timeout();
34863            assert_eq!(
34864                first, second,
34865                "MeshPolicy::timeout must be idempotent — two \
34866                 successive calls on the same &self must return the \
34867                 same Option<Duration>",
34868            );
34869            assert_eq!(
34870                first, timeout,
34871                "MeshPolicy::timeout must return :politicas :timeout \
34872                 verbatim by copy — got {first:?}, expected {timeout:?}",
34873            );
34874        }
34875    }
34876
34877    #[test]
34878    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
34879        // The canonical per-`:politicas` `:rate-limit` Envoy-
34880        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
34881        // [`MeshPolicy::rate_limit`] must return the `:politicas
34882        // :rate-limit` typed [`RateLimit`] verbatim as an
34883        // `Option<RateLimit>`, byte-equal to the raw field access
34884        // across every representative value in the accept-set — `None`
34885        // (cluster default applies — no per-Aplicacao rate declaration,
34886        // the gateway-class per-listener default arm the future caixa-
34887        // mesh `local_rate_limit_overlay` emitter documents),
34888        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
34889        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
34890        // accept-set the surrounding
34891        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
34892        // sibling `PolicyRateLimitZero` refusal, paired with the
34893        // canonical-window "1 second" arm of the three-unit
34894        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
34895        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
34896        // (the upper boundary the same gate carves out on the sibling
34897        // `PolicyRateLimitExceedsCap` refusal, paired with the
34898        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
34899        // (a past-the-guard sentinel that pins the accessor doesn't
34900        // perform a silent bounds-collapse into `None` on the
34901        // zero-rate/zero-window arm — validate rejects zero but the
34902        // accessor must ship the raw slot verbatim so a validate-time
34903        // gate regression surfaces at the emit boundary rather than
34904        // being silently absorbed), and
34905        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
34906        // (a past-the-guard sentinel that pins the accessor doesn't
34907        // perform a silent bounds-collapse at the return path).
34908        //
34909        // First `Option<Copy-composite-T>`-return accessor pin on the
34910        // M3 mesh-slot family (peer of the sibling per-`:politicas`
34911        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
34912        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
34913        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
34914        // Copy accessor pins, extended onto the peer per-`:politicas`
34915        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
34916        // and the accessor returns by value). Pins against a future
34917        // silent detour that re-derived the rate declaration from a
34918        // peer axis (an accidental
34919        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
34920        // collapse that read the breaker's trip threshold + rolling
34921        // window as a rate declaration), a `None → Some(default())`
34922        // cluster-default projection (which would silently re-
34923        // introduce a "cluster default is 0/s" arm the emit boundary
34924        // would take as "declared but inert" — the canonical
34925        // declared-but-inert footgun the sibling
34926        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
34927        // amplification-shape axis), a bounds-collapsing accessor
34928        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
34929        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
34930        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
34931        // accessor must ship the raw slot verbatim), or a
34932        // by-reference detour (`Option<&RateLimit>`) that broke every
34933        // downstream consumer keying off `Option<RateLimit>` by-copy.
34934        for rl in [
34935            None,
34936            Some(RateLimit {
34937                rate: 1,
34938                window: Duration::from_secs(1),
34939            }),
34940            Some(RateLimit {
34941                rate: POLICY_RATE_LIMIT_MAX,
34942                window: Duration::from_secs(3600),
34943            }),
34944            Some(RateLimit {
34945                rate: 0,
34946                window: Duration::ZERO,
34947            }),
34948            Some(RateLimit {
34949                rate: u32::MAX,
34950                window: Duration::MAX,
34951            }),
34952        ] {
34953            let p = MeshPolicy {
34954                rate_limit: rl,
34955                ..MeshPolicy::default()
34956            };
34957            assert_eq!(
34958                p.rate_limit(),
34959                rl,
34960                "MeshPolicy::rate_limit must return :politicas :rate-limit \
34961                 verbatim (got {:?}, expected {rl:?})",
34962                p.rate_limit(),
34963            );
34964            assert_eq!(
34965                p.rate_limit(),
34966                p.rate_limit,
34967                "MeshPolicy::rate_limit must byte-equal the raw \
34968                 .rate_limit field access across every value in the \
34969                 accept-set",
34970            );
34971        }
34972    }
34973
34974    #[test]
34975    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
34976        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
34977        // must key off [`MeshPolicy::rate_limit`], not the raw
34978        // `.rate_limit` field access. Structurally: toggling ONLY the
34979        // `rate_limit` slot on an otherwise-default MeshPolicy must
34980        // flip `is_empty()` from `true` (all-`None`) to `false` (one
34981        // axis carries a value); the flip must be observed for every
34982        // representative value in the accept-set the surrounding
34983        // [`AplicacaoSpec::validate_politicas`] gate accepts
34984        // (`Some(RateLimit { rate: 1, window: 1s })`,
34985        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
34986        // since the emptiness semantic reads "any axis carries a
34987        // value" — not "any axis carries a value the validate gate
34988        // accepts" — the same non-collapsing shape the peer M2
34989        // [`crate::LimitsSpec::is_empty`] /
34990        // [`crate::BehaviorSpec::is_empty`] predicates carry.
34991        //
34992        // Pins against a future silent detour that re-derived the
34993        // emptiness predicate off a peer axis (an accidental
34994        // `.timeout.is_none()`-only chain that dropped the
34995        // `rate_limit` arm entirely — the last unlifted inline field
34996        // access on `is_empty` before this lift), a `rate_limit ==
34997        // Some(_)` collapse that key-off a validate-gate-clamped
34998        // bounds check (which would silently classify a past-the-
34999        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
35000        // because it fails the value-shape gate), or an accessor-
35001        // side detour that no longer names the substrate-primitive
35002        // typed dispatch.
35003        //
35004        // Fourth "the emptiness predicate must route through the
35005        // substrate-primitive typed dispatch" composition pin on the
35006        // M3 mesh-slot family — closes the last unlifted composition
35007        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
35008        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
35009        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
35010        // 7073d0f is_empty-composition pins on the sibling primitive-
35011        // Copy axes, extended onto the peer per-`:politicas`
35012        // composite-Copy `Option<RateLimit>` axis).
35013        let empty = MeshPolicy::default();
35014        assert!(
35015            empty.is_empty(),
35016            "MeshPolicy::default() must be is_empty() — every axis \
35017             defaults to None",
35018        );
35019        for rl in [
35020            RateLimit {
35021                rate: 1,
35022                window: Duration::from_secs(1),
35023            },
35024            RateLimit {
35025                rate: POLICY_RATE_LIMIT_MAX,
35026                window: Duration::from_secs(3600),
35027            },
35028        ] {
35029            let p = MeshPolicy {
35030                rate_limit: Some(rl),
35031                ..MeshPolicy::default()
35032            };
35033            assert!(
35034                !p.is_empty(),
35035                "MeshPolicy::is_empty must return false when \
35036                 :rate-limit is {rl:?} — the emptiness predicate \
35037                 reads \"any axis carries a value\", not \"any axis \
35038                 carries a value the validate gate accepts\"",
35039            );
35040            assert_eq!(
35041                p.rate_limit().is_none(),
35042                p.is_empty(),
35043                "when :rate-limit is the only set axis, is_empty() \
35044                 must equal rate_limit().is_none() — the accessor \
35045                 and the emptiness predicate must route through the \
35046                 same substrate-primitive typed dispatch on the \
35047                 :rate-limit arm",
35048            );
35049        }
35050    }
35051
35052    #[test]
35053    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
35054        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
35055        // `:rate-limit` value-shape gate must key off
35056        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
35057        // field bind. Structurally: a `MeshPolicy` whose only set
35058        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
35059        // the `PolicyRateLimitZero` refusal exactly, and the same
35060        // MeshPolicy with the rate at the canonical lower boundary
35061        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
35062        // The pair jointly pins the accessor + validate-gate
35063        // composition: any future silent detour that had the accessor
35064        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
35065        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
35066        // silently absorb the `PolicyRateLimitZero` refusal at the
35067        // accessor boundary — the composition pin catches that at
35068        // caixa-core build time.
35069        //
35070        // Sibling of the peer [`validate_politicas`]
35071        // `:mtls-required` / `:retries` / `:timeout` composition pins
35072        // on the sibling primitive-Copy optional-scalar axes — same
35073        // "the validate / shape-gate predicate must route through the
35074        // substrate-primitive typed dispatch" discipline extended
35075        // onto the peer per-`:politicas` composite-Copy
35076        // `Option<RateLimit>` axis. Second composition-with-accessor
35077        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
35078        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
35079        let mut spec = three_member_spec();
35080        spec.politicas = MeshPolicy {
35081            rate_limit: Some(RateLimit {
35082                rate: 0,
35083                window: Duration::from_secs(1),
35084            }),
35085            ..MeshPolicy::default()
35086        };
35087        assert!(
35088            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
35089            "validate_politicas must reject rate == 0 with \
35090             PolicyRateLimitZero — the accessor and the validate gate \
35091             must route through the same substrate-primitive typed \
35092             dispatch on the :rate-limit zero-floor arm",
35093        );
35094        spec.politicas = MeshPolicy {
35095            rate_limit: Some(RateLimit {
35096                rate: 1,
35097                window: Duration::from_secs(1),
35098            }),
35099            ..MeshPolicy::default()
35100        };
35101        assert!(
35102            spec.validate().is_ok(),
35103            "validate_politicas must accept rate == 1 (the canonical \
35104             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
35105             set) with a canonical 1s window",
35106        );
35107    }
35108
35109    #[test]
35110    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
35111        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
35112        // `outlier_detection`-mesh consecutive-failure-ejection scalar
35113        // pin: [`MeshPolicy::circuit_breaker`] must return the
35114        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
35115        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
35116        // raw field access across every representative value in the
35117        // accept-set — `None` (cluster default applies — no
35118        // per-Aplicacao breaker declaration, the gateway-class per-
35119        // listener default arm the future caixa-mesh
35120        // `outlier_detection_overlay` emitter documents),
35121        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
35122        // (the lower boundary of the accept-set the surrounding
35123        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
35124        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
35125        // refusals),
35126        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
35127        // (the upper boundary the same gate carves out on the sibling
35128        // `PolicyBreakerMaxFailuresExceedsCap` /
35129        // `PolicyBreakerWindowExceedsCap` refusals),
35130        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
35131        // (a past-the-guard sentinel that pins the accessor doesn't
35132        // perform a silent bounds-collapse into `None` on the
35133        // zero-failures/zero-window arm — validate rejects zero but
35134        // the accessor must ship the raw slot verbatim so a validate-
35135        // time gate regression surfaces at the emit boundary rather
35136        // than being silently absorbed), and
35137        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
35138        // (a past-the-guard sentinel that pins the accessor doesn't
35139        // perform a silent bounds-collapse at the return path).
35140        //
35141        // Second `Option<Copy-composite-T>`-return accessor pin on the
35142        // M3 mesh-slot family (peer of the sibling per-`:politicas`
35143        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
35144        // composite-Copy accessor pin, and of the sibling per-
35145        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
35146        // [`MeshPolicy::retries`] bdfb399 /
35147        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
35148        // accessor pins). Pins against a future silent detour that
35149        // re-derived the breaker declaration from a peer axis (an
35150        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
35151        // collapse that read the rate-limit's bucket capacity + refill
35152        // period as a breaker declaration), a `None → Some(default())`
35153        // cluster-default projection (which would silently re-
35154        // introduce the `PolicyBreakerZeroFailures` /
35155        // `PolicyBreakerZeroWindow` refusal cases at the emit
35156        // boundary), a bounds-collapsing accessor that clamped
35157        // `cb.max_failures` through
35158        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
35159        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
35160        // [`AplicacaoSpec::validate`] gate owns the bounds; the
35161        // accessor must ship the raw slot verbatim), or a
35162        // by-reference detour (`Option<&CircuitBreaker>`) that broke
35163        // every downstream consumer keying off `Option<CircuitBreaker>`
35164        // by-copy.
35165        for cb in [
35166            None,
35167            Some(CircuitBreaker {
35168                max_failures: 1,
35169                window: Duration::from_millis(1),
35170            }),
35171            Some(CircuitBreaker {
35172                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
35173                window: POLICY_BREAKER_WINDOW_MAX,
35174            }),
35175            Some(CircuitBreaker {
35176                max_failures: 0,
35177                window: Duration::ZERO,
35178            }),
35179            Some(CircuitBreaker {
35180                max_failures: u32::MAX,
35181                window: Duration::MAX,
35182            }),
35183        ] {
35184            let p = MeshPolicy {
35185                circuit_breaker: cb,
35186                ..MeshPolicy::default()
35187            };
35188            assert_eq!(
35189                p.circuit_breaker(),
35190                cb,
35191                "MeshPolicy::circuit_breaker must return :politicas \
35192                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
35193                p.circuit_breaker(),
35194            );
35195            assert_eq!(
35196                p.circuit_breaker(),
35197                p.circuit_breaker,
35198                "MeshPolicy::circuit_breaker must byte-equal the raw \
35199                 .circuit_breaker field access across every value in \
35200                 the accept-set",
35201            );
35202        }
35203    }
35204
35205    #[test]
35206    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
35207        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
35208        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
35209        // `.circuit_breaker` field access. Structurally: toggling ONLY
35210        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
35211        // must flip `is_empty()` from `true` (all-`None`) to `false`
35212        // (one axis carries a value); the flip must be observed for
35213        // every representative value in the accept-set the surrounding
35214        // [`AplicacaoSpec::validate_politicas`] gate accepts
35215        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
35216        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
35217        // since the emptiness semantic reads "any axis carries a
35218        // value" — not "any axis carries a value the validate gate
35219        // accepts" — the same non-collapsing shape the peer M2
35220        // [`crate::LimitsSpec::is_empty`] /
35221        // [`crate::BehaviorSpec::is_empty`] predicates carry.
35222        //
35223        // Pins against a future silent detour that re-derived the
35224        // emptiness predicate off a peer axis (an accidental
35225        // `.rate_limit.is_none()`-only chain that dropped the
35226        // `circuit_breaker` arm entirely — the last unlifted inline
35227        // field access on `is_empty` before this lift), a
35228        // `circuit_breaker == Some(_)` collapse that key-off a
35229        // validate-gate-clamped bounds check (which would silently
35230        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
35231        // 0, window: 0s })` as empty because it fails the value-shape
35232        // gate), or an accessor-side detour that no longer names the
35233        // substrate-primitive typed dispatch.
35234        //
35235        // Fifth "the emptiness predicate must route through the
35236        // substrate-primitive typed dispatch" composition pin on the
35237        // M3 mesh-slot family — closes the last unlifted composition
35238        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
35239        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
35240        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
35241        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
35242        // composition pins on the sibling primitive-Copy + composite-
35243        // Copy axes, extended onto the peer per-`:politicas`
35244        // composite-Copy `Option<CircuitBreaker>` axis).
35245        let empty = MeshPolicy::default();
35246        assert!(
35247            empty.is_empty(),
35248            "MeshPolicy::default() must be is_empty() — every axis \
35249             defaults to None",
35250        );
35251        for cb in [
35252            CircuitBreaker {
35253                max_failures: 1,
35254                window: Duration::from_millis(1),
35255            },
35256            CircuitBreaker {
35257                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
35258                window: POLICY_BREAKER_WINDOW_MAX,
35259            },
35260        ] {
35261            let p = MeshPolicy {
35262                circuit_breaker: Some(cb),
35263                ..MeshPolicy::default()
35264            };
35265            assert!(
35266                !p.is_empty(),
35267                "MeshPolicy::is_empty must return false when \
35268                 :circuit-breaker is {cb:?} — the emptiness predicate \
35269                 reads \"any axis carries a value\", not \"any axis \
35270                 carries a value the validate gate accepts\"",
35271            );
35272            assert_eq!(
35273                p.circuit_breaker().is_none(),
35274                p.is_empty(),
35275                "when :circuit-breaker is the only set axis, \
35276                 is_empty() must equal circuit_breaker().is_none() — \
35277                 the accessor and the emptiness predicate must route \
35278                 through the same substrate-primitive typed dispatch \
35279                 on the :circuit-breaker arm",
35280            );
35281        }
35282    }
35283
35284    #[test]
35285    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
35286        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
35287        // `:circuit-breaker` value-shape gate must key off
35288        // [`MeshPolicy::circuit_breaker`], not the raw
35289        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
35290        // whose only set axis is a `Some(CircuitBreaker { max_failures:
35291        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
35292        // refusal exactly, and the same MeshPolicy with the breaker at
35293        // the canonical lower boundary
35294        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
35295        // pass validate. The pair jointly pins the accessor +
35296        // validate-gate composition: any future silent detour that had
35297        // the accessor omit the `Some(CircuitBreaker { max_failures:
35298        // 0, .. })` arm (a
35299        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
35300        // collapse) would silently absorb the
35301        // `PolicyBreakerZeroFailures` refusal at the accessor
35302        // boundary — the composition pin catches that at caixa-core
35303        // build time.
35304        //
35305        // Sibling of the peer [`validate_politicas`]
35306        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
35307        // composition pins on the sibling primitive-Copy + composite-
35308        // Copy optional-scalar axes — same "the validate / shape-gate
35309        // predicate must route through the substrate-primitive typed
35310        // dispatch" discipline extended onto the peer per-`:politicas`
35311        // composite-Copy `Option<CircuitBreaker>` axis. Second
35312        // composition-with-accessor pin on the M3 mesh-slot
35313        // `Option<CircuitBreaker>` arm alongside the
35314        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
35315        let mut spec = three_member_spec();
35316        spec.politicas = MeshPolicy {
35317            circuit_breaker: Some(CircuitBreaker {
35318                max_failures: 0,
35319                window: Duration::from_millis(1),
35320            }),
35321            ..MeshPolicy::default()
35322        };
35323        assert!(
35324            matches!(
35325                spec.validate(),
35326                Err(AplicacaoError::PolicyBreakerZeroFailures)
35327            ),
35328            "validate_politicas must reject max_failures == 0 with \
35329             PolicyBreakerZeroFailures — the accessor and the validate \
35330             gate must route through the same substrate-primitive \
35331             typed dispatch on the :circuit-breaker zero-floor arm",
35332        );
35333        spec.politicas = MeshPolicy {
35334            circuit_breaker: Some(CircuitBreaker {
35335                max_failures: 1,
35336                window: Duration::from_millis(1),
35337            }),
35338            ..MeshPolicy::default()
35339        };
35340        assert!(
35341            spec.validate().is_ok(),
35342            "validate_politicas must accept a CircuitBreaker at the \
35343             canonical lower boundary (max_failures = 1, window = \
35344             1ms) — the accessor and the validate gate must route \
35345             through the same substrate-primitive typed dispatch on \
35346             the :circuit-breaker arm",
35347        );
35348    }
35349
35350    #[test]
35351    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
35352        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
35353        // Envoy-outlier-detection trip-threshold scalar pin:
35354        // [`CircuitBreaker::max_failures`] must return the
35355        // `:politicas :circuit-breaker :max-failures` typed `u32`
35356        // verbatim, byte-equal to the raw field access across every
35357        // representative value in the accept-set — `1` (the lower
35358        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
35359        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
35360        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
35361        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
35362        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
35363        // refusal), `0` (a past-the-guard sentinel that pins the accessor
35364        // doesn't perform a silent bounds-collapse into `1` on the zero
35365        // arm — validate rejects zero but the accessor must ship the
35366        // raw slot verbatim so a validate-time gate regression surfaces
35367        // at the emit boundary rather than being silently absorbed),
35368        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
35369        // doesn't perform a silent bounds-collapse through
35370        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
35371        //
35372        // First sub-struct required-scalar accessor pin on the M3
35373        // mesh-slot family — sibling in shape to the peer per-`:membros`
35374        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
35375        // (a40b0e3) required-`String`-carry accessor pins and the peer
35376        // per-`:contratos` [`WitContract::source`] /
35377        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
35378        // accessor pins, extended onto the peer per-`CircuitBreaker`
35379        // required-`u32` scalar-value axis. Pins against a future silent
35380        // detour that re-derived the trip threshold from a peer axis (an
35381        // accidental `self.window.as_secs() as u32` collapse that read
35382        // the breaker's rolling-window duration as a failure count), a
35383        // `0 → 1` cluster-default projection (which would silently absorb
35384        // the `PolicyBreakerZeroFailures` refusal case at the accessor
35385        // boundary), or a bounds-collapsing accessor that clamped the
35386        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
35387        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
35388        // must ship the raw slot verbatim).
35389        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
35390            let cb = CircuitBreaker {
35391                max_failures,
35392                window: Duration::from_secs(60),
35393            };
35394            assert_eq!(
35395                cb.max_failures(),
35396                max_failures,
35397                "CircuitBreaker::max_failures must return :politicas \
35398                 :circuit-breaker :max-failures verbatim (got {}, \
35399                 expected {max_failures})",
35400                cb.max_failures(),
35401            );
35402            assert_eq!(
35403                cb.max_failures(),
35404                cb.max_failures,
35405                "CircuitBreaker::max_failures must byte-equal the raw \
35406                 .max_failures field access across every value in the \
35407                 u32 accept-set",
35408            );
35409        }
35410    }
35411
35412    #[test]
35413    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
35414        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
35415        // `:circuit-breaker :max-failures` zero-floor arm must key off
35416        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
35417        // field access. Structurally: a `CircuitBreaker { max_failures:
35418        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
35419        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
35420        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
35421        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
35422        // pass validate. The pair jointly pins the accessor +
35423        // validate-gate composition: any future silent detour that had
35424        // the accessor return a fresh `1` on the zero arm (a
35425        // `.max_failures().max(1)` collapse) would silently absorb the
35426        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
35427        // and the validate gate would accept a struct-literal
35428        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
35429        // catches that at caixa-core build time.
35430        //
35431        // Peer of the sibling per-`:politicas`
35432        // [`MeshPolicy::mtls_required`] (c0110f1) /
35433        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
35434        // (7073d0f) accessor-composition pins on the sibling optional-
35435        // scalar axes — same "the validate / shape-gate predicate must
35436        // route through the substrate-primitive typed dispatch"
35437        // discipline extended onto the peer per-`CircuitBreaker`
35438        // required-scalar composition axis.
35439        let mut spec = three_member_spec();
35440        spec.politicas = MeshPolicy {
35441            circuit_breaker: Some(CircuitBreaker {
35442                max_failures: 0,
35443                window: Duration::from_secs(60),
35444            }),
35445            ..MeshPolicy::default()
35446        };
35447        assert!(
35448            matches!(
35449                spec.validate(),
35450                Err(AplicacaoError::PolicyBreakerZeroFailures)
35451            ),
35452            "validate_politicas must reject max_failures == 0 with \
35453             PolicyBreakerZeroFailures — the accessor and the validate \
35454             gate must route through the same substrate-primitive typed \
35455             dispatch on the :max-failures zero-floor arm",
35456        );
35457        spec.politicas = MeshPolicy {
35458            circuit_breaker: Some(CircuitBreaker {
35459                max_failures: 1,
35460                window: Duration::from_secs(60),
35461            }),
35462            ..MeshPolicy::default()
35463        };
35464        assert!(
35465            spec.validate().is_ok(),
35466            "validate_politicas must accept max_failures == 1 (the \
35467             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
35468             accept-set)",
35469        );
35470    }
35471
35472    #[test]
35473    fn circuit_breaker_max_failures_projects_u32_by_copy() {
35474        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
35475        // `u32` by copy — `u32` is `Copy` and the accessor must return
35476        // by value, not by reference. Peer of the sibling
35477        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
35478        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
35479        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
35480        // optional-scalar axes, extended onto the peer
35481        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
35482        // the accessor's returned `u32` must outlive `&self` (multiple
35483        // calls must return equal values from a dropped-`&self` copy,
35484        // since the returned scalar carries no borrow), and calling
35485        // the accessor twice on the same CircuitBreaker must yield the
35486        // same `u32` verbatim (idempotent, no side effects on `&self`).
35487        //
35488        // Pins against a future silent detour that returned `&u32`
35489        // (which would type-check but silently break every downstream
35490        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
35491        // first parameter is `u32`, and `&u32` would fold to a detached
35492        // copy at the call site with a `*` deref the sibling accessors
35493        // don't need), an accidental `.max_failures.wrapping_add(0)`
35494        // detour that returned a fresh copy through an arithmetic
35495        // no-op (breaking a future `const fn` regression), or a
35496        // one-arm-only accessor that returned a saturating value on
35497        // some sentinel input (breaking the pass-through invariant the
35498        // sibling required-scalar accessors carry).
35499        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
35500            let cb = CircuitBreaker {
35501                max_failures,
35502                window: Duration::from_secs(60),
35503            };
35504            let first = cb.max_failures();
35505            let second = cb.max_failures();
35506            assert_eq!(
35507                first, second,
35508                "CircuitBreaker::max_failures must be idempotent — two \
35509                 successive calls on the same &self must return the \
35510                 same u32",
35511            );
35512            assert_eq!(
35513                first, max_failures,
35514                "CircuitBreaker::max_failures must return :politicas \
35515                 :circuit-breaker :max-failures verbatim by copy — \
35516                 got {first}, expected {max_failures}",
35517            );
35518        }
35519    }
35520
35521    #[test]
35522    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
35523        // The canonical per-`:politicas :circuit-breaker` `:window`
35524        // Envoy-outlier-detection rolling-observation-interval scalar
35525        // pin: [`CircuitBreaker::window`] must return the
35526        // `:politicas :circuit-breaker :window` typed `Duration`
35527        // verbatim, byte-equal to the raw field access across every
35528        // representative value in the accept-set — `Duration::from_millis(1)`
35529        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
35530        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
35531        // gate carves out on the sibling `PolicyBreakerZeroWindow`
35532        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
35533        // same gate carves out on the sibling
35534        // `PolicyBreakerWindowExceedsCap` refusal),
35535        // `Duration::ZERO` (a past-the-guard sentinel that pins the
35536        // accessor doesn't perform a silent bounds-collapse into
35537        // `Duration::from_millis(1)` on the zero arm — validate rejects
35538        // zero but the accessor must ship the raw slot verbatim so a
35539        // validate-time gate regression surfaces at the emit boundary
35540        // rather than being silently absorbed),
35541        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
35542        // far above the 1h cap — that pins the accessor doesn't perform
35543        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
35544        // at the return path).
35545        //
35546        // Second sub-struct required-scalar accessor pin on the M3
35547        // mesh-slot family — sibling in shape to the just-landed
35548        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
35549        // (3a74062) required-`u32` accessor pin on the peer
35550        // per-`CircuitBreaker` required-axis, extended onto the
35551        // per-sub-struct required-`Duration` axis. Pins against a
35552        // future silent detour that re-derived the observation window
35553        // from a peer axis (an accidental
35554        // `Duration::from_secs(self.max_failures as u64)` collapse that
35555        // read the breaker's trip count as an observation-interval
35556        // duration), a `Duration::ZERO → Duration::from_millis(1)`
35557        // cluster-default projection (which would silently absorb the
35558        // `PolicyBreakerZeroWindow` refusal case at the accessor
35559        // boundary), or a bounds-collapsing accessor that clamped the
35560        // return through `POLICY_BREAKER_WINDOW_MAX` (the
35561        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
35562        // must ship the raw slot verbatim).
35563        for window in [
35564            Duration::from_millis(1),
35565            POLICY_BREAKER_WINDOW_MAX,
35566            Duration::ZERO,
35567            Duration::from_secs(86_400),
35568        ] {
35569            let cb = CircuitBreaker {
35570                max_failures: 5,
35571                window,
35572            };
35573            assert_eq!(
35574                cb.window(),
35575                window,
35576                "CircuitBreaker::window must return :politicas \
35577                 :circuit-breaker :window verbatim (got {:?}, \
35578                 expected {window:?})",
35579                cb.window(),
35580            );
35581            assert_eq!(
35582                cb.window(),
35583                cb.window,
35584                "CircuitBreaker::window must byte-equal the raw \
35585                 .window field access across every value in the \
35586                 Duration accept-set",
35587            );
35588        }
35589    }
35590
35591    #[test]
35592    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
35593        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
35594        // `:circuit-breaker :window` zero-floor arm must key off
35595        // [`CircuitBreaker::window`], not the raw `.window` field
35596        // access. Structurally: a `CircuitBreaker { window:
35597        // Duration::ZERO, .. }` embedded in a
35598        // `:politicas :circuit-breaker` slot must surface the
35599        // `PolicyBreakerZeroWindow` refusal exactly, and a
35600        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
35601        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
35602        // accept-set) must pass validate. The pair jointly pins the
35603        // accessor + validate-gate composition: any future silent
35604        // detour that had the accessor return a fresh
35605        // `Duration::from_millis(1)` on the zero arm (a
35606        // `.window().max(Duration::from_millis(1))` collapse) would
35607        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
35608        // accessor boundary and the validate gate would accept a
35609        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
35610        // — the composition pin catches that at caixa-core build time.
35611        //
35612        // Peer of the sibling per-`CircuitBreaker`
35613        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
35614        // pin on the peer required-scalar `:max-failures` axis — same
35615        // "the validate / shape-gate predicate must route through the
35616        // substrate-primitive typed dispatch" discipline extended onto
35617        // the peer per-`CircuitBreaker` required-`Duration` composition
35618        // axis.
35619        let mut spec = three_member_spec();
35620        spec.politicas = MeshPolicy {
35621            circuit_breaker: Some(CircuitBreaker {
35622                max_failures: 5,
35623                window: Duration::ZERO,
35624            }),
35625            ..MeshPolicy::default()
35626        };
35627        assert!(
35628            matches!(
35629                spec.validate(),
35630                Err(AplicacaoError::PolicyBreakerZeroWindow)
35631            ),
35632            "validate_politicas must reject window == Duration::ZERO \
35633             with PolicyBreakerZeroWindow — the accessor and the \
35634             validate gate must route through the same substrate-\
35635             primitive typed dispatch on the :window zero-floor arm",
35636        );
35637        spec.politicas = MeshPolicy {
35638            circuit_breaker: Some(CircuitBreaker {
35639                max_failures: 5,
35640                window: Duration::from_millis(1),
35641            }),
35642            ..MeshPolicy::default()
35643        };
35644        assert!(
35645            spec.validate().is_ok(),
35646            "validate_politicas must accept window == \
35647             Duration::from_millis(1) (the lower boundary of the \
35648             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
35649        );
35650    }
35651
35652    #[test]
35653    fn circuit_breaker_window_projects_duration_by_copy() {
35654        // The by-copy pin: [`CircuitBreaker::window`] returns
35655        // `Duration` by copy — `Duration` is `Copy` and the accessor
35656        // must return by value, not by reference. Peer of the sibling
35657        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
35658        // (3a74062) by-copy pin on the peer required-scalar
35659        // `:max-failures` axis, extended onto the peer
35660        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
35661        // — the accessor's returned `Duration` must outlive `&self`
35662        // (multiple calls must return equal values from a
35663        // dropped-`&self` copy, since the returned scalar carries no
35664        // borrow), and calling the accessor twice on the same
35665        // CircuitBreaker must yield the same `Duration` verbatim
35666        // (idempotent, no side effects on `&self`).
35667        //
35668        // Pins against a future silent detour that returned
35669        // `&Duration` (which would type-check but silently break every
35670        // downstream `Duration`-by-value consumer —
35671        // [`crate::render::require_positive_canonical_bounded_duration`]'s
35672        // first parameter is `Duration`, and `&Duration` would fold to
35673        // a detached copy at the call site with a `*` deref the sibling
35674        // accessors don't need), an accidental `.window + Duration::ZERO`
35675        // detour that returned a fresh copy through an arithmetic
35676        // no-op (breaking a future `const fn` regression), or a
35677        // one-arm-only accessor that returned a saturating value on
35678        // some sentinel input (breaking the pass-through invariant the
35679        // sibling required-scalar accessors carry).
35680        for window in [
35681            Duration::from_millis(1),
35682            POLICY_BREAKER_WINDOW_MAX,
35683            Duration::ZERO,
35684            Duration::from_secs(86_400),
35685        ] {
35686            let cb = CircuitBreaker {
35687                max_failures: 5,
35688                window,
35689            };
35690            let first = cb.window();
35691            let second = cb.window();
35692            assert_eq!(
35693                first, second,
35694                "CircuitBreaker::window must be idempotent — two \
35695                 successive calls on the same &self must return the \
35696                 same Duration",
35697            );
35698            assert_eq!(
35699                first, window,
35700                "CircuitBreaker::window must return :politicas \
35701                 :circuit-breaker :window verbatim by copy — \
35702                 got {first:?}, expected {window:?}",
35703            );
35704        }
35705    }
35706
35707    #[test]
35708    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
35709        // Apex-identity pair-invariant pin composing both substrate-
35710        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
35711        // and [`WitContract::destination`] — at the emit-side call shape
35712        // every per-`(:de, :para)` CNP L4 port reader now takes. The
35713        // invariant, evaluated per-edge:
35714        //
35715        //   spec.port_for_destination(c.destination()) == expected_port
35716        //
35717        // where `expected_port` is `entrada.port` when
35718        // `c.destination() == entrada.destination()` and
35719        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
35720        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
35721        // pin on the per-`:entrada` axis — that pin encodes the apex
35722        // ingress L4 identity via `entrada.destination()`; this pin
35723        // encodes the per-edge L4 identity via `c.destination()`, and
35724        // both compose on the same substrate-primitive resolver so a
35725        // future refactor that silently split either accessor's apex
35726        // behavior surfaces at caixa-core build time.
35727        let mut spec = three_member_spec();
35728        if let Some(e) = spec.entrada.as_mut() {
35729            e.para = "cart".into();
35730            e.port = 8443;
35731        }
35732        let apex_contract = WitContract {
35733            de: "checkout".into(),
35734            para: "cart".into(),
35735            wit: "wasi:http/proxy".into(),
35736            endpoint: Some("/hello".into()),
35737            subject: None,
35738            slot: None,
35739        };
35740        assert_eq!(
35741            spec.port_for_destination(apex_contract.destination()),
35742            8443,
35743            "`spec.port_for_destination(c.destination())` must equal \
35744             `entrada.port` when the contract callee names the ingress \
35745             apex — the CNP per-edge L4 port and the HTTPRoute apex \
35746             backendRef port share this substrate-primitive resolver.",
35747        );
35748        let non_apex_contract = WitContract {
35749            de: "cart".into(),
35750            para: "payment".into(),
35751            wit: "wasi:http/proxy".into(),
35752            endpoint: Some("/charge".into()),
35753            subject: None,
35754            slot: None,
35755        };
35756        assert_eq!(
35757            spec.port_for_destination(non_apex_contract.destination()),
35758            DEFAULT_SERVICO_PORT,
35759            "`spec.port_for_destination(c.destination())` must fall back \
35760             to the substrate-canonical port floor when the contract \
35761             callee is not the ingress apex — the resolver's non-apex \
35762             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
35763        );
35764    }
35765
35766    #[test]
35767    fn membro_key_consts_are_lower_camel_case_shape() {
35768        // Shape-pin: every `MEMBRO_KEY_*` const must be a
35769        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
35770        // `kebab-case` hyphens, no leading colon, no `PascalCase`
35771        // leading capital, no whitespace / dots) — the canonical shape
35772        // the `#[serde(rename_all = "camelCase")]` derive produces on
35773        // [`Membro`]. A future flip to a non-camelCase attribute at
35774        // the derive surfaces both here (this test fails on the
35775        // stale-constant shape) and at
35776        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
35777        // fails on the mismatch between const and derive). Peer with
35778        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
35779        // on the sibling `SupervisorSpec` top-level axis.
35780        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
35781            assert!(
35782                !key.is_empty(),
35783                "MEMBRO_KEY_* must be non-empty (got {key:?})"
35784            );
35785            let first = key.chars().next().unwrap();
35786            assert!(
35787                first.is_ascii_lowercase(),
35788                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
35789                 (got {key:?}, leads with {first:?})",
35790            );
35791            assert!(
35792                key.chars().all(|c| c.is_ascii_alphanumeric()),
35793                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
35794                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
35795            );
35796        }
35797    }
35798
35799    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
35800
35801    #[test]
35802    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
35803        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
35804        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
35805        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
35806        // keys the `#[serde(rename_all = "camelCase")]` attribute on
35807        // [`WitContract`] emits for the required-triad. The three
35808        // sibling payload-arm keys already pin under
35809        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
35810        // `STORE_FIELD_NAME` — pin all six alongside so a future
35811        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
35812        // verbatim-field-name flip at the derive attribute (any of which
35813        // would silently break every downstream JSON consumer that
35814        // reaches for one of the six via `Value::get(...)`) surfaces
35815        // here as a build-time test failure at `aplicacao.rs`, not as an
35816        // apply-time `.get(<stale-canonical-const>)` returning `None`
35817        // far from the derive-attr drift's commit. Peer with the sibling
35818        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
35819        // pin on the M3 `:membros` per-entry axis — same discipline the
35820        // `Membro` per-entry lift established, extended here to the
35821        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
35822        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
35823        // axis on the Aplicacao surface without a lifted serde-key peer.
35824        let c = WitContract {
35825            de: "cart".into(),
35826            para: "catalog".into(),
35827            wit: "wasi:http/proxy".into(),
35828            endpoint: Some("/lookup".into()),
35829            subject: None,
35830            slot: None,
35831        };
35832        let json = serde_json::to_string(&c).unwrap();
35833        for key in [
35834            crate::CONTRATO_KEY_DE,
35835            crate::CONTRATO_KEY_PARA,
35836            crate::CONTRATO_KEY_WIT,
35837            WitTarget::HTTP_FIELD_NAME,
35838        ] {
35839            let quoted = format!("\"{key}\"");
35840            assert!(
35841                json.contains(&quoted),
35842                "serialized WitContract must carry the lifted \
35843                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
35844                 {quoted} verbatim in the JSON emission (got: {json})",
35845            );
35846        }
35847
35848        // Pin the two remaining payload-arm keys by round-tripping a
35849        // `WitContract` under each payload-shape (pub-sub, store) — the
35850        // required-triad appears on every emission but the payload arms
35851        // only surface when their `Option<String>` field is `Some`.
35852        let pubsub = WitContract {
35853            de: "cart".into(),
35854            para: "events".into(),
35855            wit: "nats:pub-sub".into(),
35856            endpoint: None,
35857            subject: Some("orders.placed".into()),
35858            slot: None,
35859        };
35860        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
35861        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
35862        assert!(
35863            pubsub_json.contains(&pubsub_quoted),
35864            "serialized pub-sub WitContract must carry the lifted \
35865             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
35866             verbatim in the JSON emission (got: {pubsub_json})",
35867        );
35868        let store = WitContract {
35869            de: "cart".into(),
35870            para: "sessions".into(),
35871            wit: "wasi:keyvalue/store".into(),
35872            endpoint: None,
35873            subject: None,
35874            slot: Some("cart/$id".into()),
35875        };
35876        let store_json = serde_json::to_string(&store).unwrap();
35877        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
35878        assert!(
35879            store_json.contains(&store_quoted),
35880            "serialized store WitContract must carry the lifted \
35881             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
35882             verbatim in the JSON emission (got: {store_json})",
35883        );
35884    }
35885
35886    #[test]
35887    fn contrato_key_consts_are_pairwise_distinct() {
35888        // Cross-axis drift-detection pin: a future collapse of the six
35889        // canonical [`WitContract`] per-entry byte-strings onto the same
35890        // value (e.g. an accidental copy-paste flip of
35891        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
35892        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
35893        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
35894        // every downstream probe on one axis onto the sibling axis's
35895        // overlay entry and pass every propagation-probe test that
35896        // expected only the stale axis's value. Peer of the sibling
35897        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
35898        // widened here to the six-way axis the `WitContract`
35899        // required-triad + `WitTarget` payload-triad jointly cover.
35900        let all = [
35901            crate::CONTRATO_KEY_DE,
35902            crate::CONTRATO_KEY_PARA,
35903            crate::CONTRATO_KEY_WIT,
35904            WitTarget::HTTP_FIELD_NAME,
35905            WitTarget::PUBSUB_FIELD_NAME,
35906            WitTarget::STORE_FIELD_NAME,
35907        ];
35908        for (i, a) in all.iter().enumerate() {
35909            for b in all.iter().skip(i + 1) {
35910                assert_ne!(
35911                    a, b,
35912                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
35913                     must be pairwise-distinct canonical byte-sequences \
35914                     — got `{a}` == `{b}`",
35915                );
35916            }
35917        }
35918    }
35919
35920    #[test]
35921    fn contrato_key_consts_are_lower_camel_case_shape() {
35922        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
35923        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
35924        // byte-sequence (no `snake_case` underscores, no `kebab-case`
35925        // hyphens, no leading colon, no `PascalCase` leading capital, no
35926        // whitespace / dots) — the canonical shape the
35927        // `#[serde(rename_all = "camelCase")]` derive produces on
35928        // [`WitContract`]. A future flip to a non-camelCase attribute at
35929        // the derive surfaces both here (this test fails on the
35930        // stale-constant shape) and at
35931        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
35932        // (that test fails on the mismatch between const and derive).
35933        // Peer with `membro_key_consts_are_lower_camel_case_shape`
35934        // (ce80ca0) on the sibling `Membro` per-entry axis.
35935        for key in [
35936            crate::CONTRATO_KEY_DE,
35937            crate::CONTRATO_KEY_PARA,
35938            crate::CONTRATO_KEY_WIT,
35939            WitTarget::HTTP_FIELD_NAME,
35940            WitTarget::PUBSUB_FIELD_NAME,
35941            WitTarget::STORE_FIELD_NAME,
35942        ] {
35943            assert!(
35944                !key.is_empty(),
35945                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
35946                 non-empty (got {key:?})"
35947            );
35948            let first = key.chars().next().unwrap();
35949            assert!(
35950                first.is_ascii_lowercase(),
35951                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
35952                 with an ASCII-lowercase byte (got {key:?}, leads with \
35953                 {first:?})",
35954            );
35955            assert!(
35956                key.chars().all(|c| c.is_ascii_alphanumeric()),
35957                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
35958                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
35959                 whitespace (got {key:?})",
35960            );
35961        }
35962    }
35963
35964    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
35965
35966    #[test]
35967    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
35968        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
35969        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
35970        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
35971        // name the exact camelCase JSON keys the
35972        // `#[serde(rename_all = "camelCase")]` attribute on
35973        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
35974        // pin that each canonical byte-sequence appears verbatim in the
35975        // JSON — a future accidental `rename_all = "snake_case"` /
35976        // `"kebab-case"` / verbatim-field-name flip at the derive
35977        // attribute (any of which would silently break every downstream
35978        // JSON consumer that reaches for one of the four consts via
35979        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
35980        // emitter's per-Aplicacao hostname/paths/port projection, the
35981        // future `app-operator` reconciler's per-Aplicacao ingress
35982        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
35983        // materializer's admission-time cross-check) surfaces here as
35984        // a build-time test failure at `aplicacao.rs`, not as an
35985        // apply-time `.get(<stale-canonical-const>)` returning `None`
35986        // far from the derive-attr drift's commit. Peer with the
35987        // sibling
35988        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
35989        // (ca463a4) and
35990        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
35991        // pins on the M3 collection-slot atom axes — same discipline
35992        // both collection-slot lifts established, extended here to the
35993        // singleton `:entrada` mesh-slot atom axis, the last M3
35994        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
35995        // axis on the Aplicacao surface without a lifted serde-key
35996        // peer.
35997        let e = Entrada {
35998            host: "checkout.quero.cloud".into(),
35999            para: "cart".into(),
36000            paths: vec!["/cart".into()],
36001            port: 8080,
36002        };
36003        let json = serde_json::to_string(&e).unwrap();
36004        for key in [
36005            crate::ENTRADA_KEY_HOST,
36006            crate::ENTRADA_KEY_PARA,
36007            crate::ENTRADA_KEY_PATHS,
36008            crate::ENTRADA_KEY_PORT,
36009        ] {
36010            let quoted = format!("\"{key}\"");
36011            assert!(
36012                json.contains(&quoted),
36013                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
36014                 byte-sequence {quoted} verbatim in the JSON emission \
36015                 (got: {json})",
36016            );
36017        }
36018    }
36019
36020    #[test]
36021    fn entrada_key_consts_are_pairwise_distinct() {
36022        // Cross-axis drift-detection pin: a future collapse of the four
36023        // canonical [`Entrada`] singleton byte-strings onto the same
36024        // value (e.g. an accidental copy-paste flip of
36025        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
36026        // silently reroute every downstream probe on one axis onto the
36027        // sibling axis's overlay entry and pass every propagation-probe
36028        // test that expected only the stale axis's value — the
36029        // Gateway/HTTPRoute emitter would read the hostname string
36030        // where the destination-Servico name was expected (or vice
36031        // versa), the admission-webhook cross-check would compare the
36032        // wrong pair of values, and the resulting Gateway resource
36033        // would either be admitted with garbage or rejected at the
36034        // controller far from the rebrand commit's source. Peer of the
36035        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
36036        // tetrad (40cc4e5), the two-way distinct pin on the
36037        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
36038        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
36039        // triad (ca463a4).
36040        let all = [
36041            crate::ENTRADA_KEY_HOST,
36042            crate::ENTRADA_KEY_PARA,
36043            crate::ENTRADA_KEY_PATHS,
36044            crate::ENTRADA_KEY_PORT,
36045        ];
36046        for (i, a) in all.iter().enumerate() {
36047            for b in all.iter().skip(i + 1) {
36048                assert_ne!(
36049                    a, b,
36050                    "ENTRADA_KEY_* consts must be pairwise-distinct \
36051                     canonical byte-sequences — got `{a}` == `{b}`",
36052                );
36053            }
36054        }
36055    }
36056
36057    #[test]
36058    fn entrada_key_consts_are_lower_camel_case_shape() {
36059        // Shape-pin: every `ENTRADA_KEY_*` const must be a
36060        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
36061        // `kebab-case` hyphens, no leading colon, no `PascalCase`
36062        // leading capital, no whitespace / dots) — the canonical shape
36063        // the `#[serde(rename_all = "camelCase")]` derive produces on
36064        // [`Entrada`]. A future flip to a non-camelCase attribute at
36065        // the derive surfaces both here (this test fails on the
36066        // stale-constant shape) and at
36067        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
36068        // test fails on the mismatch between const and derive). Peer
36069        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
36070        // and `contrato_key_consts_are_lower_camel_case_shape`
36071        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
36072        // entry axes.
36073        for key in [
36074            crate::ENTRADA_KEY_HOST,
36075            crate::ENTRADA_KEY_PARA,
36076            crate::ENTRADA_KEY_PATHS,
36077            crate::ENTRADA_KEY_PORT,
36078        ] {
36079            assert!(
36080                !key.is_empty(),
36081                "ENTRADA_KEY_* must be non-empty (got {key:?})"
36082            );
36083            let first = key.chars().next().unwrap();
36084            assert!(
36085                first.is_ascii_lowercase(),
36086                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
36087                 (got {key:?}, leads with {first:?})",
36088            );
36089            assert!(
36090                key.chars().all(|c| c.is_ascii_alphanumeric()),
36091                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
36092                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
36093            );
36094        }
36095    }
36096
36097    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
36098
36099    #[test]
36100    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
36101        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
36102        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
36103        // [`crate::POLITICAS_KEY_RETRIES`] /
36104        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
36105        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
36106        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
36107        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
36108        // on [`MeshPolicy`] emits. Three of the five axes
36109        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
36110        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
36111        // camelCase transforms — the derive-attribute is load-bearing
36112        // on those, unlike the sibling `Entrada` / `Membro` /
36113        // `WitContract` structs whose fields are all lowercase-single-
36114        // word and where the derive is a no-op on every axis.
36115        // Serialize a fully-populated [`MeshPolicy`] (every axis
36116        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
36117        // on none of the five slots) and pin that each canonical
36118        // byte-sequence appears verbatim in the JSON — a future
36119        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
36120        // verbatim-field-name flip at the derive attribute (any of
36121        // which would silently break every downstream JSON consumer
36122        // that reaches for one of the five consts via
36123        // `Value::get(...)` — the future M4 per-edge `:politicas`
36124        // overlay projection onto Cilium `L7Rules` and Gateway API
36125        // `HTTPRoute` backend timeouts, the future
36126        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
36127        // admission-time mesh-policy cross-check, the future
36128        // `feira lint` per-`:politicas` bound-check gate) surfaces here
36129        // as a build-time test failure at `aplicacao.rs`, not as an
36130        // apply-time `.get(<stale-canonical-const>)` returning `None`
36131        // far from the derive-attr drift's commit. Peer with the
36132        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
36133        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
36134        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
36135        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
36136        // atom axes — same discipline every M3 sibling lift
36137        // established, extended here to the singleton `:politicas`
36138        // mesh-slot atom axis, closing the last M3 typed-struct
36139        // top-level `#[serde(rename_all = "camelCase")]` axis on the
36140        // Aplicacao surface without a lifted serde-key peer.
36141        let p = MeshPolicy {
36142            timeout: Some(Duration::from_secs(30)),
36143            retries: Some(3),
36144            circuit_breaker: Some(CircuitBreaker {
36145                max_failures: 5,
36146                window: Duration::from_secs(60),
36147            }),
36148            mtls_required: Some(true),
36149            rate_limit: Some(RateLimit {
36150                rate: 100,
36151                window: Duration::from_secs(1),
36152            }),
36153        };
36154        let json = serde_json::to_string(&p).unwrap();
36155        for key in [
36156            crate::POLITICAS_KEY_TIMEOUT,
36157            crate::POLITICAS_KEY_RETRIES,
36158            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
36159            crate::POLITICAS_KEY_MTLS_REQUIRED,
36160            crate::POLITICAS_KEY_RATE_LIMIT,
36161        ] {
36162            let quoted = format!("\"{key}\"");
36163            assert!(
36164                json.contains(&quoted),
36165                "serialized MeshPolicy must carry the lifted \
36166                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
36167                 JSON emission (got: {json})",
36168            );
36169        }
36170    }
36171
36172    #[test]
36173    fn politicas_key_consts_are_pairwise_distinct() {
36174        // Cross-axis drift-detection pin: a future collapse of the five
36175        // canonical [`MeshPolicy`] singleton byte-strings onto the same
36176        // value (e.g. an accidental copy-paste flip of
36177        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
36178        // would silently reroute every downstream probe on one axis
36179        // onto the sibling axis's overlay entry and pass every
36180        // propagation-probe test that expected only the stale axis's
36181        // value — the M4 per-edge `:politicas` overlay projection would
36182        // read the retry-count string where the timeout duration was
36183        // expected (or vice versa), the CR materializer's admission
36184        // cross-check would compare the wrong pair of values, and the
36185        // resulting mesh reconciler would either bind the wrong axis
36186        // or reject the resource at reconcile far from the rebrand
36187        // commit's source. Peer of the sibling four-way distinct pin
36188        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
36189        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
36190        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
36191        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
36192        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
36193        let all = [
36194            crate::POLITICAS_KEY_TIMEOUT,
36195            crate::POLITICAS_KEY_RETRIES,
36196            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
36197            crate::POLITICAS_KEY_MTLS_REQUIRED,
36198            crate::POLITICAS_KEY_RATE_LIMIT,
36199        ];
36200        for (i, a) in all.iter().enumerate() {
36201            for b in all.iter().skip(i + 1) {
36202                assert_ne!(
36203                    a, b,
36204                    "POLITICAS_KEY_* consts must be pairwise-distinct \
36205                     canonical byte-sequences — got `{a}` == `{b}`",
36206                );
36207            }
36208        }
36209    }
36210
36211    #[test]
36212    fn politicas_key_consts_are_lower_camel_case_shape() {
36213        // Shape-pin: every `POLITICAS_KEY_*` const must be a
36214        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
36215        // `kebab-case` hyphens, no leading colon, no `PascalCase`
36216        // leading capital, no whitespace / dots) — the canonical shape
36217        // the `#[serde(rename_all = "camelCase")]` derive produces on
36218        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
36219        // at the derive surfaces both here (this test fails on the
36220        // stale-constant shape) and at
36221        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
36222        // (that test fails on the mismatch between const and derive).
36223        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
36224        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
36225        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
36226        // (ca463a4) on the sibling M3 typed-struct axes.
36227        for key in [
36228            crate::POLITICAS_KEY_TIMEOUT,
36229            crate::POLITICAS_KEY_RETRIES,
36230            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
36231            crate::POLITICAS_KEY_MTLS_REQUIRED,
36232            crate::POLITICAS_KEY_RATE_LIMIT,
36233        ] {
36234            assert!(
36235                !key.is_empty(),
36236                "POLITICAS_KEY_* must be non-empty (got {key:?})"
36237            );
36238            let first = key.chars().next().unwrap();
36239            assert!(
36240                first.is_ascii_lowercase(),
36241                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
36242                 byte (got {key:?}, leads with {first:?})",
36243            );
36244            assert!(
36245                key.chars().all(|c| c.is_ascii_alphanumeric()),
36246                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
36247                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
36248            );
36249        }
36250    }
36251
36252    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
36253
36254    #[test]
36255    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
36256        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
36257        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
36258        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
36259        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
36260        // [`CircuitBreaker`] emits inside the
36261        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
36262        // two axes (`max_failures` → `maxFailures`) is a non-trivial
36263        // camelCase transform — the derive-attribute is load-bearing on
36264        // that axis, unlike the sibling `window` field where the derive
36265        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
36266        // pin that each canonical byte-sequence appears verbatim in the
36267        // JSON — a future accidental `rename_all = "snake_case"` /
36268        // `"kebab-case"` / verbatim-field-name flip at the derive
36269        // attribute (any of which would silently break every downstream
36270        // JSON consumer that reaches for one of the two consts via
36271        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
36272        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
36273        // per-edge `:politicas` overlay projection onto the mesh's
36274        // per-backend consecutive-failure-counter tripping threshold, the
36275        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
36276        // admission-time breaker cross-check, the future `feira lint`
36277        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
36278        // here as a build-time test failure at `aplicacao.rs`, not as an
36279        // apply-time `.get(<stale-canonical-const>)` returning `None`
36280        // far from the derive-attr drift's commit. Peer with the sibling
36281        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
36282        // (b55cca7) parent-axis pin — that test pins the outer
36283        // sub-block key the derive on [`MeshPolicy`] emits, this test
36284        // pins the inner keys the derive on the payload type emits, so
36285        // the two together lock the whole [`MeshPolicy`] breaker-tuning
36286        // shape end-to-end at build time.
36287        let cb = CircuitBreaker {
36288            max_failures: 5,
36289            window: Duration::from_secs(60),
36290        };
36291        let json = serde_json::to_string(&cb).unwrap();
36292        for key in [
36293            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
36294            crate::CIRCUIT_BREAKER_KEY_WINDOW,
36295        ] {
36296            let quoted = format!("\"{key}\"");
36297            assert!(
36298                json.contains(&quoted),
36299                "serialized CircuitBreaker must carry the lifted \
36300                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
36301                 in the JSON emission (got: {json})",
36302            );
36303        }
36304    }
36305
36306    #[test]
36307    fn circuit_breaker_key_consts_are_pairwise_distinct() {
36308        // Cross-axis drift-detection pin: a future collapse of the two
36309        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
36310        // same value (e.g. an accidental copy-paste flip of
36311        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
36312        // `"maxFailures"`) would silently reroute every downstream
36313        // probe on one axis onto the sibling axis's overlay entry and
36314        // pass every propagation-probe test that expected only the
36315        // stale axis's value — the M4 per-edge `:politicas` overlay
36316        // projection would read the failure-count where the window
36317        // duration was expected (or vice versa), the CR materializer's
36318        // admission cross-check would compare the wrong pair of values,
36319        // and the resulting mesh reconciler would either bind the wrong
36320        // axis or reject the resource at reconcile far from the rebrand
36321        // commit's source. Peer of the sibling five-way distinct pin on
36322        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
36323        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
36324        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
36325        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
36326        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
36327        let all = [
36328            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
36329            crate::CIRCUIT_BREAKER_KEY_WINDOW,
36330        ];
36331        for (i, a) in all.iter().enumerate() {
36332            for b in all.iter().skip(i + 1) {
36333                assert_ne!(
36334                    a, b,
36335                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
36336                     canonical byte-sequences — got `{a}` == `{b}`",
36337                );
36338            }
36339        }
36340    }
36341
36342    #[test]
36343    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
36344        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
36345        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
36346        // `kebab-case` hyphens, no leading colon, no `PascalCase`
36347        // leading capital, no whitespace / dots) — the canonical shape
36348        // the `#[serde(rename_all = "camelCase")]` derive produces on
36349        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
36350        // at the derive surfaces both here (this test fails on the
36351        // stale-constant shape) and at
36352        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
36353        // (that test fails on the mismatch between const and derive).
36354        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
36355        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
36356        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
36357        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
36358        // (ca463a4) on the sibling M3 typed-struct axes.
36359        for key in [
36360            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
36361            crate::CIRCUIT_BREAKER_KEY_WINDOW,
36362        ] {
36363            assert!(
36364                !key.is_empty(),
36365                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
36366            );
36367            let first = key.chars().next().unwrap();
36368            assert!(
36369                first.is_ascii_lowercase(),
36370                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
36371                 byte (got {key:?}, leads with {first:?})",
36372            );
36373            assert!(
36374                key.chars().all(|c| c.is_ascii_alphanumeric()),
36375                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
36376                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
36377            );
36378        }
36379    }
36380
36381    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
36382
36383    #[test]
36384    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
36385        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
36386        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
36387        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
36388        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
36389        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
36390        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
36391        // [`Placement`] emits. One of the four axes (`shard_key` →
36392        // `shardKey`) is a non-trivial camelCase transform — the
36393        // derive-attribute is load-bearing on that axis, unlike the
36394        // sibling `estrategia` / `clusters` / `affinity` axes whose
36395        // source-side field names carry no `_` and where the derive is a
36396        // no-op. Serialize a fully-populated [`Placement`] (both
36397        // `Option`-carrying axes `Some(_)` so
36398        // `skip_serializing_if = "Option::is_none"` fires on neither of
36399        // the two optional slots) and pin that each canonical
36400        // byte-sequence appears verbatim in the JSON — a future
36401        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
36402        // verbatim-field-name flip at the derive attribute (any of which
36403        // would silently break every downstream consumer that reaches
36404        // for one of the four consts via
36405        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
36406        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
36407        // aggregator's per-cluster fanout filter keying off
36408        // `placement.clusters`, the M3 shard-pool dispatch materializer
36409        // keying off `placement.shardKey`, the M3 Adaptive compression
36410        // pass weighting off `placement.affinity`, every downstream
36411        // dispatcher branching on `placement.estrategia`, the future
36412        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
36413        // admission-time placement cross-check, the future `feira lint`
36414        // per-`:placement` bound-check gate) surfaces here as a
36415        // build-time test failure at `aplicacao.rs`, not as an
36416        // apply-time `.get(<stale-canonical-const>)` returning `None`
36417        // far from the derive-attr drift's commit. Peer with the sibling
36418        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
36419        // (b55cca7),
36420        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
36421        // (468e959),
36422        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
36423        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
36424        // (ca463a4), and
36425        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
36426        // pins on the M3 collection-slot / singleton-slot atom axes —
36427        // closes the last M3 typed-struct top-level
36428        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
36429        // surface without a drift-detection pin.
36430        let p = Placement {
36431            estrategia: PlacementStrategy::Sharded,
36432            clusters: vec!["rio".into(), "mar".into()],
36433            affinity: Some("data-locality".into()),
36434            shard_key: Some("$tenantId".into()),
36435        };
36436        let json = serde_json::to_string(&p).unwrap();
36437        for key in [
36438            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
36439            crate::M3_PLACEMENT_KEY_CLUSTERS,
36440            crate::M3_PLACEMENT_KEY_AFFINITY,
36441            crate::M3_PLACEMENT_KEY_SHARD_KEY,
36442        ] {
36443            let quoted = format!("\"{key}\"");
36444            assert!(
36445                json.contains(&quoted),
36446                "serialized Placement must carry the lifted \
36447                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
36448                 the JSON emission (got: {json})",
36449            );
36450        }
36451    }
36452
36453    #[test]
36454    fn m3_placement_key_consts_are_pairwise_distinct() {
36455        // Cross-axis drift-detection pin: a future collapse of the four
36456        // canonical [`Placement`] sub-block byte-strings onto the same
36457        // value (e.g. an accidental copy-paste flip of
36458        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
36459        // `"affinity"`) would silently reroute every downstream probe on
36460        // one axis onto the sibling axis's overlay entry and pass every
36461        // propagation-probe test that expected only the stale axis's
36462        // value — the M3 shard-pool dispatch materializer would read the
36463        // affinity placement-hint where the shard-selection template was
36464        // expected (or vice versa), the M3 Adaptive compression pass's
36465        // cross-check would compare the wrong pair of values, and the
36466        // resulting placement engine would either bind the wrong axis or
36467        // reject the resource at reconcile far from the rebrand commit's
36468        // source. Peer of the sibling two-way distinct pin on the
36469        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
36470        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
36471        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
36472        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
36473        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
36474        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
36475        let all = [
36476            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
36477            crate::M3_PLACEMENT_KEY_CLUSTERS,
36478            crate::M3_PLACEMENT_KEY_AFFINITY,
36479            crate::M3_PLACEMENT_KEY_SHARD_KEY,
36480        ];
36481        for (i, a) in all.iter().enumerate() {
36482            for b in all.iter().skip(i + 1) {
36483                assert_ne!(
36484                    a, b,
36485                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
36486                     canonical byte-sequences — got `{a}` == `{b}`",
36487                );
36488            }
36489        }
36490    }
36491
36492    #[test]
36493    fn m3_placement_key_consts_are_lower_camel_case_shape() {
36494        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
36495        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
36496        // `kebab-case` hyphens, no leading colon, no `PascalCase`
36497        // leading capital, no whitespace / dots) — the canonical shape
36498        // the `#[serde(rename_all = "camelCase")]` derive produces on
36499        // [`Placement`]. A future flip to a non-camelCase attribute at
36500        // the derive surfaces both here (this test fails on the stale-
36501        // constant shape) and at
36502        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
36503        // (that test fails on the mismatch between const and derive).
36504        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
36505        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
36506        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
36507        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
36508        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
36509        // (ca463a4) on the sibling M3 typed-struct axes.
36510        for key in [
36511            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
36512            crate::M3_PLACEMENT_KEY_CLUSTERS,
36513            crate::M3_PLACEMENT_KEY_AFFINITY,
36514            crate::M3_PLACEMENT_KEY_SHARD_KEY,
36515        ] {
36516            assert!(
36517                !key.is_empty(),
36518                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
36519            );
36520            let first = key.chars().next().unwrap();
36521            assert!(
36522                first.is_ascii_lowercase(),
36523                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
36524                 byte (got {key:?}, leads with {first:?})",
36525            );
36526            assert!(
36527                key.chars().all(|c| c.is_ascii_alphanumeric()),
36528                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
36529                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
36530            );
36531        }
36532    }
36533
36534    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
36535    //    destination-facing L4 port resolver every per-Aplicacao renderer
36536    //    reaching for a per-destination Servico TCP port axis routes
36537    //    through. The four pin tests below fix the four-way accept-set
36538    //    the resolver must always honor: (:entrada-para-matches,
36539    //    :entrada-para-mismatches, :entrada-none-so-fallback,
36540    //    :entrada-port-non-default-honored) — drift on any arm surfaces
36541    //    at caixa-core build time rather than at cluster-apply time.
36542
36543    #[test]
36544    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
36545        // The typed `:entrada` block's `:para "cart"` matches the
36546        // queried destination, so the resolver returns the author-
36547        // declared `:port` scalar verbatim — the canonical "the
36548        // destination Servico IS the ingress apex, honor the typed
36549        // listener port" arm of the port-resolution dispatch.
36550        let mut spec = three_member_spec();
36551        if let Some(e) = spec.entrada.as_mut() {
36552            e.para = "cart".into();
36553            e.port = 9090;
36554        }
36555        assert_eq!(
36556            spec.port_for_destination("cart"),
36557            9090,
36558            "port_for_destination(entrada.para) must return entrada.port \
36559             verbatim, not the DEFAULT_SERVICO_PORT fallback"
36560        );
36561    }
36562
36563    #[test]
36564    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
36565        // The typed `:entrada` block names `:para "cart"`, but the
36566        // queried destination is `"payment"` — a Servico that
36567        // participates in the mesh graph but is not the ingress apex.
36568        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
36569        // canonical port floor, closing the "non-apex destination reads
36570        // the substrate default" arm. Same fixture the peer
36571        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
36572        // pin at caixa-mesh exercises through the CNP emit-side path;
36573        // this pin exercises the shared underlying resolver directly.
36574        let spec = three_member_spec();
36575        assert_eq!(
36576            spec.port_for_destination("payment"),
36577            DEFAULT_SERVICO_PORT,
36578            "port_for_destination(non-apex-destination) must route \
36579             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
36580        );
36581    }
36582
36583    #[test]
36584    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
36585        // Internal-only Aplicacao — no `:entrada` block declared. Every
36586        // per-destination port query falls back to the lifted
36587        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
36588        // the Aplicacao surface admits `:entrada None` (internal mesh
36589        // with no external gateway); every downstream renderer's per-
36590        // destination port axis must still resolve to a well-defined
36591        // scalar even without an ingress apex.
36592        let mut spec = three_member_spec();
36593        spec.entrada = None;
36594        assert_eq!(
36595            spec.port_for_destination("cart"),
36596            DEFAULT_SERVICO_PORT,
36597            "port_for_destination on an internal-only Aplicacao must \
36598             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
36599             every destination"
36600        );
36601        assert_eq!(
36602            spec.port_for_destination("payment"),
36603            DEFAULT_SERVICO_PORT,
36604            "port_for_destination on an internal-only Aplicacao must \
36605             fall back uniformly across every destination — the fallback \
36606             is not entrada-shape-conditional"
36607        );
36608    }
36609
36610    #[test]
36611    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
36612        // Structural pin against a hypothetical future refactor that
36613        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
36614        // the resolver (a "normalize to the default when the author's
36615        // port matches the substrate default" collapse) — that would
36616        // break renderer sites that carry meaning on the emitted port
36617        // value beyond bare equality (a future per-cluster listener-
36618        // audit that keys off the author-declared port, not the
36619        // resolved-with-fallback port). Pin that a non-default
36620        // entrada.port is returned verbatim so drift here surfaces at
36621        // caixa-core build time.
36622        let mut spec = three_member_spec();
36623        if let Some(e) = spec.entrada.as_mut() {
36624            e.para = "cart".into();
36625            e.port = 8443;
36626        }
36627        assert_ne!(
36628            8443, DEFAULT_SERVICO_PORT,
36629            "test fixture must probe a port distinct from \
36630             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
36631        );
36632        assert_eq!(
36633            spec.port_for_destination("cart"),
36634            8443,
36635            "port_for_destination(entrada.para) must return entrada.port \
36636             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
36637        );
36638    }
36639
36640    #[test]
36641    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
36642        // Apex-identity pair-invariant pin composing both substrate-
36643        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
36644        // and [`Entrada::destination`] — at the emit-side call shape
36645        // every per-Aplicacao renderer's ingress-apex L4 port reader
36646        // now takes. The invariant:
36647        //
36648        //   spec.port_for_destination(entrada.destination()) == entrada.port
36649        //
36650        // holds by construction under today's single-destination
36651        // `:entrada` slot (`destination()` returns `entrada.para`, and
36652        // the resolver's apex arm matches `para == destination` and
36653        // returns `entrada.port`), and every downstream consumer that
36654        // composes the two accessors at the ingress apex — the
36655        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
36656        // `backendRefs[0].port` emit-site path, the peer future M4 CR
36657        // materializer's admission-webhook that promotes the scalar to
36658        // a per-CR override overlay, every future per-Aplicacao snapshot
36659        // renderer's apex-facing L4 port reader — reaches through the
36660        // same composition. Pin the identity across four permutations
36661        // (`:para` × `:port` including a non-default port to exercise
36662        // the honor-verbatim arm and a non-cart `:para` to exercise
36663        // destination-agnostic identity) so a future refactor that
36664        // silently split either accessor's apex behavior surfaces at
36665        // caixa-core build time — a subtle `destination()` renaming
36666        // that returned `entrada.host.as_str()` instead of
36667        // `entrada.para.as_str()` would blow this pin loudly, closing
36668        // the last quiet failure mode the two lifts admit in composition.
36669        //
36670        // Peer discipline with the sibling caixa-mesh cross-crate pin
36671        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
36672        // on the two-renderer pair-invariant axis; this pin encodes the
36673        // same two-consumer coherence rule at the substrate-primitive
36674        // level so the invariant survives even if every renderer is
36675        // deleted.
36676        for (para, port) in [
36677            ("cart", DEFAULT_SERVICO_PORT),
36678            ("cart", 8443u16),
36679            ("payment", 9090u16),
36680            ("catalog", 443u16),
36681        ] {
36682            let mut spec = three_member_spec();
36683            if let Some(e) = spec.entrada.as_mut() {
36684                e.para = para.into();
36685                e.port = port;
36686            }
36687            let expected_port = spec
36688                .entrada()
36689                .expect("three_member_spec carries a typed `:entrada` block")
36690                .port();
36691            let composed_port = {
36692                let entrada = spec.entrada().expect("entrada present");
36693                spec.port_for_destination(entrada.destination())
36694            };
36695            assert_eq!(
36696                composed_port, expected_port,
36697                "`spec.port_for_destination(entrada.destination())` must \
36698                 equal `entrada.port` under today's single-destination \
36699                 `:entrada` slot — this is the apex-identity contract \
36700                 every downstream ingress-apex L4 port reader relies on. \
36701                 Input :entrada :para: {para:?}, :entrada :port: {port}"
36702            );
36703        }
36704    }
36705
36706    #[test]
36707    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
36708        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
36709        // per-`:entrada` apex-arm membership probe must key off
36710        // [`Entrada::destination`], not the raw `.para` field access.
36711        // Structurally: setting ONLY the `:entrada :para` field to a
36712        // fresh non-cart destination on an otherwise-well-formed
36713        // Aplicacao must (1) leave `e.destination()` byte-equal to
36714        // `e.para.as_str()` (the accessor is byte-projective by
36715        // definition), and (2) cause the resolver's apex arm to fire
36716        // and return `entrada.port` at exactly that new destination
36717        // while every other destination string falls through to
36718        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
36719        // membership check. Pins against a future silent detour that
36720        // (a) re-derived the apex-arm membership probe off
36721        // `e.para == destination` in `port_for_destination` instead of
36722        // `e.destination() == destination`, silently disagreeing with
36723        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
36724        // consumers (`entrada.destination()` at
36725        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
36726        // caixa-mesh/src/lib.rs:2739) that already reach through the
36727        // accessor, (b) accessor-side introduced a per-tenant alias
36728        // arm the caller was unaware of, silently rewriting an
36729        // author-declared `:para "cart"` value to a canary-aliased
36730        // form — the raw-field-access resolver would fall through to
36731        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
36732        // while the peer emit-site consumers landed on the aliased
36733        // destination, splitting the ingress-apex L4 port at
36734        // cluster-apply time.
36735        //
36736        // Peer of the sibling
36737        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
36738        // (d0de220) composition pin on the per-`:membros` refusal-arm
36739        // axis — same "the shape-gate predicate must route through the
36740        // substrate-primitive typed dispatch" discipline extended onto
36741        // the per-`:entrada` apex-arm membership-probe axis. Closes
36742        // the last unlifted `.para` production-code read site on
36743        // `Entrada` in `caixa-core` — after this converge every
36744        // `caixa-core` `.para` field access outside the accessor's own
36745        // body and outside the `WitContract` per-`:contratos` sibling
36746        // axis is either a test-side field-setter or a doc-comment
36747        // reference.
36748        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
36749            let mut spec = three_member_spec();
36750            if let Some(e) = spec.entrada.as_mut() {
36751                e.para = para.into();
36752                e.port = port;
36753            }
36754            let e = spec
36755                .entrada
36756                .as_ref()
36757                .expect("three_member_spec carries a typed `:entrada` block");
36758            assert_eq!(
36759                e.destination(),
36760                e.para.as_str(),
36761                "Entrada::destination must byte-equal the .para field \
36762                 access — an accessor-side detour that no longer \
36763                 projects the raw field would silently split this \
36764                 drift-detection test from the port_for_destination \
36765                 apex-arm membership probe",
36766            );
36767            assert_eq!(
36768                spec.port_for_destination(para),
36769                port,
36770                "port_for_destination must key off the accessor-projected \
36771                 destination and return `entrada.port` on the apex arm — \
36772                 input :entrada :para: {para:?}, :entrada :port: {port}",
36773            );
36774            assert_eq!(
36775                spec.port_for_destination("ghost-destination-never-a-member"),
36776                DEFAULT_SERVICO_PORT,
36777                "port_for_destination must fall through to \
36778                 DEFAULT_SERVICO_PORT on a non-matching destination \
36779                 under the accessor-projected membership check — input \
36780                 :entrada :para: {para:?}, :entrada :port: {port}",
36781            );
36782        }
36783    }
36784
36785    #[test]
36786    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
36787        // The canonical per-`:politicas :rate-limit` `:rate`
36788        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
36789        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
36790        // typed `u32` verbatim, byte-equal to the raw field access
36791        // across every representative value in the accept-set — `1` (the
36792        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
36793        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
36794        // carves out on the sibling `PolicyRateLimitZero` refusal),
36795        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
36796        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
36797        // `0` (a past-the-guard sentinel that pins the accessor doesn't
36798        // perform a silent bounds-collapse into `1` on the zero arm —
36799        // validate rejects zero but the accessor must ship the raw slot
36800        // verbatim so a validate-time gate regression surfaces at the
36801        // emit boundary rather than being silently absorbed), `u32::MAX`
36802        // (a past-the-guard sentinel that pins the accessor doesn't
36803        // perform a silent bounds-collapse through
36804        // `POLICY_RATE_LIMIT_MAX` at the return path).
36805        //
36806        // First sub-struct required-scalar accessor pin on the
36807        // `RateLimit` axis — sibling in shape to the peer
36808        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
36809        // required-`u32` accessor pin on the peer per-sub-struct
36810        // required-axis. Pins against a future silent detour that
36811        // re-derived the token capacity from a peer axis (an accidental
36812        // `self.window.as_secs() as u32` collapse that read the
36813        // rate-limit window duration as a token count), a `0 → 1`
36814        // cluster-default projection (which would silently absorb the
36815        // `PolicyRateLimitZero` refusal case at the accessor boundary),
36816        // or a bounds-collapsing accessor that clamped the return
36817        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
36818        // gate owns the bounds; the accessor must ship the raw slot
36819        // verbatim).
36820        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
36821            let rl = RateLimit {
36822                rate,
36823                window: Duration::from_secs(1),
36824            };
36825            assert_eq!(
36826                rl.rate(),
36827                rate,
36828                "RateLimit::rate must return :politicas :rate-limit :rate \
36829                 verbatim (got {}, expected {rate})",
36830                rl.rate(),
36831            );
36832            assert_eq!(
36833                rl.rate(),
36834                rl.rate,
36835                "RateLimit::rate must byte-equal the raw .rate field \
36836                 access across every value in the u32 accept-set",
36837            );
36838        }
36839    }
36840
36841    #[test]
36842    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
36843        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
36844        // `:rate-limit :rate` zero-floor arm must key off
36845        // [`RateLimit::rate`], not the raw `.rate` field access.
36846        // Structurally: a `RateLimit { rate: 0, window:
36847        // Duration::from_secs(1) }` embedded in a `:politicas
36848        // :rate-limit` slot must surface the `PolicyRateLimitZero`
36849        // refusal exactly, and a `RateLimit { rate: 1, window:
36850        // Duration::from_secs(1) }` (the lower boundary of the
36851        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
36852        // The pair jointly pins the accessor + validate-gate composition:
36853        // any future silent detour that had the accessor return a fresh
36854        // `1` on the zero arm (a `.rate().max(1)` collapse) would
36855        // silently absorb the `PolicyRateLimitZero` refusal at the
36856        // accessor boundary and the validate gate would accept a
36857        // struct-literal `RateLimit { rate: 0, .. }` — the composition
36858        // pin catches that at caixa-core build time.
36859        //
36860        // Peer of the sibling per-`CircuitBreaker`
36861        // [`CircuitBreaker::max_failures`] (3a74062) /
36862        // [`CircuitBreaker::window`] (373957f) accessor-composition
36863        // pins on the peer required-scalar axes — same "the validate /
36864        // shape-gate predicate must route through the substrate-primitive
36865        // typed dispatch" discipline extended onto the peer
36866        // per-`RateLimit` required-`u32` composition axis.
36867        let mut spec = three_member_spec();
36868        spec.politicas = MeshPolicy {
36869            rate_limit: Some(RateLimit {
36870                rate: 0,
36871                window: Duration::from_secs(1),
36872            }),
36873            ..MeshPolicy::default()
36874        };
36875        assert!(
36876            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
36877            "validate_politicas must reject rate == 0 with \
36878             PolicyRateLimitZero — the accessor and the validate gate \
36879             must route through the same substrate-primitive typed \
36880             dispatch on the :rate zero-floor arm",
36881        );
36882        spec.politicas = MeshPolicy {
36883            rate_limit: Some(RateLimit {
36884                rate: 1,
36885                window: Duration::from_secs(1),
36886            }),
36887            ..MeshPolicy::default()
36888        };
36889        assert!(
36890            spec.validate().is_ok(),
36891            "validate_politicas must accept rate == 1 (the lower \
36892             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
36893        );
36894    }
36895
36896    #[test]
36897    fn rate_limit_rate_projects_u32_by_copy() {
36898        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
36899        // `u32` is `Copy` and the accessor must return by value, not by
36900        // reference. Peer of the sibling per-`CircuitBreaker`
36901        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
36902        // peer required-scalar `:max-failures` axis, extended onto the
36903        // peer per-`RateLimit` required-`u32` copy-invariant shape —
36904        // the accessor's returned `u32` must outlive `&self` (multiple
36905        // calls must return equal values from a dropped-`&self` copy,
36906        // since the returned scalar carries no borrow), and calling the
36907        // accessor twice on the same RateLimit must yield the same
36908        // `u32` verbatim (idempotent, no side effects on `&self`).
36909        //
36910        // Pins against a future silent detour that returned `&u32`
36911        // (which would type-check but silently break every downstream
36912        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
36913        // first parameter is `u32`, and `&u32` would fold to a detached
36914        // copy at the call site with a `*` deref the sibling accessors
36915        // don't need), an accidental `.rate.wrapping_add(0)` detour that
36916        // returned a fresh copy through an arithmetic no-op (breaking a
36917        // future `const fn` regression), or a one-arm-only accessor
36918        // that returned a saturating value on some sentinel input
36919        // (breaking the pass-through invariant the sibling required-
36920        // scalar accessors carry).
36921        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
36922            let rl = RateLimit {
36923                rate,
36924                window: Duration::from_secs(1),
36925            };
36926            let first = rl.rate();
36927            let second = rl.rate();
36928            assert_eq!(
36929                first, second,
36930                "RateLimit::rate must be idempotent — two successive \
36931                 calls on the same &self must return the same u32",
36932            );
36933            assert_eq!(
36934                first, rate,
36935                "RateLimit::rate must return :politicas :rate-limit :rate \
36936                 verbatim by copy — got {first}, expected {rate}",
36937            );
36938        }
36939    }
36940
36941    #[test]
36942    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
36943        // The canonical per-`:politicas :rate-limit` `:window`
36944        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
36945        // pin: [`RateLimit::window`] must return the
36946        // `:politicas :rate-limit :window` typed `Duration` verbatim,
36947        // byte-equal to the raw field access across every
36948        // representative value in the accept-set — `Duration::from_secs(1)`
36949        // (the `"s"` canonical window, the lower row of
36950        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
36951        // [`AplicacaoSpec::validate_politicas`] gate accepts via
36952        // [`is_canonical_rate_limit_window`]),
36953        // `Duration::from_secs(60)` (the `"m"` canonical window, the
36954        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
36955        // window, the upper row), `Duration::ZERO` (a past-the-guard
36956        // sentinel that pins the accessor doesn't perform a silent
36957        // bounds-collapse into `Duration::from_secs(1)` on the zero
36958        // arm — validate rejects an off-set window through
36959        // `PolicyRateLimitWindowNotCanonical` but the accessor must
36960        // ship the raw slot verbatim so a validate-time gate
36961        // regression surfaces at the emit boundary rather than being
36962        // silently absorbed), `Duration::from_millis(500)` (a
36963        // sub-canonical past-the-guard sentinel that pins the accessor
36964        // doesn't silently normalize a non-canonical fractional
36965        // magnitude onto the nearest canonical row).
36966        //
36967        // Second sub-struct required-scalar accessor pin on the
36968        // `RateLimit` axis — sibling in shape to the just-landed
36969        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
36970        // accessor pin on the peer per-sub-struct required-axis,
36971        // extended onto the per-`RateLimit` required-`Duration` axis.
36972        // Pins against a future silent detour that re-derived the
36973        // refill period from a peer axis (an accidental
36974        // `Duration::from_secs(self.rate as u64)` collapse that read
36975        // the rate-limit token capacity as a refill-interval
36976        // duration), a `Duration::ZERO → Duration::from_secs(1)`
36977        // canonical-default projection (which would silently absorb
36978        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
36979        // accessor boundary), or a canonical-set-collapsing accessor
36980        // that clamped the return through [`rate_limit_window_unit`]
36981        // (the `AplicacaoSpec::validate` gate owns the canonical-set
36982        // membership; the accessor must ship the raw slot verbatim).
36983        for window in [
36984            Duration::from_secs(1),
36985            Duration::from_secs(60),
36986            Duration::from_secs(3600),
36987            Duration::ZERO,
36988            Duration::from_millis(500),
36989        ] {
36990            let rl = RateLimit { rate: 100, window };
36991            assert_eq!(
36992                rl.window(),
36993                window,
36994                "RateLimit::window must return :politicas :rate-limit :window \
36995                 verbatim (got {:?}, expected {window:?})",
36996                rl.window(),
36997            );
36998            assert_eq!(
36999                rl.window(),
37000                rl.window,
37001                "RateLimit::window must byte-equal the raw .window field \
37002                 access across every value in the Duration accept-set",
37003            );
37004        }
37005    }
37006
37007    #[test]
37008    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
37009        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
37010        // `:rate-limit :window` canonical-set arm must key off
37011        // [`RateLimit::window`], not the raw `.window` field access.
37012        // Structurally: a `RateLimit { window: Duration::from_millis(500),
37013        // .. }` embedded in a `:politicas :rate-limit` slot must
37014        // surface the `PolicyRateLimitWindowNotCanonical` refusal
37015        // exactly (with the sub-canonical `Duration::from_millis(500)`
37016        // magnitude carried through verbatim), and a `RateLimit
37017        // { window: Duration::from_secs(1), .. }` (the lower row of
37018        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
37019        // The pair jointly pins the accessor + validate-gate
37020        // composition: any future silent detour that had the accessor
37021        // normalize the off-set window to the nearest canonical row
37022        // (a `.window().max(Duration::from_secs(1))` collapse, or a
37023        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
37024        // collapse) would silently absorb the
37025        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
37026        // boundary — including a drift in the error's `window` payload
37027        // (the emit-side diagnostic reader keys off the offending
37028        // magnitude verbatim, so a normalization at the accessor
37029        // boundary would silently pin the wrong magnitude in the
37030        // refusal). The composition pin catches that at caixa-core
37031        // build time.
37032        //
37033        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
37034        // (7f81a60) accessor-composition pin on the peer required-
37035        // scalar `:rate` axis — same "the validate / shape-gate
37036        // predicate must route through the substrate-primitive typed
37037        // dispatch, and the error payload must project through the
37038        // same accessor" discipline extended onto the peer
37039        // per-`RateLimit` required-`Duration` composition axis.
37040        let mut spec = three_member_spec();
37041        spec.politicas = MeshPolicy {
37042            rate_limit: Some(RateLimit {
37043                rate: 100,
37044                window: Duration::from_millis(500),
37045            }),
37046            ..MeshPolicy::default()
37047        };
37048        match spec.validate() {
37049            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
37050                assert_eq!(
37051                    window,
37052                    Duration::from_millis(500),
37053                    "PolicyRateLimitWindowNotCanonical must carry the \
37054                     offending :window magnitude verbatim through the \
37055                     accessor — got {window:?}, expected 500ms",
37056                );
37057            }
37058            other => panic!(
37059                "validate_politicas must reject non-canonical :window \
37060                 with PolicyRateLimitWindowNotCanonical — the accessor \
37061                 and the validate gate must route through the same \
37062                 substrate-primitive typed dispatch on the :window \
37063                 canonical-set arm; got {other:?}",
37064            ),
37065        }
37066        spec.politicas = MeshPolicy {
37067            rate_limit: Some(RateLimit {
37068                rate: 100,
37069                window: Duration::from_secs(1),
37070            }),
37071            ..MeshPolicy::default()
37072        };
37073        assert!(
37074            spec.validate().is_ok(),
37075            "validate_politicas must accept window == Duration::from_secs(1) \
37076             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
37077        );
37078    }
37079
37080    #[test]
37081    fn rate_limit_window_projects_duration_by_copy() {
37082        // The by-copy pin: [`RateLimit::window`] returns `Duration`
37083        // by copy — `Duration` is `Copy` and the accessor must return
37084        // by value, not by reference. Peer of the sibling per-`RateLimit`
37085        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
37086        // required-scalar `:rate` axis, extended onto the peer
37087        // per-`RateLimit` required-`Duration` copy-invariant shape —
37088        // the accessor's returned `Duration` must outlive `&self`
37089        // (multiple calls must return equal values from a
37090        // dropped-`&self` copy, since the returned scalar carries no
37091        // borrow), and calling the accessor twice on the same
37092        // RateLimit must yield the same `Duration` verbatim
37093        // (idempotent, no side effects on `&self`).
37094        //
37095        // Pins against a future silent detour that returned
37096        // `&Duration` (which would type-check but silently break every
37097        // downstream `Duration`-by-value consumer —
37098        // [`is_canonical_rate_limit_window`]'s first parameter is
37099        // `Duration`, and `&Duration` would fold to a detached copy at
37100        // the call site with a `*` deref the sibling accessors don't
37101        // need), an accidental `.window + Duration::ZERO` detour that
37102        // returned a fresh copy through an arithmetic no-op (breaking
37103        // a future `const fn` regression), or a one-arm-only accessor
37104        // that returned a canonical fallback on some sentinel input
37105        // (breaking the pass-through invariant the sibling required-
37106        // scalar accessors carry).
37107        for window in [
37108            Duration::from_secs(1),
37109            Duration::from_secs(60),
37110            Duration::from_secs(3600),
37111            Duration::ZERO,
37112            Duration::from_millis(500),
37113        ] {
37114            let rl = RateLimit { rate: 100, window };
37115            let first = rl.window();
37116            let second = rl.window();
37117            assert_eq!(
37118                first, second,
37119                "RateLimit::window must be idempotent — two successive \
37120                 calls on the same &self must return the same Duration",
37121            );
37122            assert_eq!(
37123                first, window,
37124                "RateLimit::window must return :politicas :rate-limit :window \
37125                 verbatim by copy — got {first:?}, expected {window:?}",
37126            );
37127        }
37128    }
37129
37130    #[test]
37131    fn placement_estrategia_default_pins_m3_canonical_value() {
37132        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
37133        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
37134        // active-active-across-every-named-cluster arm, the closest
37135        // canonical M3 production reference the substrate carries and
37136        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
37137        // for every un-`:placement`-declared Aplicacao. Pinning the arm
37138        // here surfaces a future rebrand of the M3-canonical
37139        // distribution default (a widening to `Sharded` once the
37140        // substrate discovers hash-keyed distribution as the more
37141        // common production shape, a tightening to `SingleNode` for
37142        // stateful Erlang/OTP distributed-app-takeover semantics
37143        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
37144        // operator pins through a future `:placement-overrides` slot)
37145        // as a deliberate test edit, not a silent contract migration.
37146        // Peer of the sibling M2 per-supervisor value pins
37147        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
37148        // /
37149        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
37150        // extended onto the M3 mesh-primitive-defining `:placement
37151        // :estrategia` axis.
37152        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
37153    }
37154
37155    #[test]
37156    fn placement_strategy_default_routes_through_lifted_default() {
37157        // Composition pin: the [`Default for PlacementStrategy`] impl's
37158        // return arm must route through the substrate-canonical
37159        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
37160        // a raw `Self::Replicated` arm. Prior to the lift the impl
37161        // carried an inline `Self::Replicated` arm with no compile-time
37162        // link back to the shared M3-canonical `Replicated` arm the
37163        // paired [`Default for Placement`] impl's struct-literal
37164        // `estrategia` field, the serde-side `#[serde(default)]` on
37165        // [`Placement::estrategia`] that resolves an author-omitted
37166        // wire-form `:placement :estrategia` scalar through the impl,
37167        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
37168        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
37169        // routes through [`Placement::default`] which routes through the
37170        // strategy default) all key off — so a future rebrand of the
37171        // M3-canonical distribution default would have had to be threaded
37172        // through the `Default` impl and the three peer routes in
37173        // lockstep or the four consumers would silently split. Byte-
37174        // parity against the lifted constant closes the split. Peer of
37175        // the sibling
37176        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
37177        // /
37178        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
37179        // composition pins on the M2 per-supervisor axes.
37180        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
37181    }
37182
37183    #[test]
37184    fn placement_default_estrategia_routes_through_lifted_default() {
37185        // Composition pin: the [`Default for Placement`] impl's
37186        // struct-literal `estrategia` field must route through the
37187        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
37188        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
37189        // impl that the sibling
37190        // `placement_strategy_default_routes_through_lifted_default` pin
37191        // already routes onto the constant). Structurally: every
37192        // `Placement::default()` call must yield an `estrategia` field
37193        // byte-equal to the lifted constant so the two paired defaults —
37194        // the [`Default for PlacementStrategy`] impl arm and the
37195        // struct-literal default arm here — cannot silently split on any
37196        // future M3-canonical distribution-default rebrand. Peer of the
37197        // sibling M2
37198        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
37199        // byte-parity pin on the [`Default for SupervisorSpec`]
37200        // struct-literal `estrategia` field extended onto the M3
37201        // mesh-primitive-defining slot family.
37202        assert_eq!(
37203            Placement::default().estrategia,
37204            PLACEMENT_ESTRATEGIA_DEFAULT,
37205        );
37206    }
37207
37208    #[test]
37209    fn placement_serde_default_estrategia_routes_through_lifted_default() {
37210        // Composition pin: the serde-side `#[serde(default)]` on
37211        // [`Placement::estrategia`] — the wire-format author-omitted
37212        // `:placement :estrategia` arm — must resolve onto the substrate-
37213        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
37214        // (via the [`Default for PlacementStrategy`] impl the sibling
37215        // `placement_strategy_default_routes_through_lifted_default` pin
37216        // already routes onto the constant). Structurally: a `Placement`
37217        // deserialized from a payload that omits the `estrategia` key
37218        // must yield an `estrategia` field byte-equal to the lifted
37219        // constant, so the wire-format author-omitted arm and the
37220        // [`PlacementStrategy::default`] impl arm cannot silently split
37221        // on any future M3-canonical distribution-default rebrand. Peer
37222        // of the sibling M2
37223        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
37224        // byte-parity pin on the wire-format author-omitted `:children
37225        // :restart` scalar extended onto the M3 mesh-primitive-defining
37226        // slot family.
37227        let omitted: Placement = serde_json::from_str("{}")
37228            .expect("Placement must deserialize with the estrategia key omitted");
37229        assert_eq!(
37230            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
37231            "an author-omitted :placement :estrategia slot must degrade onto \
37232             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
37233             {:?}, expected {:?})",
37234            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
37235        );
37236    }
37237
37238    // ── contrato_target_ctors! fold pins ────────────────────────────────
37239    //
37240    // Fixture edge triple + payload-field-name label pair for every
37241    // `contrato_target_ctors!`-generated ctor pin below. Kept as
37242    // non-default `("cart", "catalog", "wasi:http/proxy")` +
37243    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
37244    // the fixture default doesn't silently pass. Peer of the sibling
37245    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
37246    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
37247    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
37248    // `missing_entry_ctor_matches_struct_literal_wrap` /
37249    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
37250    // four `LayoutError` constructor families each closed on their
37251    // sibling envelopes.
37252    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
37253        (
37254            "cart".to_string(),
37255            "catalog".to_string(),
37256            "wasi:http/proxy".to_string(),
37257            WitTarget::HTTP_FIELD_NAME,
37258        )
37259    }
37260
37261    #[test]
37262    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
37263        // Equivalence pin: the ctor produces byte-equal
37264        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
37265        // coded struct-literal on the same edge fixture, so the fold
37266        // cannot silently drift on any future field-addition /
37267        // reordering / string-conversion tweak on the variant. Peer of
37268        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
37269        // (17dd504) / the four `LayoutError` family equivalence pins.
37270        let (de, para, wit, expected) = contrato_target_ctor_fixture();
37271        let lifted = AplicacaoError::contrato_wrong_target(
37272            (de.clone(), para.clone(), wit.clone()),
37273            expected,
37274        );
37275        let struct_literal = AplicacaoError::ContratoWrongTarget {
37276            de,
37277            para,
37278            wit,
37279            expected,
37280        };
37281        assert_eq!(lifted, struct_literal);
37282    }
37283
37284    #[test]
37285    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
37286        // Equivalence pin peer of the sibling
37287        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
37288        // on the paired `ContratoMissingTarget` variant of the same
37289        // four-slot envelope shape the `contrato_target_ctors!` macro
37290        // closes.
37291        let (de, para, wit, expected) = contrato_target_ctor_fixture();
37292        let lifted = AplicacaoError::contrato_missing_target(
37293            (de.clone(), para.clone(), wit.clone()),
37294            expected,
37295        );
37296        let struct_literal = AplicacaoError::ContratoMissingTarget {
37297            de,
37298            para,
37299            wit,
37300            expected,
37301        };
37302        assert_eq!(lifted, struct_literal);
37303    }
37304
37305    #[test]
37306    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
37307        // Routing pin: the `(de, para, wit)` triple threads verbatim
37308        // onto same-named fields on both generated ctors, no wrapper-
37309        // side lowercase / trim / re-order. Sweeps a non-default triple
37310        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
37311        // wrapper-side transformation surfaces here rather than at a
37312        // downstream diagnostic-shape drift. Sibling of
37313        // `entrada_host_invalid_ctor_routes_host_through_to_string`
37314        // (17dd504) on the paired triple-carrying envelope.
37315        let edge = (
37316            "cart-svc".to_string(),
37317            "catalog-v2".to_string(),
37318            "nats:pub-sub".to_string(),
37319        );
37320        let wrong =
37321            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
37322        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
37323        let AplicacaoError::ContratoWrongTarget {
37324            de: wde,
37325            para: wpara,
37326            wit: wwit,
37327            ..
37328        } = wrong
37329        else {
37330            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
37331        };
37332        let AplicacaoError::ContratoMissingTarget {
37333            de: mde,
37334            para: mpara,
37335            wit: mwit,
37336            ..
37337        } = missing
37338        else {
37339            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
37340        };
37341        assert_eq!(wde, "cart-svc");
37342        assert_eq!(wpara, "catalog-v2");
37343        assert_eq!(wwit, "nats:pub-sub");
37344        assert_eq!(mde, "cart-svc");
37345        assert_eq!(mpara, "catalog-v2");
37346        assert_eq!(mwit, "nats:pub-sub");
37347    }
37348
37349    #[test]
37350    fn contrato_target_ctors_route_expected_through_verbatim() {
37351        // Routing pin: the `expected: &'static str` label threads
37352        // verbatim (identity, not copy-and-transform) onto the
37353        // `expected` field of both variants, so the four canonical
37354        // labels [`WitTarget::HTTP_FIELD_NAME`] /
37355        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
37356        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
37357        // pointer-equal (not merely value-equal) references — a wrapper-
37358        // side `.to_string()` / `Cow::Owned` promotion would break the
37359        // `&'static str` contract downstream consumers depend on.
37360        for label in [
37361            WitTarget::HTTP_FIELD_NAME,
37362            WitTarget::PUBSUB_FIELD_NAME,
37363            WitTarget::STORE_FIELD_NAME,
37364            WitTarget::CAPABILITY_EXPECTED,
37365        ] {
37366            let (de, para, wit, _) = contrato_target_ctor_fixture();
37367            let wrong = AplicacaoError::contrato_wrong_target(
37368                (de.clone(), para.clone(), wit.clone()),
37369                label,
37370            );
37371            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
37372            match wrong {
37373                AplicacaoError::ContratoWrongTarget { expected, .. } => {
37374                    assert!(
37375                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
37376                            && expected.len() == label.len(),
37377                        "contrato_wrong_target must thread the &'static str \
37378                         label pointer-equal onto the `expected` field \
37379                         (label = {label:?})",
37380                    );
37381                }
37382                other => panic!("expected ContratoWrongTarget, got {other:?}"),
37383            }
37384            match missing {
37385                AplicacaoError::ContratoMissingTarget { expected, .. } => {
37386                    assert!(
37387                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
37388                            && expected.len() == label.len(),
37389                        "contrato_missing_target must thread the &'static \
37390                         str label pointer-equal onto the `expected` field \
37391                         (label = {label:?})",
37392                    );
37393                }
37394                other => panic!("expected ContratoMissingTarget, got {other:?}"),
37395            }
37396        }
37397    }
37398
37399    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
37400    //
37401    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
37402    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
37403    // byte-equality mistake against the fixture default doesn't silently
37404    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
37405    // triple + expected-label envelope on
37406    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
37407    // struct_literal_wrap` (17dd504, host + reason envelope on
37408    // `entrada_host_invalid`) / the four `LayoutError` family
37409    // equivalence pins.
37410    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
37411        ("cart".to_string(), "catalog".to_string())
37412    }
37413
37414    #[test]
37415    fn empty_wit_ctor_matches_struct_literal_wrap() {
37416        // Equivalence pin: the ctor produces byte-equal
37417        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
37418        // struct-literal on the same edge pair, so the fold cannot
37419        // silently drift on any future field-addition / reordering /
37420        // string-conversion tweak on the variant. Peer of the sibling
37421        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
37422        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
37423        // (17dd504) / the four `LayoutError` family equivalence pins.
37424        let (de, para) = contrato_empty_pair_ctor_fixture();
37425        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
37426        let struct_literal = AplicacaoError::EmptyWit { de, para };
37427        assert_eq!(lifted, struct_literal);
37428    }
37429
37430    #[test]
37431    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
37432        // Equivalence pin peer of the sibling
37433        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
37434        // paired `ContratoEndpointEmpty` variant of the same two-slot
37435        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
37436        let (de, para) = contrato_empty_pair_ctor_fixture();
37437        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
37438        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
37439        assert_eq!(lifted, struct_literal);
37440    }
37441
37442    #[test]
37443    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
37444        // Equivalence pin peer of the sibling
37445        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
37446        // above on the paired `ContratoSubjectEmpty` variant of the
37447        // same two-slot envelope shape.
37448        let (de, para) = contrato_empty_pair_ctor_fixture();
37449        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
37450        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
37451        assert_eq!(lifted, struct_literal);
37452    }
37453
37454    #[test]
37455    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
37456        // Equivalence pin peer of the sibling
37457        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
37458        // above on the paired `ContratoSlotEmpty` variant of the same
37459        // two-slot envelope shape.
37460        let (de, para) = contrato_empty_pair_ctor_fixture();
37461        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
37462        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
37463        assert_eq!(lifted, struct_literal);
37464    }
37465
37466    #[test]
37467    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
37468        // Routing pin: the `(de, para)` pair threads verbatim onto
37469        // same-named fields on all four generated ctors, no wrapper-
37470        // side lowercase / trim / re-order. Sweeps a non-default pair
37471        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
37472        // transformation surfaces here rather than at a downstream
37473        // diagnostic-shape drift. Sibling of
37474        // `contrato_target_ctors_route_edge_triple_through_verbatim`
37475        // (14b81d5) on the paired triple-carrying envelope and of
37476        // `entrada_host_invalid_ctor_routes_host_through_to_string`
37477        // (17dd504) on the sibling `{ host, reason }` envelope.
37478        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
37479        let variants: [(AplicacaoError, &'static str); 4] = [
37480            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
37481            (
37482                AplicacaoError::contrato_endpoint_empty(edge.clone()),
37483                "ContratoEndpointEmpty",
37484            ),
37485            (
37486                AplicacaoError::contrato_subject_empty(edge.clone()),
37487                "ContratoSubjectEmpty",
37488            ),
37489            (
37490                AplicacaoError::contrato_slot_empty(edge.clone()),
37491                "ContratoSlotEmpty",
37492            ),
37493        ];
37494        for (built, label) in variants {
37495            let (de, para) = match built {
37496                AplicacaoError::EmptyWit { de, para }
37497                | AplicacaoError::ContratoEndpointEmpty { de, para }
37498                | AplicacaoError::ContratoSubjectEmpty { de, para }
37499                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
37500                other => panic!("expected {label} pair variant, got {other:?}"),
37501            };
37502            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
37503            assert_eq!(
37504                para, "catalog-v2",
37505                "para field on {label} must thread verbatim",
37506            );
37507        }
37508    }
37509
37510    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
37511    //
37512    // Fixture edge pair + value + reason for every
37513    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
37514    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
37515    // fixed per-axis `<val>` / reason so a byte-equality mistake against
37516    // the fixture default doesn't silently pass. Peer of the sibling
37517    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
37518    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
37519    // (14b81d5, triple + expected-label envelope on
37520    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
37521    // struct_literal_wrap` (17dd504, host + reason envelope on
37522    // `entrada_host_invalid`).
37523    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
37524        ("cart".to_string(), "catalog".to_string())
37525    }
37526
37527    #[test]
37528    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
37529        // Equivalence pin: the ctor produces byte-equal
37530        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
37531        // open-coded struct-literal on the same
37532        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
37533        // silently drift on any future field-addition / reordering /
37534        // string-conversion tweak on the variant. Peer of the sibling
37535        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
37536        // (8580068) on the paired two-slot envelope of the same
37537        // `{ de, para, ... }` prefix, and of
37538        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
37539        // (17dd504) on the sibling `{ <field>: String, reason: String }`
37540        // two-slot envelope.
37541        let (de, para) = contrato_pair_value_reason_ctor_fixture();
37542        let endpoint = "/charge";
37543        let reason = "sample reason text";
37544        let lifted =
37545            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
37546        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
37547            de,
37548            para,
37549            endpoint: endpoint.to_string(),
37550            reason: reason.to_string(),
37551        };
37552        assert_eq!(lifted, struct_literal);
37553    }
37554
37555    #[test]
37556    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
37557        // Equivalence pin peer of the sibling
37558        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
37559        // above on the paired `ContratoSubjectInvalid` variant of the
37560        // same four-slot envelope shape the
37561        // `contrato_pair_value_reason_ctors!` macro closes.
37562        let (de, para) = contrato_pair_value_reason_ctor_fixture();
37563        let subject = "checkout.events.charge.failed";
37564        let reason = "sample reason text";
37565        let lifted =
37566            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
37567        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
37568            de,
37569            para,
37570            subject: subject.to_string(),
37571            reason: reason.to_string(),
37572        };
37573        assert_eq!(lifted, struct_literal);
37574    }
37575
37576    #[test]
37577    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
37578        // Equivalence pin peer of the sibling
37579        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
37580        // above on the paired `ContratoSlotInvalid` variant of the same
37581        // four-slot envelope shape.
37582        let (de, para) = contrato_pair_value_reason_ctor_fixture();
37583        let slot = "checkout/$orderId";
37584        let reason = "sample reason text";
37585        let lifted =
37586            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
37587        let struct_literal = AplicacaoError::ContratoSlotInvalid {
37588            de,
37589            para,
37590            slot: slot.to_string(),
37591            reason: reason.to_string(),
37592        };
37593        assert_eq!(lifted, struct_literal);
37594    }
37595
37596    #[test]
37597    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
37598        // Equivalence pin peer of the sibling
37599        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
37600        // on the paired `ContratoWitInvalid` variant of the same four-
37601        // slot envelope shape the `contrato_pair_value_reason_ctors!`
37602        // macro closes. Fold pinned this test lands with the last
37603        // `{ de, para, <field>: String, reason: String }` open-coded
37604        // struct-literal inside [`WitContract::target`] rewritten to
37605        // route through the macro-generated
37606        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
37607        // between the ctor and the pre-lift struct-literal trips this
37608        // pin ahead of any downstream diagnostic-shape drift on the
37609        // `:contratos :wit` axis.
37610        let (de, para) = contrato_pair_value_reason_ctor_fixture();
37611        let wit = "wasi-http/proxy";
37612        let reason = "sample reason text";
37613        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
37614        let struct_literal = AplicacaoError::ContratoWitInvalid {
37615            de,
37616            para,
37617            wit: wit.to_string(),
37618            reason: reason.to_string(),
37619        };
37620        assert_eq!(lifted, struct_literal);
37621    }
37622
37623    #[test]
37624    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
37625        // Routing pin: the `(de, para)` pair threads verbatim onto
37626        // same-named fields on all four generated ctors, no wrapper-
37627        // side lowercase / trim / re-order. Sweeps a non-default pair
37628        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
37629        // transformation surfaces here rather than at a downstream
37630        // diagnostic-shape drift. Sibling of
37631        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
37632        // (8580068) on the paired two-slot envelope and of
37633        // `contrato_target_ctors_route_edge_triple_through_verbatim`
37634        // (14b81d5) on the paired triple-carrying envelope.
37635        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
37636        let variants: [(AplicacaoError, &'static str); 4] = [
37637            (
37638                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
37639                "ContratoEndpointInvalid",
37640            ),
37641            (
37642                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
37643                "ContratoSubjectInvalid",
37644            ),
37645            (
37646                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
37647                "ContratoSlotInvalid",
37648            ),
37649            (
37650                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
37651                "ContratoWitInvalid",
37652            ),
37653        ];
37654        for (built, label) in variants {
37655            let (de, para) = match built {
37656                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
37657                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
37658                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
37659                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
37660                other => panic!("expected {label} pair variant, got {other:?}"),
37661            };
37662            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
37663            assert_eq!(
37664                para, "catalog-v2",
37665                "para field on {label} must thread verbatim",
37666            );
37667        }
37668    }
37669
37670    #[test]
37671    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
37672        // Cross-arm invariance pin — the four ctors all route
37673        // `reason: impl Into<String>` verbatim onto their respective
37674        // typed variants through the shared
37675        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
37676        // pair (`&str` literal, `format!` output) against every ctor to
37677        // pin that no per-arm wrapper transformation drifted in against
37678        // the uniform macro-generated body. Peer of
37679        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
37680        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
37681        let edge = || ("cart".to_string(), "catalog".to_string());
37682        let via_literal = "literal reason text";
37683        let via_format = format!("{} reason text", "literal");
37684        assert_eq!(
37685            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
37686            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
37687        );
37688        assert_eq!(
37689            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
37690            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
37691        );
37692        assert_eq!(
37693            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
37694            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
37695        );
37696        assert_eq!(
37697            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
37698            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
37699        );
37700    }
37701
37702    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
37703    //
37704    // Fail-before-pass-after pins for the standalone
37705    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
37706    // (see the paired doc-block above the ctor definition) — the fold of
37707    // the last open-coded three-slot `{ de, para, endpoint: <val>
37708    // .to_string() }` struct-literal inside [`WitContract::target`]'s
37709    // HTTP-arm leading-slash gate onto one substrate primitive on the
37710    // envelope. A byte-mismatched ctor body would trip the equivalence
37711    // pin first, ahead of any downstream diagnostic-shape drift.
37712    //
37713    // Peer of the sibling standalone-ctor equivalence pins on the peer
37714    // one-off variants across caixa-core:
37715    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
37716    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
37717    // on the paired two-slot and four-slot per-`:contratos :endpoint`
37718    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
37719    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
37720    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
37721    // reason }` two- and three-slot envelopes; the
37722    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
37723    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
37724    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
37725        ("cart".to_string(), "catalog".to_string())
37726    }
37727
37728    #[test]
37729    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
37730        // Equivalence pin: the ctor produces byte-equal
37731        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
37732        // open-coded struct-literal on the same `(edge_pair, endpoint)`
37733        // pair, so the fold cannot silently drift on any future
37734        // field-addition / reordering / string-conversion tweak on the
37735        // variant. Same equivalence-pin shape as the sibling
37736        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
37737        // (8580068) on the paired two-slot envelope and
37738        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
37739        // (14e13f1) on the paired four-slot envelope of the same
37740        // `{ de, para, ... }`-prefix `:endpoint` axis.
37741        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
37742        let endpoint = "charge";
37743        let lifted =
37744            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
37745        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
37746            de,
37747            para,
37748            endpoint: endpoint.to_string(),
37749        };
37750        assert_eq!(lifted, struct_literal);
37751    }
37752
37753    #[test]
37754    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
37755        // Routing pin on the `(de, para)` axis: sweep a non-default
37756        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
37757        // lowercase / trim / re-order surfaces here rather than at a
37758        // downstream diagnostic-shape drift. Peer of
37759        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
37760        // (8580068) on the paired two-slot envelope and
37761        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
37762        // (14e13f1) on the paired four-slot envelope of the same
37763        // `{ de, para, ... }`-prefix `:contratos` axis.
37764        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
37765        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
37766        match built {
37767            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
37768                assert_eq!(de, "cart-svc", "de field must thread verbatim");
37769                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
37770            }
37771            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
37772        }
37773    }
37774
37775    #[test]
37776    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
37777        // Routing pin on the `endpoint: &str` axis: sweep a non-default
37778        // value (`"charge"` — no leading `/`, the exact shape the
37779        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
37780        // through the sole payload-carrier constructor axis so any
37781        // wrapper-side transformation on the `endpoint.to_string()`
37782        // one-field construction surfaces here rather than at a
37783        // downstream diagnostic-shape mismatch. Sibling of
37784        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
37785        // (14e13f1) on the sibling four-slot envelope's payload-carrier
37786        // routing pin.
37787        let edge = || ("cart".to_string(), "catalog".to_string());
37788        let via_literal = "charge";
37789        let via_string = String::from("charge");
37790        assert_eq!(
37791            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
37792            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
37793        );
37794    }
37795
37796    // ── contrato_self_loop standalone ctor pins ─────────────────────────
37797    //
37798    // Fail-before-pass-after pins for the standalone
37799    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
37800    // doc-block above the ctor definition) — the fold of the last
37801    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
37802    // <ct>.world_ref().to_string() }` struct-literal inside
37803    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
37804    // arm onto one substrate primitive on the [`AplicacaoError`]
37805    // envelope, projecting through the paired [`WitContract::source`] /
37806    // [`WitContract::world_ref`] scalar accessors on the substrate
37807    // primitive. A byte-mismatched ctor body would trip the equivalence
37808    // pin first, ahead of any downstream diagnostic-shape drift.
37809    //
37810    // Peer of the sibling standalone-ctor equivalence pins on the peer
37811    // one-off variants across caixa-core:
37812    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
37813    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
37814    // envelope, the sibling
37815    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
37816    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
37817    // the paired two-slot and four-slot per-`:contratos :endpoint`
37818    // envelopes, and the sibling
37819    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
37820    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
37821    fn contrato_self_loop_ctor_fixture() -> WitContract {
37822        WitContract {
37823            de: "cart".to_string(),
37824            para: "cart".to_string(),
37825            wit: "wasi:http/proxy".to_string(),
37826            endpoint: Some("/self".to_string()),
37827            subject: None,
37828            slot: None,
37829        }
37830    }
37831
37832    #[test]
37833    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
37834        // Equivalence pin: the ctor produces byte-equal
37835        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
37836        // struct-literal that read the same two fields through
37837        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
37838        // any future field-addition / reordering / string-conversion
37839        // tweak on the variant. Same equivalence-pin shape as the
37840        // sibling `contrato_endpoint_not_absolute_ctor_matches_
37841        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
37842        // per-`:contratos :endpoint` envelope.
37843        let contract = contrato_self_loop_ctor_fixture();
37844        let lifted = AplicacaoError::contrato_self_loop(&contract);
37845        let struct_literal = AplicacaoError::ContratoSelfLoop {
37846            caixa: contract.source().to_string(),
37847            wit: contract.world_ref().to_string(),
37848        };
37849        assert_eq!(lifted, struct_literal);
37850    }
37851
37852    #[test]
37853    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
37854        // Routing pin sweeping non-default `caixa` and `:wit` values
37855        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
37856        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
37857        // axes so any wrapper-side lowercase / trim / re-order surfaces
37858        // here rather than at a downstream diagnostic-shape drift.
37859        // Peer of the sibling
37860        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
37861        // (cdf1a2c) routing pin on the sibling three-slot envelope.
37862        let contract = WitContract {
37863            de: "catalog-v2".to_string(),
37864            para: "catalog-v2".to_string(),
37865            wit: "nats:pub-sub".to_string(),
37866            endpoint: None,
37867            subject: Some("orders.>".to_string()),
37868            slot: None,
37869        };
37870        let built = AplicacaoError::contrato_self_loop(&contract);
37871        match built {
37872            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
37873                assert_eq!(
37874                    caixa, "catalog-v2",
37875                    "caixa slot must thread WitContract::source() verbatim"
37876                );
37877                assert_eq!(
37878                    wit, "nats:pub-sub",
37879                    "wit slot must thread WitContract::world_ref() verbatim"
37880                );
37881            }
37882            other => panic!("expected ContratoSelfLoop, got {other:?}"),
37883        }
37884    }
37885
37886    #[test]
37887    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
37888        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
37889        // [`WitContract::source`] accessor (matching the pre-lift open-
37890        // coded body's field selection), not [`WitContract::destination`].
37891        // Under today's `WitContract::is_self_loop()`-gated call site
37892        // the two are equal by that predicate's own contract, but a
37893        // future consumer that constructs the ctor against a not-yet-
37894        // gated candidate contract — an M4
37895        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
37896        // checking a per-`(:de, :para)`-patched candidate before the
37897        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
37898        // resolver rejecting a self-edge introduced by a cluster-local
37899        // `:contratos` override — needs the pre-lift field selection
37900        // pinned so a silent `.destination()` swap at the ctor body
37901        // surfaces here rather than at a downstream diagnostic mis-
37902        // attribution far from the self-loop diagnostic's owner
37903        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
37904        // direction).
37905        //
37906        // Deliberately constructs a non-self-loop pair (`"cart" →
37907        // "catalog"`) so the two accessors yield distinct bytes on the
37908        // fixture — a `.destination()` swap at the ctor body would land
37909        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
37910        // the assertion here.
37911        let contract = WitContract {
37912            de: "cart".to_string(),
37913            para: "catalog".to_string(),
37914            wit: "wasi:http/proxy".to_string(),
37915            endpoint: Some("/charge".to_string()),
37916            subject: None,
37917            slot: None,
37918        };
37919        let built = AplicacaoError::contrato_self_loop(&contract);
37920        match built {
37921            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
37922                assert_eq!(
37923                    caixa, "cart",
37924                    "caixa slot must project WitContract::source() (not destination)"
37925                );
37926            }
37927            other => panic!("expected ContratoSelfLoop, got {other:?}"),
37928        }
37929    }
37930
37931    // Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
37932    // whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
37933    // family — the sole per-axis ctor projecting through both
37934    // [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
37935    // triple) and [`WitTarget::label`] (on the trailing `target` slot).
37936    // Equivalence pin locks the ctor body to the pre-lift struct-literal
37937    // shape under `PartialEq`, so any accessor-side field-selection drift
37938    // or per-arm wrapper transformation surfaces here as a build-time
37939    // test failure rather than at a downstream diagnostic-shape mismatch
37940    // far from the substrate primitive. Peer of the sibling
37941    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
37942    // equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
37943    // edge envelope's `WitContract`-projection ctor.
37944    #[test]
37945    fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
37946        let contract = contrato_self_loop_ctor_fixture();
37947        let target = contract.target_projected();
37948        let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
37949        let (de, para, wit) = contract.edge_triple();
37950        let struct_literal = AplicacaoError::ContratoDuplicate {
37951            de,
37952            para,
37953            wit,
37954            target: target.label(),
37955        };
37956        assert_eq!(lifted, struct_literal);
37957    }
37958
37959    // Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
37960    // the paired [`WitContract::edge_triple`] projection's three axes
37961    // (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
37962    // the `target` axis all yield distinct bytes on the fixture — any
37963    // wrapper-side re-order / accessor-swap on the four axes surfaces
37964    // here rather than at a downstream diagnostic-shape drift. Peer of
37965    // the sibling
37966    // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
37967    // (b30edfe) routing pin on the paired two-slot envelope.
37968    #[test]
37969    fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
37970        let contract = WitContract {
37971            de: "cart".to_string(),
37972            para: "catalog".to_string(),
37973            wit: "wasi:http/proxy".to_string(),
37974            endpoint: Some("/charge".to_string()),
37975            subject: None,
37976            slot: None,
37977        };
37978        let target = contract.target_projected();
37979        let built = AplicacaoError::contrato_duplicate(&contract, &target);
37980        match built {
37981            AplicacaoError::ContratoDuplicate {
37982                de,
37983                para,
37984                wit,
37985                target,
37986            } => {
37987                assert_eq!(
37988                    de, "cart",
37989                    "de slot must thread WitContract::edge_triple().0 verbatim"
37990                );
37991                assert_eq!(
37992                    para, "catalog",
37993                    "para slot must thread WitContract::edge_triple().1 verbatim"
37994                );
37995                assert_eq!(
37996                    wit, "wasi:http/proxy",
37997                    "wit slot must thread WitContract::edge_triple().2 verbatim"
37998                );
37999                assert!(
38000                    target.contains("/charge"),
38001                    "target slot must project through WitTarget::label() \
38002                     (got target = {target:?})"
38003                );
38004            }
38005            other => panic!("expected ContratoDuplicate, got {other:?}"),
38006        }
38007    }
38008
38009    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
38010    // macro definition (see the paired doc-block above the macro definition)
38011    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
38012    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
38013    // struct-literal onto one substrate primitive. The four per-variant
38014    // equivalence pins below (fail-before-pass-after by construction — a
38015    // byte-mismatched macro arm would trip its equivalence pin first) lock
38016    // each generated constructor to its struct-literal peer under
38017    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
38018    // [`AplicacaoSpec::validate_membros`], and
38019    // [`validate_no_self_membership`] on that variant produces a byte-equal
38020    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
38021    // cross-axis pin that follows (non-default caixa name) routes the sole
38022    // constructor input axis through `.to_string()`, so the fold does not
38023    // silently collapse onto a fixed name.
38024    //
38025    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
38026    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
38027    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
38028    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
38029    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
38030    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
38031    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
38032    // of the peer M2 `:behavior` envelope fold (67c31ec,
38033    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
38034    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
38035    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
38036
38037    #[test]
38038    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
38039        assert_eq!(
38040            AplicacaoError::contrato_member_missing("cart"),
38041            AplicacaoError::ContratoMemberMissing {
38042                caixa: "cart".to_string(),
38043            },
38044            "generated contrato_member_missing ctor must produce byte-equal \
38045             AplicacaoError to the open-coded struct-literal wrap on the \
38046             same &str fixture",
38047        );
38048    }
38049
38050    #[test]
38051    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
38052        assert_eq!(
38053            AplicacaoError::membro_versao_empty("cart"),
38054            AplicacaoError::MembroVersaoEmpty {
38055                caixa: "cart".to_string(),
38056            },
38057            "generated membro_versao_empty ctor must produce byte-equal \
38058             AplicacaoError to the open-coded struct-literal wrap on the \
38059             same &str fixture",
38060        );
38061    }
38062
38063    #[test]
38064    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
38065        assert_eq!(
38066            AplicacaoError::membro_duplicate("cart"),
38067            AplicacaoError::MembroDuplicate {
38068                caixa: "cart".to_string(),
38069            },
38070            "generated membro_duplicate ctor must produce byte-equal \
38071             AplicacaoError to the open-coded struct-literal wrap on the \
38072             same &str fixture",
38073        );
38074    }
38075
38076    #[test]
38077    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
38078        assert_eq!(
38079            AplicacaoError::membro_is_self_aplicacao("checkout"),
38080            AplicacaoError::MembroIsSelfAplicacao {
38081                caixa: "checkout".to_string(),
38082            },
38083            "generated membro_is_self_aplicacao ctor must produce byte-equal \
38084             AplicacaoError to the open-coded struct-literal wrap on the \
38085             same &str fixture",
38086        );
38087    }
38088
38089    #[test]
38090    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
38091        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
38092        // &str`) through a non-default fixture name against every generated
38093        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
38094        // wrapper-side lowercase / trim / truncate / re-order on the
38095        // `caixa.to_string()` sole-field construction surfaces here rather
38096        // than at a downstream diagnostic-shape mismatch. Peer of the
38097        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
38098        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
38099        // envelope (db09650), extended here onto the peer `AplicacaoError`
38100        // `{ caixa: String }` envelope so every substrate-primitive ctor
38101        // family in caixa-core carrying a single-slot `{ caixa: String }`
38102        // shape guarantees the sole-field construction routes the caller's
38103        // `&str` through `.to_string()` verbatim.
38104        let name = "cache-v2";
38105        assert_eq!(
38106            AplicacaoError::contrato_member_missing(name),
38107            AplicacaoError::ContratoMemberMissing {
38108                caixa: name.to_string(),
38109            },
38110        );
38111        assert_eq!(
38112            AplicacaoError::membro_versao_empty(name),
38113            AplicacaoError::MembroVersaoEmpty {
38114                caixa: name.to_string(),
38115            },
38116        );
38117        assert_eq!(
38118            AplicacaoError::membro_duplicate(name),
38119            AplicacaoError::MembroDuplicate {
38120                caixa: name.to_string(),
38121            },
38122        );
38123        assert_eq!(
38124            AplicacaoError::membro_is_self_aplicacao(name),
38125            AplicacaoError::MembroIsSelfAplicacao {
38126                caixa: name.to_string(),
38127            },
38128        );
38129    }
38130
38131    #[test]
38132    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
38133        assert_eq!(
38134            AplicacaoError::entrada_path_not_absolute("api/cart"),
38135            AplicacaoError::EntradaPathNotAbsolute {
38136                path: "api/cart".to_string(),
38137            },
38138            "generated entrada_path_not_absolute ctor must produce byte-equal \
38139             AplicacaoError to the open-coded struct-literal wrap on the \
38140             same &str fixture",
38141        );
38142    }
38143
38144    #[test]
38145    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
38146        assert_eq!(
38147            AplicacaoError::entrada_path_duplicate("/api/cart"),
38148            AplicacaoError::EntradaPathDuplicate {
38149                path: "/api/cart".to_string(),
38150            },
38151            "generated entrada_path_duplicate ctor must produce byte-equal \
38152             AplicacaoError to the open-coded struct-literal wrap on the \
38153             same &str fixture",
38154        );
38155    }
38156
38157    // ── membro_versao_invalid ctor pins ────────────────────────────────
38158    //
38159    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
38160    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
38161    // produces an `AplicacaoError` structurally identical to the pre-lift
38162    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
38163    // versao.to_string(), reason: reason.into() }` open-coded three-slot
38164    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
38165    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
38166    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
38167    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
38168    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
38169    // extended here onto the paired per-`:membros :versao` axis on the
38170    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
38171    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
38172    // typed-error surface guarantee the shared three-field construction
38173    // routes through one substrate primitive per envelope.
38174
38175    #[test]
38176    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
38177        let caixa = "cart";
38178        let versao = "not-a-req";
38179        let reason = "sample reason text";
38180        assert_eq!(
38181            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
38182            AplicacaoError::MembroVersaoInvalid {
38183                caixa: caixa.to_string(),
38184                versao: versao.to_string(),
38185                reason: reason.to_string(),
38186            },
38187            "lifted membro_versao_invalid ctor must produce byte-equal \
38188             AplicacaoError to the open-coded struct-literal wrap on the \
38189             same (&str, &str, reason) fixture",
38190        );
38191    }
38192
38193    #[test]
38194    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
38195        // Cross-axis pin: sweep the two `&str`-shaped constructor input
38196        // axes (`caixa`, `versao`) through non-default fixtures so any
38197        // wrapper-side lowercase / trim / truncate / re-order on either
38198        // `.to_string()` field construction surfaces here rather than at
38199        // a downstream diagnostic-shape mismatch. Peer of the sibling
38200        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
38201        // routing pin on the peer `SupervisorError` envelope.
38202        let caixa = "Cart-V2";
38203        let versao = "0.1.0-alpha+build.42";
38204        let reason = "constructed reason";
38205        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
38206        let AplicacaoError::MembroVersaoInvalid {
38207            caixa: got_caixa,
38208            versao: got_versao,
38209            reason: got_reason,
38210        } = err
38211        else {
38212            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
38213        };
38214        assert_eq!(got_caixa, caixa.to_string());
38215        assert_eq!(got_versao, versao.to_string());
38216        assert_eq!(got_reason, reason.to_string());
38217    }
38218
38219    #[test]
38220    fn membro_versao_invalid_ctor_routes_reason_through_into() {
38221        // Route pin: the `reason: impl Into<String>` bound accepts both
38222        // `&str` literals and `format!(…)` / `String` outputs verbatim,
38223        // matching the sibling
38224        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
38225        // routing pin on the peer `SupervisorError::child_versao_invalid`.
38226        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
38227        // `require_valid_versao_requirement`-delivered `reason` closure
38228        // parameter (typed `String`) picks the ctor up without a per-arm
38229        // wrapper transformation, and every future consumer that
38230        // constructs the variant from a `format!(…)` reason surfaces
38231        // byte-equal to the `&str`-literal path.
38232        let caixa = "cart";
38233        let versao = "not-a-req";
38234        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
38235        let from_format =
38236            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
38237        let from_string =
38238            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
38239        assert_eq!(from_literal, from_format);
38240        assert_eq!(from_literal, from_string);
38241    }
38242
38243    #[test]
38244    fn aplicacao_path_only_ctors_route_path_through_to_string() {
38245        // Cross-axis pin: sweep the sole constructor input axis (`path:
38246        // &str`) through a non-default fixture path against every generated
38247        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
38248        // wrapper-side lowercase / trim / truncate / re-order on the
38249        // `path.to_string()` sole-field construction surfaces here rather
38250        // than at a downstream diagnostic-shape mismatch. Peer of the
38251        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
38252        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
38253        // envelope (d9f6867), extended here onto the sibling
38254        // `AplicacaoError` `{ path: String }` envelope so every substrate-
38255        // primitive ctor family in caixa-core carrying a single-slot
38256        // `{ <slot>: String }` shape guarantees the sole-field construction
38257        // routes the caller's `&str` through `.to_string()` verbatim.
38258        let path = "/api/v2/checkout";
38259        assert_eq!(
38260            AplicacaoError::entrada_path_not_absolute(path),
38261            AplicacaoError::EntradaPathNotAbsolute {
38262                path: path.to_string(),
38263            },
38264        );
38265        assert_eq!(
38266            AplicacaoError::entrada_path_duplicate(path),
38267            AplicacaoError::EntradaPathDuplicate {
38268                path: path.to_string(),
38269            },
38270        );
38271    }
38272
38273    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
38274    //
38275    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
38276    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
38277    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
38278    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
38279    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
38280    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
38281    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
38282    // substitution on any one variant surfaces here rather than at a downstream
38283    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
38284    // pins on `aplicacao_field_reason_ctors!` (981060b),
38285    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
38286    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
38287    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
38288    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
38289    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
38290    // per-envelope ctor-macro pins.
38291
38292    #[test]
38293    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
38294        let timeout = Duration::from_micros(1_500);
38295        assert_eq!(
38296            AplicacaoError::policy_timeout_not_canonical(timeout),
38297            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
38298            "generated policy_timeout_not_canonical ctor must produce byte-equal \
38299             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
38300             struct-literal wrap on the same `Copy`-`Duration` fixture",
38301        );
38302    }
38303
38304    #[test]
38305    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
38306        let timeout = Duration::from_secs(3_601);
38307        assert_eq!(
38308            AplicacaoError::policy_timeout_exceeds_cap(timeout),
38309            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
38310            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
38311             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
38312             struct-literal wrap on the same `Copy`-`Duration` fixture",
38313        );
38314    }
38315
38316    #[test]
38317    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
38318        let retries = 47_u32;
38319        assert_eq!(
38320            AplicacaoError::policy_retries_exceeds_cap(retries),
38321            AplicacaoError::PolicyRetriesExceedsCap { retries },
38322            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
38323             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
38324             struct-literal wrap on the same `Copy`-`u32` fixture",
38325        );
38326    }
38327
38328    #[test]
38329    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
38330        let max_failures = 1_337_u32;
38331        assert_eq!(
38332            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
38333            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
38334            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
38335             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
38336             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
38337        );
38338    }
38339
38340    #[test]
38341    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
38342        let window = Duration::from_micros(500);
38343        assert_eq!(
38344            AplicacaoError::policy_breaker_window_not_canonical(window),
38345            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
38346            "generated policy_breaker_window_not_canonical ctor must produce \
38347             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
38348             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
38349        );
38350    }
38351
38352    #[test]
38353    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
38354        let window = Duration::from_secs(3_700);
38355        assert_eq!(
38356            AplicacaoError::policy_breaker_window_exceeds_cap(window),
38357            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
38358            "generated policy_breaker_window_exceeds_cap ctor must produce \
38359             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
38360             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
38361        );
38362    }
38363
38364    #[test]
38365    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
38366        let rate = 1_000_001_u32;
38367        assert_eq!(
38368            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
38369            AplicacaoError::PolicyRateLimitExceedsCap { rate },
38370            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
38371             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
38372             struct-literal wrap on the same `Copy`-`u32` fixture",
38373        );
38374    }
38375
38376    #[test]
38377    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
38378        let window = Duration::from_secs(15);
38379        assert_eq!(
38380            AplicacaoError::policy_rate_limit_window_not_canonical(window),
38381            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
38382            "generated policy_rate_limit_window_not_canonical ctor must produce \
38383             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
38384             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
38385             fixture",
38386        );
38387    }
38388
38389    #[test]
38390    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
38391        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
38392        // constructor input axis through a non-default `Copy` fixture against
38393        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
38394        // wrapper-side silent `.into()` / silent constant-substitution / silent
38395        // field re-name away from the canonical `timeout | retries |
38396        // max_failures | window | rate` axes on any one variant, or a
38397        // `Duration | u32` axis silently rerouted through some other `Copy`
38398        // coercion, surfaces here rather than at a downstream per-`:politicas`
38399        // diagnostic-shape drift. Peer of the sibling
38400        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
38401        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
38402        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
38403        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
38404        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
38405        // families, extended here onto the last M3 per-`:politicas` per-axis
38406        // `AplicacaoError` variant family folded onto a substrate primitive.
38407        //
38408        // Fixtures picked out of each variant's accept-set boundary rather
38409        // than the default value so a silent constant-substitution to `0` /
38410        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
38411        // structural-equality assertion. The two `Duration` fixtures pick the
38412        // sub-millisecond and above-cap ends respectively; the three `u32`
38413        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
38414        // `rate` respectively (each variant's cap sits well below the fixture
38415        // so the pre-lift struct-literal wrap the fixture is compared against
38416        // is the same shape the pre-lift wire-up produced).
38417        let sub_ms = Duration::from_micros(1_500);
38418        let above_hour = Duration::from_secs(3_700);
38419        let non_canonical_rl_window = Duration::from_secs(15);
38420        assert_eq!(
38421            AplicacaoError::policy_timeout_not_canonical(sub_ms),
38422            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
38423        );
38424        assert_eq!(
38425            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
38426            AplicacaoError::PolicyTimeoutExceedsCap {
38427                timeout: above_hour,
38428            },
38429        );
38430        assert_eq!(
38431            AplicacaoError::policy_retries_exceeds_cap(47),
38432            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
38433        );
38434        assert_eq!(
38435            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
38436            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
38437                max_failures: 1_337,
38438            },
38439        );
38440        assert_eq!(
38441            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
38442            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
38443        );
38444        assert_eq!(
38445            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
38446            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
38447        );
38448        assert_eq!(
38449            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
38450            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
38451        );
38452        assert_eq!(
38453            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
38454            AplicacaoError::PolicyRateLimitWindowNotCanonical {
38455                window: non_canonical_rl_window,
38456            },
38457        );
38458    }
38459
38460    #[test]
38461    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
38462        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
38463        // every generated ctor `const fn` so a caller can pin an
38464        // `AplicacaoError` at compile time — the same zero-runtime-work
38465        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
38466        // closure carried on its `Copy`-pass-through construction path (no
38467        // `.to_string()` / `.into()` allocation, no branching). If any future
38468        // edit silently drops the `const` qualifier from the macro body the
38469        // per-arm `const` bindings below fail to compile, which surfaces the
38470        // regression at the substrate-primitive definition rather than at
38471        // some downstream consumer that had come to rely on the `const`-
38472        // constructibility. Peer of the sibling per-variant
38473        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
38474        // equality axis; this pin closes the compile-time-const axis on the
38475        // same generated family.
38476        const TIMEOUT_NC: AplicacaoError =
38477            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
38478        const TIMEOUT_CAP: AplicacaoError =
38479            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
38480        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
38481        const MAX_FAIL_CAP: AplicacaoError =
38482            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
38483        const CB_WIN_NC: AplicacaoError =
38484            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
38485        const CB_WIN_CAP: AplicacaoError =
38486            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
38487        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
38488        const RL_WIN_NC: AplicacaoError =
38489            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
38490        assert!(matches!(
38491            TIMEOUT_NC,
38492            AplicacaoError::PolicyTimeoutNotCanonical { .. }
38493        ));
38494        assert!(matches!(
38495            TIMEOUT_CAP,
38496            AplicacaoError::PolicyTimeoutExceedsCap { .. }
38497        ));
38498        assert!(matches!(
38499            RETRIES_CAP,
38500            AplicacaoError::PolicyRetriesExceedsCap { .. }
38501        ));
38502        assert!(matches!(
38503            MAX_FAIL_CAP,
38504            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
38505        ));
38506        assert!(matches!(
38507            CB_WIN_NC,
38508            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
38509        ));
38510        assert!(matches!(
38511            CB_WIN_CAP,
38512            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
38513        ));
38514        assert!(matches!(
38515            RATE_CAP,
38516            AplicacaoError::PolicyRateLimitExceedsCap { .. }
38517        ));
38518        assert!(matches!(
38519            RL_WIN_NC,
38520            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
38521        ));
38522    }
38523
38524    // Per-variant equivalence + routing pins for the
38525    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
38526    // (see the paired doc-block above the ctor definition) — the
38527    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
38528    // Self` inherent constructor folds the uniform
38529    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
38530    // one-field struct-literal onto one substrate primitive. Same
38531    // shape as the sibling
38532    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
38533    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
38534    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
38535    // ctors — extended here onto the single-slot per-`:placement
38536    // :clusters` dedup-envelope.
38537
38538    #[test]
38539    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
38540        // Equivalence pin: the ctor produces byte-equal
38541        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
38542        // open-coded struct-literal that read the same field through
38543        // `c.clone()` at the caller site inside
38544        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
38545        // field-addition / reordering / string-conversion tweak on the
38546        // variant.
38547        let cluster = "rio";
38548        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
38549        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
38550            cluster: cluster.to_string(),
38551        };
38552        assert_eq!(lifted, struct_literal);
38553    }
38554
38555    #[test]
38556    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
38557        // Routing pin: sweep the sole constructor input axis
38558        // (`cluster: &str`) through a non-default fixture name so any
38559        // wrapper-side lowercase / trim / truncate / re-order on the
38560        // `cluster.to_string()` sole-field construction surfaces here
38561        // rather than at a downstream diagnostic-shape mismatch. Peer of
38562        // the sibling
38563        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
38564        // (d9f6867) cross-axis pin on the sibling one-slot
38565        // `{ caixa: String }` envelope — extended here onto the sibling
38566        // `{ cluster: String }` envelope so the sole `String`-slot
38567        // construction routes the caller's `&str` through `.to_string()`
38568        // verbatim.
38569        let cluster = "sao-paulo-2";
38570        let built = AplicacaoError::placement_cluster_duplicate(cluster);
38571        match built {
38572            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
38573                assert_eq!(
38574                    c, cluster,
38575                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
38576                );
38577            }
38578            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
38579        }
38580    }
38581
38582    // Per-variant equivalence + routing pins for the
38583    // [`AplicacaoError::placement_without_clusters`] standalone ctor
38584    // (see the paired doc-block above the ctor definition) — the
38585    // generated `pub const fn placement_without_clusters(placement:
38586    // &Placement) -> Self` inherent constructor folds the uniform
38587    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
38588    // }` one-field `Copy`-pass-through struct-literal onto one substrate
38589    // primitive. Same shape as the sibling
38590    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
38591    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
38592    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
38593    // ctors — extended here onto the one-slot per-`:placement`
38594    // empty-clusters envelope.
38595
38596    #[test]
38597    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
38598        // Equivalence pin: the ctor produces byte-equal
38599        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
38600        // open-coded struct-literal that read the same field through
38601        // `p.estrategia()` at the caller site inside
38602        // [`AplicacaoSpec::validate_placement`]. Guards any future
38603        // field-addition / reordering / accessor-return tweak on the
38604        // variant.
38605        let placement = Placement {
38606            estrategia: PlacementStrategy::Replicated,
38607            clusters: vec![],
38608            affinity: None,
38609            shard_key: None,
38610        };
38611        let lifted = AplicacaoError::placement_without_clusters(&placement);
38612        let struct_literal = AplicacaoError::PlacementWithoutClusters {
38613            estrategia: placement.estrategia(),
38614        };
38615        assert_eq!(lifted, struct_literal);
38616    }
38617
38618    #[test]
38619    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
38620        // Routing pin: sweep the sole constructor input axis
38621        // (`placement: &Placement`) through every variant in the closed
38622        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
38623        // re-derivation / off-by-one arm-swap / stale-field read on the
38624        // `placement.estrategia()` sole-field projection surfaces here
38625        // rather than at a downstream diagnostic-shape mismatch. Peer of
38626        // the sibling
38627        // `validate_placement_reads_through_lifted_estrategia_accessor`
38628        // three-consumer coherence pin — extended here onto the ctor
38629        // itself so the accessor-projection posture is byte-witnessed at
38630        // the substrate primitive rather than only at the caller-site
38631        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
38632        // future addition to the closed accept-set surfaces as an
38633        // exhaustiveness gap on this iteration list.
38634        for estrategia in [
38635            PlacementStrategy::SingleNode,
38636            PlacementStrategy::Replicated,
38637            PlacementStrategy::Sharded,
38638        ] {
38639            let placement = Placement {
38640                estrategia,
38641                clusters: vec![],
38642                affinity: None,
38643                shard_key: None,
38644            };
38645            let built = AplicacaoError::placement_without_clusters(&placement);
38646            match built {
38647                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
38648                    assert_eq!(
38649                        e,
38650                        placement.estrategia(),
38651                        "estrategia slot must thread the caller's `Placement` verbatim \
38652                         through Placement::estrategia() — the ctor reads through the \
38653                         lifted accessor",
38654                    );
38655                    assert_eq!(
38656                        e, estrategia,
38657                        "estrategia slot must byte-equal the fixture-declared variant",
38658                    );
38659                }
38660                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
38661            }
38662        }
38663    }
38664
38665    #[test]
38666    fn placement_without_clusters_ctor_is_const_fn() {
38667        // Fail-before-pass-after pin on
38668        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
38669        // surface posture. The ctor threads the paired
38670        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
38671        // return through one `const fn` construction — any future
38672        // accidental downgrade to non-`const` (a `.clone()` on the
38673        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
38674        // materialization on the sibling non-`estrategia:` axis) fails
38675        // `placement_without_clusters_via_const_fn` at caixa-core build
38676        // time with E0015 (`cannot call non-const method`), strictly
38677        // stronger than a runtime `assert!`. Sibling of the peer
38678        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
38679        // posture on the sibling per-`:politicas` cap-scalar envelopes
38680        // and the peer [`Placement::estrategia`] const-fn accessor pin at
38681        // [`placement_estrategia_accessor_is_const_fn`] on the paired
38682        // substrate primitive.
38683        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
38684            AplicacaoError::placement_without_clusters(p)
38685        }
38686        let placement = Placement {
38687            estrategia: PlacementStrategy::Sharded,
38688            clusters: vec![],
38689            affinity: None,
38690            shard_key: Some("tenantId".into()),
38691        };
38692        assert_eq!(
38693            placement_without_clusters_via_const_fn(&placement),
38694            AplicacaoError::placement_without_clusters(&placement),
38695        );
38696    }
38697
38698    #[test]
38699    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
38700        // Equivalence pin: the ctor produces byte-equal
38701        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
38702        // open-coded struct-literal that read the same `:para` value
38703        // through `e.destination().to_string()` at the caller site
38704        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
38705        // field-addition / reordering / accessor-return tweak on the
38706        // variant. Sibling of the peer
38707        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
38708        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
38709        // pins on the sibling per-`:placement` envelope, and sibling of
38710        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
38711        // pin on the sibling per-`:membros :caixa` envelope.
38712        let entrada = Entrada {
38713            host: "checkout.quero.cloud".into(),
38714            para: "phantom-shim".into(),
38715            paths: vec!["/api".into()],
38716            port: 8080,
38717        };
38718        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
38719        let via_literal = AplicacaoError::EntradaMemberMissing {
38720            para: entrada.destination().to_string(),
38721        };
38722        assert_eq!(
38723            via_ctor, via_literal,
38724            "entrada_member_missing(&entrada) must byte-equal the open-coded \
38725             EntradaMemberMissing struct-literal on the same &Entrada fixture"
38726        );
38727        assert_eq!(
38728            via_ctor.to_string(),
38729            via_literal.to_string(),
38730            "Display byte-string must byte-equal the open-coded struct-literal"
38731        );
38732    }
38733
38734    #[test]
38735    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
38736        // Boundary-sweep pin on the ctor's substrate-primitive
38737        // projection: the `para` slot is stored verbatim from
38738        // [`Entrada::destination`] across a representative set of
38739        // `:entrada :para` byte-strings, so any wrapper-side silent
38740        // normalization, `.into()` divergence, accidental field
38741        // rebrand, or per-arm ctor divergence on the sole-field
38742        // projection surfaces at caixa-core build time rather than at
38743        // a downstream diagnostic consumer that reads `err.para` back
38744        // and gets a different value than the one it stored. Peer of
38745        // the sibling
38746        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
38747        // boundary-sweep pin on the sibling per-`:placement :shard-key`
38748        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
38749        // sweep on the sibling per-`:placement` empty-clusters envelope
38750        // — extended here onto the [`Entrada`]-borrow-projected sole
38751        // `para` slot on the sibling per-`:entrada :para` envelope. The
38752        // sweep list carries a mixed set (well-shaped phantom, hyphen-
38753        // digit tail, single-character floor, and the digit-start form
38754        // the peer `accepts_canonical_entrada_para_forms` positive-
38755        // control test also sweeps) so a future silent per-input
38756        // normalization surfaces on the arm that diverges.
38757        for para in [
38758            "phantom-shim",
38759            "cart-v2",
38760            "a",
38761            "c0",
38762            "3rd-party-shim",
38763            "x-1-2-3-4",
38764        ] {
38765            let entrada = Entrada {
38766                host: "checkout.quero.cloud".into(),
38767                para: para.into(),
38768                paths: vec!["/api".into()],
38769                port: 8080,
38770            };
38771            let err = AplicacaoError::entrada_member_missing(&entrada);
38772            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
38773                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
38774            };
38775            assert_eq!(
38776                stored_para,
38777                entrada.destination(),
38778                "para slot must round-trip verbatim through Entrada::destination() \
38779                 for {para:?}"
38780            );
38781            assert_eq!(
38782                stored_para, para,
38783                "para slot must byte-equal the fixture-declared value for {para:?}"
38784            );
38785        }
38786    }
38787
38788    #[test]
38789    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
38790        // End-to-end pin: the sole in-crate wire-up site
38791        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
38792        // routes through [`AplicacaoError::entrada_member_missing`] and
38793        // the observed `Err` byte-equals the ctor's output on the same
38794        // well-shaped-phantom `:para` fixture. A future silent de-lift
38795        // of the wire-up back to the open-coded struct-literal trips
38796        // this test at caixa-core build time rather than at a
38797        // downstream diagnostic consumer far from the wire-up commit.
38798        // Sibling of the peer
38799        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
38800        // end-to-end pin on the sibling per-`:placement :shard-key`
38801        // envelope, and sibling of the peer
38802        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
38803        // pattern-match pin on the same wire-up — extended here from a
38804        // `matches!` shape check to a byte-identity + Display parity
38805        // route through the ctor.
38806        let mut s = three_member_spec();
38807        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
38808        let observed = s.validate().unwrap_err();
38809        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
38810        assert_eq!(
38811            observed, expected,
38812            "validate_entrada's phantom-reference-arm Err must byte-equal \
38813             entrada_member_missing(&entrada)"
38814        );
38815        assert_eq!(
38816            observed.to_string(),
38817            expected.to_string(),
38818            "Display byte-string parity"
38819        );
38820    }
38821
38822    #[test]
38823    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
38824        // Equivalence pin: the ctor produces byte-equal
38825        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
38826        // struct-literal that stored the caller-side reconstructed
38827        // cycle path verbatim at the gray-arm cycle-close return inside
38828        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
38829        // field-addition / reordering / re-collect divergence on the
38830        // variant. Sibling of the peer
38831        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
38832        // (deeae5c) pin on the sibling per-`:entrada :para`
38833        // phantom-reference envelope, and sibling of the peer
38834        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
38835        // pin on the sibling per-`:placement` empty-clusters envelope.
38836        let cycle = vec![
38837            "cart".to_string(),
38838            "catalog".to_string(),
38839            "cart".to_string(),
38840        ];
38841        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
38842        let via_literal = AplicacaoError::ContratoCycle {
38843            cycle: cycle.clone(),
38844        };
38845        assert_eq!(
38846            via_ctor, via_literal,
38847            "contrato_cycle(cycle) must byte-equal the open-coded \
38848             ContratoCycle struct-literal on the same Vec<String> fixture"
38849        );
38850        assert_eq!(
38851            via_ctor.to_string(),
38852            via_literal.to_string(),
38853            "Display byte-string must byte-equal the open-coded struct-literal"
38854        );
38855    }
38856
38857    #[test]
38858    fn contrato_cycle_ctor_routes_path_verbatim() {
38859        // Boundary-sweep pin on the ctor's substrate-primitive
38860        // pass-through: the `cycle` slot is stored verbatim across a
38861        // representative set of reconstructed cycle paths (two-node
38862        // closed loop; three-node loop; long chain with repeated
38863        // interior nodes; a fixture whose first/last coincide by the
38864        // gray-arm's own append-target-once-more discipline), so any
38865        // wrapper-side silent normalization, dedup, sort, `.into()`
38866        // divergence, accidental field rebrand, or re-collect on the
38867        // sole-field pass-through surfaces at caixa-core build time
38868        // rather than at a downstream diagnostic consumer that reads
38869        // `err.cycle` back and gets a different value than the one it
38870        // stored. Peer of the sibling
38871        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
38872        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
38873        // :para` envelope — extended here onto the owned-[`Vec<String>`]
38874        // pass-through on the sibling per-`:contratos` cycle envelope.
38875        for cycle in [
38876            vec![
38877                "cart".to_string(),
38878                "catalog".to_string(),
38879                "cart".to_string(),
38880            ],
38881            vec![
38882                "cart".to_string(),
38883                "catalog".to_string(),
38884                "payment".to_string(),
38885                "cart".to_string(),
38886            ],
38887            vec![
38888                "a".to_string(),
38889                "b".to_string(),
38890                "c".to_string(),
38891                "d".to_string(),
38892                "b".to_string(),
38893            ],
38894            vec!["only".to_string(), "only".to_string()],
38895        ] {
38896            let err = AplicacaoError::contrato_cycle(cycle.clone());
38897            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
38898                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
38899            };
38900            assert_eq!(
38901                stored, cycle,
38902                "cycle slot must round-trip the caller-side Vec<String> verbatim \
38903                 for {cycle:?}"
38904            );
38905        }
38906    }
38907
38908    #[test]
38909    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
38910        // End-to-end pin: the sole in-crate wire-up site
38911        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
38912        // return) routes through [`AplicacaoError::contrato_cycle`] and
38913        // the observed `Err` byte-equals the ctor's output on the same
38914        // reconstructed cycle path. A future silent de-lift of the
38915        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
38916        // { cycle }` struct-literal trips this test at caixa-core build
38917        // time rather than at a downstream diagnostic consumer far from
38918        // the wire-up commit. Sibling of the peer
38919        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
38920        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
38921        // envelope, and sibling of the peer
38922        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
38923        // (14bafca) end-to-end pin on the sibling per-`:placement
38924        // :shard-key` envelope — extended here from a bare
38925        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
38926        // check to a byte-identity route through the ctor.
38927        let mut s = three_member_spec();
38928        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
38929        s.contratos = vec![
38930            contract_http("catalog", "cart", "/x"),
38931            contract_http("cart", "payment", "/y"),
38932            contract_http("payment", "catalog", "/z"),
38933        ];
38934        let observed = s.validate().unwrap_err();
38935        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
38936            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
38937        };
38938        let expected = AplicacaoError::contrato_cycle(cycle.clone());
38939        assert_eq!(
38940            observed, expected,
38941            "detect_sync_cycles's gray-arm Err must byte-equal \
38942             contrato_cycle(cycle) on the reconstructed cycle path"
38943        );
38944        assert_eq!(
38945            observed.to_string(),
38946            expected.to_string(),
38947            "Display byte-string parity"
38948        );
38949    }
38950
38951    // ── policy_breaker_window_below_timeout standalone ctor pins ────────
38952    //
38953    // Fail-before-pass-after pins for the standalone
38954    // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
38955    // ctor (see the paired doc-block above the ctor definition) — the
38956    // fold of the last open-coded two-slot `{ window: cb.window(),
38957    // timeout: t }` struct-literal inside
38958    // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
38959    // arm onto one substrate primitive on the [`AplicacaoError`]
38960    // envelope, projecting through the [`CircuitBreaker::window`] scalar
38961    // accessor on the substrate primitive. A byte-mismatched ctor body
38962    // would trip the equivalence pin first, ahead of any downstream
38963    // diagnostic-shape drift.
38964    //
38965    // Peer of the sibling standalone-ctor equivalence pins on the peer
38966    // per-envelope substrate-primitive-projection ctors across
38967    // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
38968    // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
38969    // per-`:contratos` self-edge envelope,
38970    // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
38971    // on the sibling `{ para: String }` one-slot per-`:entrada :para`
38972    // phantom-reference envelope, and
38973    // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
38974    // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
38975    // per-`:placement :shard-key` envelope.
38976
38977    #[test]
38978    fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
38979        // Equivalence pin: the ctor produces byte-equal
38980        // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
38981        // lift open-coded struct-literal that read the same two fields
38982        // through [`CircuitBreaker::window`] and the paired
38983        // `:politicas :timeout` destructure. Guards any future
38984        // field-addition / reordering / accessor-swap tweak on the
38985        // variant. Same equivalence-pin shape as the sibling
38986        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
38987        // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
38988        let cb = CircuitBreaker {
38989            max_failures: 5,
38990            window: Duration::from_secs(10),
38991        };
38992        let timeout = Duration::from_secs(30);
38993        let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
38994        let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
38995            window: cb.window(),
38996            timeout,
38997        };
38998        assert_eq!(
38999            via_ctor, via_literal,
39000            "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
39001             the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
39002             on the same Copy-Duration fixture"
39003        );
39004        assert_eq!(
39005            via_ctor.to_string(),
39006            via_literal.to_string(),
39007            "Display byte-string must byte-equal the open-coded struct-literal"
39008        );
39009    }
39010
39011    #[test]
39012    fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
39013        // Routing pin sweeping non-default `:circuit-breaker :window`
39014        // and `:timeout` pairs (below-boundary window / above-boundary
39015        // window; sub-second window / multi-minute timeout;
39016        // millisecond-precision fixture) through the paired
39017        // [`CircuitBreaker::window`] accessor and the direct `timeout`
39018        // parameter, so any wrapper-side silent normalization,
39019        // rounding, argument re-order, or accidental slot rebrand on
39020        // the two-slot pass-through surfaces at caixa-core build time
39021        // rather than at a downstream diagnostic consumer that reads
39022        // the two [`Duration`]s back and gets different values than
39023        // the ones it stored.
39024        //
39025        // Deliberately routes through a fixture whose `cb.window` and
39026        // `timeout` are distinct — a silent accessor swap
39027        // (`cb.max_failures` casting to `Duration` would fail to
39028        // compile; a hypothetical field-rename swap swapping the two
39029        // slots at the ctor body would land `timeout` in the `window`
39030        // slot instead of `cb.window()` and vice-versa, tripping the
39031        // per-field assertion here). Peer of the sibling
39032        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
39033        // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
39034        // envelope.
39035        for (max_failures, window, timeout) in [
39036            (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
39037            (
39038                1_u32,
39039                Duration::from_millis(29_999),
39040                Duration::from_secs(30),
39041            ),
39042            (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
39043            (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
39044        ] {
39045            let cb = CircuitBreaker {
39046                max_failures,
39047                window,
39048            };
39049            let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
39050            let AplicacaoError::PolicyBreakerWindowBelowTimeout {
39051                window: stored_window,
39052                timeout: stored_timeout,
39053            } = built
39054            else {
39055                panic!(
39056                    "policy_breaker_window_below_timeout must construct \
39057                     PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
39058                );
39059            };
39060            assert_eq!(
39061                stored_window, window,
39062                "window slot must thread CircuitBreaker::window() verbatim \
39063                 for cb={cb:?}/timeout={timeout:?}"
39064            );
39065            assert_eq!(
39066                stored_timeout, timeout,
39067                "timeout slot must thread the caller-side :timeout scalar verbatim \
39068                 for cb={cb:?}/timeout={timeout:?}"
39069            );
39070        }
39071    }
39072
39073    #[test]
39074    fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
39075        // End-to-end pin: the sole in-crate wire-up site
39076        // ([`MeshPolicy::first_cross_axis_violation`]'s
39077        // window-below-timeout arm) routes through
39078        // [`AplicacaoError::policy_breaker_window_below_timeout`] and
39079        // the observed `Err` byte-equals the ctor's output on the same
39080        // sub-boundary `(:window, :timeout)` fixture. A future silent
39081        // de-lift of the wire-up back to the open-coded
39082        // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
39083        // timeout }` struct-literal trips this test at caixa-core build
39084        // time rather than at a downstream diagnostic consumer far from
39085        // the wire-up commit. Sibling of the peer
39086        // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
39087        // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
39088        // cross-edge cycle envelope,
39089        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
39090        // (deeae5c) on the sibling per-`:entrada :para` phantom-
39091        // reference envelope, and
39092        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
39093        // (14bafca) on the sibling per-`:placement :shard-key`
39094        // envelope — extended here from a bare `matches!(err,
39095        // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
39096        // shape check to a byte-identity route through the ctor.
39097        let mut s = three_member_spec();
39098        s.politicas.timeout = Some(Duration::from_secs(30));
39099        s.politicas.circuit_breaker = Some(CircuitBreaker {
39100            max_failures: 5,
39101            window: Duration::from_secs(10),
39102        });
39103        let observed = s.validate().unwrap_err();
39104        let cb = s.politicas.circuit_breaker.unwrap();
39105        let timeout = s.politicas.timeout.unwrap();
39106        let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
39107        assert_eq!(
39108            observed, expected,
39109            "MeshPolicy::first_cross_axis_violation's window-below-timeout \
39110             arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
39111        );
39112        assert_eq!(
39113            observed.to_string(),
39114            expected.to_string(),
39115            "Display byte-string parity"
39116        );
39117    }
39118
39119    #[test]
39120    fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
39121        // Equivalence pin: the ctor produces byte-equal
39122        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
39123        // pre-lift open-coded struct-literal that read the same four fields
39124        // through [`RateLimit::rate`], [`RateLimit::window`],
39125        // [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
39126        // Guards any future field-addition / reordering / accessor-swap
39127        // tweak on the variant. Same equivalence-pin shape as the sibling
39128        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
39129        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
39130        // cross-axis envelope.
39131        let rl = RateLimit {
39132            rate: 1,
39133            window: Duration::from_secs(3600),
39134        };
39135        let cb = CircuitBreaker {
39136            max_failures: 5,
39137            window: Duration::from_secs(10),
39138        };
39139        let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
39140        let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
39141            rate: rl.rate(),
39142            rl_window: rl.window(),
39143            max_failures: cb.max_failures(),
39144            cb_window: cb.window(),
39145        };
39146        assert_eq!(
39147            via_ctor, via_literal,
39148            "policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
39149             byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
39150             struct-literal on the same Copy-(u32|Duration) fixture"
39151        );
39152        assert_eq!(
39153            via_ctor.to_string(),
39154            via_literal.to_string(),
39155            "Display byte-string must byte-equal the open-coded struct-literal"
39156        );
39157    }
39158
39159    #[test]
39160    fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
39161        // Routing pin sweeping non-default `(:rate, :rate-limit :window,
39162        // :max-failures, :circuit-breaker :window)` tuples across the
39163        // production-playbook starve band — Envoy 5-in-10s vs 1/hour,
39164        // sub-second breaker window, multi-minute rate-limit window,
39165        // multi-tenant per-cluster ratio — through the paired
39166        // [`RateLimit::rate`] / [`RateLimit::window`] /
39167        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
39168        // accessors, so any wrapper-side silent normalization, rounding,
39169        // argument re-order, or accidental slot rebrand on the four-slot
39170        // pass-through surfaces at caixa-core build time rather than at a
39171        // downstream diagnostic consumer that reads the four scalars back
39172        // and gets different values than the ones it stored.
39173        //
39174        // Deliberately routes through fixtures whose four scalars are
39175        // pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
39176        // cb_window`) — a hypothetical field-rename swap swapping any
39177        // two adjacent slots at the ctor body would land the value from
39178        // the wrong axis, tripping the per-field assertion here. Peer of
39179        // the sibling
39180        // `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
39181        // (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
39182        // :circuit-breaker)` cross-axis envelope.
39183        for (rate, rl_window, max_failures, cb_window) in [
39184            (
39185                1_u32,
39186                Duration::from_secs(3600),
39187                5_u32,
39188                Duration::from_secs(10),
39189            ),
39190            (4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
39191            (
39192                2_u32,
39193                Duration::from_millis(500),
39194                10_u32,
39195                Duration::from_secs(300),
39196            ),
39197            (
39198                7_u32,
39199                Duration::from_secs(120),
39200                42_u32,
39201                Duration::from_millis(750),
39202            ),
39203        ] {
39204            let rl = RateLimit {
39205                rate,
39206                window: rl_window,
39207            };
39208            let cb = CircuitBreaker {
39209                max_failures,
39210                window: cb_window,
39211            };
39212            let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
39213            let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
39214                rate: stored_rate,
39215                rl_window: stored_rl_window,
39216                max_failures: stored_max_failures,
39217                cb_window: stored_cb_window,
39218            } = built
39219            else {
39220                panic!(
39221                    "policy_breaker_cannot_trip_under_rate_limit must \
39222                     construct PolicyBreakerCannotTripUnderRateLimit for \
39223                     rl={rl:?}/cb={cb:?}"
39224                );
39225            };
39226            assert_eq!(
39227                stored_rate, rate,
39228                "rate slot must thread RateLimit::rate() verbatim for \
39229                 rl={rl:?}/cb={cb:?}"
39230            );
39231            assert_eq!(
39232                stored_rl_window, rl_window,
39233                "rl_window slot must thread RateLimit::window() verbatim \
39234                 for rl={rl:?}/cb={cb:?}"
39235            );
39236            assert_eq!(
39237                stored_max_failures, max_failures,
39238                "max_failures slot must thread CircuitBreaker::max_failures() \
39239                 verbatim for rl={rl:?}/cb={cb:?}"
39240            );
39241            assert_eq!(
39242                stored_cb_window, cb_window,
39243                "cb_window slot must thread CircuitBreaker::window() verbatim \
39244                 for rl={rl:?}/cb={cb:?}"
39245            );
39246        }
39247    }
39248
39249    #[test]
39250    fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
39251     {
39252        // End-to-end pin: the sole in-crate wire-up site
39253        // ([`MeshPolicy::first_cross_axis_violation`]'s
39254        // starve-under-rate-limit arm) routes through
39255        // [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
39256        // and the observed `Err` byte-equals the ctor's output on the same
39257        // token-bucket-starves-breaker fixture. A future silent de-lift of
39258        // the wire-up back to the open-coded
39259        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
39260        // rl_window, max_failures, cb_window }` struct-literal trips this
39261        // test at caixa-core build time rather than at a downstream
39262        // diagnostic consumer far from the wire-up commit. Sibling of the
39263        // peer
39264        // `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
39265        // (9b30c07) end-to-end pin on the sibling per-`(:timeout,
39266        // :circuit-breaker)` cross-axis envelope — extended here from a
39267        // bare `matches!(err,
39268        // AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
39269        // shape check to a byte-identity route through the ctor. Clears
39270        // `:timeout` so the sibling window-below-timeout arm does not
39271        // fire first on the ordering-precedent it holds over this arm.
39272        let mut s = three_member_spec();
39273        s.politicas.timeout = None;
39274        s.politicas.circuit_breaker = Some(CircuitBreaker {
39275            max_failures: 5,
39276            window: Duration::from_secs(10),
39277        });
39278        s.politicas.rate_limit = Some(RateLimit {
39279            rate: 1,
39280            window: Duration::from_secs(3600),
39281        });
39282        let observed = s.validate().unwrap_err();
39283        let rl = s.politicas.rate_limit.unwrap();
39284        let cb = s.politicas.circuit_breaker.unwrap();
39285        let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
39286        assert_eq!(
39287            observed, expected,
39288            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
39289             arm's Err must byte-equal \
39290             policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
39291        );
39292        assert_eq!(
39293            observed.to_string(),
39294            expected.to_string(),
39295            "Display byte-string parity"
39296        );
39297    }
39298
39299    #[test]
39300    fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
39301        // Equivalence pin: the ctor produces byte-equal
39302        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
39303        // pre-lift open-coded struct-literal that read the same two fields
39304        // through the bare `retries` destructure and
39305        // [`CircuitBreaker::max_failures`]. Guards any future field-addition
39306        // / reordering / accessor-swap tweak on the variant. Same
39307        // equivalence-pin shape as the sibling
39308        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
39309        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
39310        // second cross-axis envelope and
39311        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
39312        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
39313        // cross-axis envelope.
39314        let retries = 5_u32;
39315        let cb = CircuitBreaker {
39316            max_failures: 3,
39317            window: Duration::from_secs(60),
39318        };
39319        let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
39320        let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
39321            retries,
39322            max_failures: cb.max_failures(),
39323        };
39324        assert_eq!(
39325            via_ctor, via_literal,
39326            "policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
39327             byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
39328             struct-literal on the same Copy-u32 fixture"
39329        );
39330        assert_eq!(
39331            via_ctor.to_string(),
39332            via_literal.to_string(),
39333            "Display byte-string must byte-equal the open-coded struct-literal"
39334        );
39335    }
39336
39337    #[test]
39338    fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
39339        // Routing pin sweeping non-default `(retries, max_failures)` tuples
39340        // across the production-playbook retries-saturate band — Envoy 5
39341        // retries vs 3 max-failures, boundary retries==max_failures pair (a
39342        // rejecting arm on the strict-inequality invariant), multi-tenant
39343        // high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
39344        // through the paired bare-`retries` destructure and
39345        // [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
39346        // silent normalization, rounding, argument re-order, or accidental
39347        // slot rebrand on the two-slot pass-through surfaces at caixa-core
39348        // build time rather than at a downstream diagnostic consumer that
39349        // reads the two scalars back and gets different values than the ones
39350        // it stored.
39351        //
39352        // Deliberately routes through fixtures whose two scalars are
39353        // pairwise distinct (`retries ≠ max_failures` on every non-boundary
39354        // arm) — a hypothetical field-rename swap swapping the two slots at
39355        // the ctor body would land the value from the wrong axis, tripping
39356        // the per-field assertion here. Peer of the sibling
39357        // `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
39358        // (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
39359        // :circuit-breaker)` second cross-axis envelope.
39360        for (retries, max_failures) in [
39361            (5_u32, 3_u32),
39362            (3_u32, 3_u32),
39363            (100_u32, 1_u32),
39364            (7_u32, 42_u32),
39365        ] {
39366            let cb = CircuitBreaker {
39367                max_failures,
39368                window: Duration::from_secs(60),
39369            };
39370            let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
39371            let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
39372                retries: stored_retries,
39373                max_failures: stored_max_failures,
39374            } = built
39375            else {
39376                panic!(
39377                    "policy_breaker_trips_before_retries_exhausted must \
39378                     construct PolicyBreakerTripsBeforeRetriesExhausted for \
39379                     retries={retries}/cb={cb:?}"
39380                );
39381            };
39382            assert_eq!(
39383                stored_retries, retries,
39384                "retries slot must thread the bare-`retries` destructure \
39385                 verbatim for retries={retries}/cb={cb:?}"
39386            );
39387            assert_eq!(
39388                stored_max_failures, max_failures,
39389                "max_failures slot must thread CircuitBreaker::max_failures() \
39390                 verbatim for retries={retries}/cb={cb:?}"
39391            );
39392        }
39393    }
39394
39395    #[test]
39396    fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
39397     {
39398        // End-to-end pin: the sole in-crate wire-up site
39399        // ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
39400        // arm) routes through
39401        // [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
39402        // and the observed `Err` byte-equals the ctor's output on the same
39403        // retries-saturate fixture. A future silent de-lift of the wire-up
39404        // back to the open-coded
39405        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
39406        // max_failures }` struct-literal trips this test at caixa-core build
39407        // time rather than at a downstream diagnostic consumer far from the
39408        // wire-up commit. Sibling of the peer
39409        // `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
39410        // (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
39411        // :circuit-breaker)` second cross-axis envelope — extended here from
39412        // a bare `matches!(err,
39413        // AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
39414        // shape check to a byte-identity route through the ctor. Clears
39415        // `:timeout` and `:rate-limit` so the sibling window-below-timeout
39416        // and starve-under-rate-limit arms do not fire first on the
39417        // ordering-precedent they hold over this arm.
39418        let mut s = three_member_spec();
39419        s.politicas.timeout = None;
39420        s.politicas.rate_limit = None;
39421        s.politicas.retries = Some(5);
39422        s.politicas.circuit_breaker = Some(CircuitBreaker {
39423            max_failures: 3,
39424            window: Duration::from_secs(60),
39425        });
39426        let observed = s.validate().unwrap_err();
39427        let retries = s.politicas.retries.unwrap();
39428        let cb = s.politicas.circuit_breaker.unwrap();
39429        let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
39430        assert_eq!(
39431            observed, expected,
39432            "MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
39433             Err must byte-equal \
39434             policy_breaker_trips_before_retries_exhausted(retries, &cb)"
39435        );
39436        assert_eq!(
39437            observed.to_string(),
39438            expected.to_string(),
39439            "Display byte-string parity"
39440        );
39441    }
39442
39443    #[test]
39444    fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
39445        // Equivalence pin: the ctor produces byte-equal
39446        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
39447        // pre-lift open-coded struct-literal that read the same two fields
39448        // through the bare `retries` destructure and [`RateLimit::rate`].
39449        // Guards any future field-addition / reordering / accessor-swap
39450        // tweak on the variant. Same equivalence-pin shape as the sibling
39451        // `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
39452        // (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
39453        // third cross-axis envelope,
39454        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
39455        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
39456        // second cross-axis envelope, and
39457        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
39458        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
39459        // first cross-axis envelope.
39460        let retries = 3_u32;
39461        let rl = RateLimit {
39462            rate: 3,
39463            window: Duration::from_secs(1),
39464        };
39465        let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
39466        let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
39467            retries,
39468            rate: rl.rate(),
39469        };
39470        assert_eq!(
39471            via_ctor, via_literal,
39472            "policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
39473             byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
39474             struct-literal on the same Copy-u32 fixture"
39475        );
39476        assert_eq!(
39477            via_ctor.to_string(),
39478            via_literal.to_string(),
39479            "Display byte-string must byte-equal the open-coded struct-literal"
39480        );
39481    }
39482
39483    #[test]
39484    fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
39485        // Routing pin sweeping non-default `(retries, rate)` tuples across
39486        // the production-playbook rate-limit-starve band — boundary
39487        // `retries==rate` (a rejecting arm on the `>=` invariant stated as
39488        // `rate >= retries + 1`), one-below-boundary pair, multi-tenant
39489        // high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
39490        // through the paired bare-`retries` destructure and
39491        // [`RateLimit::rate`] accessor, so any wrapper-side silent
39492        // normalization, rounding, argument re-order, or accidental slot
39493        // rebrand on the two-slot pass-through surfaces at caixa-core
39494        // build time rather than at a downstream diagnostic consumer that
39495        // reads the two scalars back and gets different values than the
39496        // ones it stored.
39497        //
39498        // Deliberately routes through fixtures whose two scalars are
39499        // pairwise distinct on every non-boundary arm — a hypothetical
39500        // field-rename swap swapping the two slots at the ctor body would
39501        // land the value from the wrong axis, tripping the per-field
39502        // assertion here. Peer of the sibling
39503        // `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
39504        // (f54c539) routing pin on the sibling two-slot per-`(:retries,
39505        // :circuit-breaker)` third cross-axis envelope.
39506        for (retries, rate) in [
39507            (3_u32, 3_u32),
39508            (5_u32, 4_u32),
39509            (100_u32, 50_u32),
39510            (2_u32, POLICY_RATE_LIMIT_MAX),
39511        ] {
39512            let rl = RateLimit {
39513                rate,
39514                window: Duration::from_secs(1),
39515            };
39516            let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
39517            let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
39518                retries: stored_retries,
39519                rate: stored_rate,
39520            } = built
39521            else {
39522                panic!(
39523                    "policy_rate_limit_cannot_admit_retry_burst must \
39524                     construct PolicyRateLimitCannotAdmitRetryBurst for \
39525                     retries={retries}/rl={rl:?}"
39526                );
39527            };
39528            assert_eq!(
39529                stored_retries, retries,
39530                "retries slot must thread the bare-`retries` destructure \
39531                 verbatim for retries={retries}/rl={rl:?}"
39532            );
39533            assert_eq!(
39534                stored_rate, rate,
39535                "rate slot must thread RateLimit::rate() verbatim for \
39536                 retries={retries}/rl={rl:?}"
39537            );
39538        }
39539    }
39540
39541    #[test]
39542    fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
39543     {
39544        // End-to-end pin: the sole in-crate wire-up site
39545        // ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
39546        // limit arm) routes through
39547        // [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
39548        // and the observed `Err` byte-equals the ctor's output on the same
39549        // rate-limit-starve fixture. A future silent de-lift of the
39550        // wire-up back to the open-coded
39551        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
39552        // rate }` struct-literal trips this test at caixa-core build time
39553        // rather than at a downstream diagnostic consumer far from the
39554        // wire-up commit. Sibling of the peer
39555        // `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
39556        // (f54c539) end-to-end pin on the sibling per-`(:retries,
39557        // :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
39558        // and `:circuit-breaker` so the sibling window-below-timeout /
39559        // starve-under-rate-limit / trips-before-retries-exhausted arms
39560        // do not fire first on the ordering-precedent they hold over this
39561        // arm.
39562        let mut s = three_member_spec();
39563        s.politicas.timeout = None;
39564        s.politicas.circuit_breaker = None;
39565        s.politicas.retries = Some(5);
39566        s.politicas.rate_limit = Some(RateLimit {
39567            rate: 3,
39568            window: Duration::from_secs(1),
39569        });
39570        let observed = s.validate().unwrap_err();
39571        let retries = s.politicas.retries.unwrap();
39572        let rl = s.politicas.rate_limit.unwrap();
39573        let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
39574        assert_eq!(
39575            observed, expected,
39576            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
39577             Err must byte-equal \
39578             policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
39579        );
39580        assert_eq!(
39581            observed.to_string(),
39582            expected.to_string(),
39583            "Display byte-string parity"
39584        );
39585    }
39586}